http://stackoverflow.com/q/52308952
tagged with: pywin32
has body: I want to make a screenshot of an inactive window with win32gui. from PIL import ImageGrab import win32gui hwnd = win32gui.FindWindow(None, 'Calculator') win32gui.SetForegroundWindow(hwnd) dimensions = win32gui.GetWindowRect(hwnd) image = ImageGrab.grab(dimensions) image.show() But it is not working as expected. It grabs a screen region but it does not grab exactly where the window is. I have also tried resizing the calculator window but it doesn't help. My screen resolution is 1920*1080 if that is relevant. Screenshot: . Please help me if you have any solutions.
favorite count: 0
score: -1
has title: Python inactive screen capture
type: Question
has comment: http://stackoverflow.com/comment/91569295
tagged with: python
linked to: http://stackoverflow.com/q/3192232
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/51786794
type: UnansweredQuestion
tagged with: win32gui
has answer: http://stackoverflow.com/a/52314641
upvote count: 0

http://stackoverflow.com/comment/91726004
score: 0
type: QuestionComment
type: Comment
has text: How do you create your object?
comment on: http://stackoverflow.com/q/52390300

python
tags question: http://stackoverflow.com/q/52346313
tags question: http://stackoverflow.com/q/52296670
tags question: http://stackoverflow.com/q/52357542
tags question: http://stackoverflow.com/q/52396215
tags question: http://stackoverflow.com/q/52275204
tags question: http://stackoverflow.com/q/52301848
tags question: http://stackoverflow.com/q/52332969
tags question: http://stackoverflow.com/q/52314854
tags question: http://stackoverflow.com/q/52395750
tags question: http://stackoverflow.com/q/52345195
tags question: http://stackoverflow.com/q/52416387
tags question: http://stackoverflow.com/q/52335195
tags question: http://stackoverflow.com/q/52280334
tags question: http://stackoverflow.com/q/52281043
tags question: http://stackoverflow.com/q/52416580
tags question: http://stackoverflow.com/q/52359388
tags question: http://stackoverflow.com/q/52350642
tags question: http://stackoverflow.com/q/52297819
tags question: http://stackoverflow.com/q/52380423
tags question: http://stackoverflow.com/q/52357463
tags question: http://stackoverflow.com/q/52378927
tags question: http://stackoverflow.com/q/52390835
tags question: http://stackoverflow.com/q/52350352
tags question: http://stackoverflow.com/q/52352495
tags question: http://stackoverflow.com/q/52319375
tags question: http://stackoverflow.com/q/52278349
tags question: http://stackoverflow.com/q/52353686
tags question: http://stackoverflow.com/q/52354662
tags question: http://stackoverflow.com/q/52374725
tags question: http://stackoverflow.com/q/52359903
tags question: http://stackoverflow.com/q/52324538
tags question: http://stackoverflow.com/q/52417794
tags question: http://stackoverflow.com/q/52393056
tags question: http://stackoverflow.com/q/52359008
tags question: http://stackoverflow.com/q/52323887
tags question: http://stackoverflow.com/q/52362966
tags question: http://stackoverflow.com/q/52374062
tags question: http://stackoverflow.com/q/52401172
tags question: http://stackoverflow.com/q/52342814
tags question: http://stackoverflow.com/q/52284029
tags question: http://stackoverflow.com/q/52286719
tags question: http://stackoverflow.com/q/52369865
tags question: http://stackoverflow.com/q/52423018
tags question: http://stackoverflow.com/q/52280718
tags question: http://stackoverflow.com/q/52277303
tags question: http://stackoverflow.com/q/52280589
tags question: http://stackoverflow.com/q/52421996
tags question: http://stackoverflow.com/q/52359210
tags question: http://stackoverflow.com/q/52425741
tags question: http://stackoverflow.com/q/52355765
tags question: http://stackoverflow.com/q/52427137
tags question: http://stackoverflow.com/q/52406069
tags question: http://stackoverflow.com/q/52339143
tags question: http://stackoverflow.com/q/52379689
tags question: http://stackoverflow.com/q/52356956
tags question: http://stackoverflow.com/q/52304959
tags question: http://stackoverflow.com/q/52361941
tags question: http://stackoverflow.com/q/52390300
tags question: http://stackoverflow.com/q/52283346
tags question: http://stackoverflow.com/q/52394252
tags question: http://stackoverflow.com/q/52334602
tags question: http://stackoverflow.com/q/52349377
tags question: http://stackoverflow.com/q/52316455
tags question: http://stackoverflow.com/q/52342110
tags question: http://stackoverflow.com/q/52383017
tags question: http://stackoverflow.com/q/52391099
tags question: http://stackoverflow.com/q/52359905
tags question: http://stackoverflow.com/q/52322822
tags question: http://stackoverflow.com/q/52347116
tags question: http://stackoverflow.com/q/52414546
tags question: http://stackoverflow.com/q/52384362
tags question: http://stackoverflow.com/q/52411968
tags question: http://stackoverflow.com/q/52386447
tags question: http://stackoverflow.com/q/52300300
tags question: http://stackoverflow.com/q/52376693
tags question: http://stackoverflow.com/q/52342209
tags question: http://stackoverflow.com/q/52405995
tags question: http://stackoverflow.com/q/52336394
tags question: http://stackoverflow.com/q/52402822
tags question: http://stackoverflow.com/q/52387516

http://stackoverflow.com/q/52389487
tagged with: python
has comment: http://stackoverflow.com/comment/91727088
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91725683
has comment: http://stackoverflow.com/comment/91726794
has title: Pyspark Dataframe GroupBy Count is Different Every Time
has comment: http://stackoverflow.com/comment/91727792
type: Question
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/91726746
tagged with: pyspark
has comment: http://stackoverflow.com/comment/91724948
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/91728885
downvote count: 0
has body: I am new to pyspark so I feel like I'm missing something simple and stupid here but I am missing it. I read the contents of a parquet file into a spark dataframe. Then I groupby a binary column and count the results. The numbers are different every time. Is this an issue of syncing data between spark nodes or does this have something to do with the lazy execution or am I just missing some basic fundamental spark principle? I'm very confused by these results. df = spark.read.parquet(input_file) df = df.limit(2000) print(df.count()) print(df.groupBy('STATUS').count().collect()) print(df.groupBy('STATUS').count().collect()) print(df.groupBy('STATUS').count().collect()) &gt;&gt;&gt; 2000 &gt;&gt;&gt; [Row(STATUS=0, count=1613), Row(STATUS=1, count=387)] &gt;&gt;&gt; [Row(STATUS=0, count=1528), Row(STATUS=1, count=472)] &gt;&gt;&gt; [Row(STATUS=0, count=1646), Row(STATUS=1, count=354)] Below is the df schema: root |-- GRP_ID: long (nullable = true) |-- WEK_ID: long (nullable = true) |-- WEK_BGN_DT: string (nullable = true) |-- WEK_END_DT: string (nullable = true) |-- FEATURES: vector (nullable = true) |-- STATUS: long (nullable = true) I should also note that if I convert the spark dataframe to pandas and get a count, it works just fine: dfp = df.toPandas() print(dfp['STATUS'][dfp['STATUS'] == 0].count()) print(dfp['STATUS'][dfp['STATUS'] == 1].count()) print(dfp['STATUS'][dfp['STATUS'] == 0].count()) print(dfp['STATUS'][dfp['STATUS'] == 1].count()) print(dfp['STATUS'][dfp['STATUS'] == 0].count()) print(dfp['STATUS'][dfp['STATUS'] == 1].count()) &gt;&gt;&gt; 1494 &gt;&gt;&gt; 506 &gt;&gt;&gt; 1494 &gt;&gt;&gt; 506 &gt;&gt;&gt; 1494 &gt;&gt;&gt; 506
has comment: http://stackoverflow.com/comment/91726797
favorite count: 0
has comment: http://stackoverflow.com/comment/91726565

http://stackoverflow.com/a/52430010
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52429274
downvote count: 0
answers question: http://stackoverflow.com/q/52429274
type: AcceptedAnswer
score: 1
has comment: http://stackoverflow.com/comment/91803775
has body: Your don't need the break. Your function is returning always after one execution of the outer thread, even if no file is found in that iteration. Remove the breakand it will work. As an example, if you have just one file test_dir/a/b.txt, in the first run of the outer thread you have dirName = test_dir subdirList = ['a'] fileList = [] and in the second run: dirName = test_dir/a subdirList = [] fileList = ['b.txt'] so you want to continue until you find something in the fileList variable.

http://stackoverflow.com/q/52272983
favorite count: 0
has comment: http://stackoverflow.com/comment/91493221
has comment: http://stackoverflow.com/comment/91493160
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/52273035
has title: Execute Statement in Python error Name Not Defined
linked to: http://stackoverflow.com/q/1373164
answer count: 1
has comment: http://stackoverflow.com/comment/91493339
duplicate of: http://stackoverflow.com/q/1373164
downvote count: 3
type: UnansweredQuestion
score: -3
upvote count: 0
has comment: http://stackoverflow.com/comment/91493135
has comment: http://stackoverflow.com/comment/91493146
has body: I am trying to use a Python list comprehension to get the Variable Name SW1 to equal the string "sw1" but I keep getting an error saying sw1 not defined VarList = ["SW1"] VarListEnd = ["sw1"] list3 = [exec("%s="%x + "%s"%y) for x in VarList for y in VarListEnd] list3 How do I amend the exec statement because that is where I think the error is? Really appreciate your help. Thanks in advance.

http://stackoverflow.com/comment/91545885
comment on: http://stackoverflow.com/q/52296041
score: 1
has text: See my answer on the description of above here:https://stackoverflow.com/a/42230764/3374996
type: Comment
type: QuestionComment

pandas
tags question: http://stackoverflow.com/q/52286056
tags question: http://stackoverflow.com/q/52280499
tags question: http://stackoverflow.com/q/52297308
tags question: http://stackoverflow.com/q/52407351
tags question: http://stackoverflow.com/q/52356730
tags question: http://stackoverflow.com/q/52299571
tags question: http://stackoverflow.com/q/52405670
tags question: http://stackoverflow.com/q/52334479
tags question: http://stackoverflow.com/q/52312164
tags question: http://stackoverflow.com/q/52311730
tags question: http://stackoverflow.com/q/52388598
tags question: http://stackoverflow.com/q/52282194
tags question: http://stackoverflow.com/q/52355093
tags question: http://stackoverflow.com/q/52427662
tags question: http://stackoverflow.com/q/52299554
tags question: http://stackoverflow.com/q/52286114
tags question: http://stackoverflow.com/q/52427024
tags question: http://stackoverflow.com/q/52319375
tags question: http://stackoverflow.com/q/52417794
tags question: http://stackoverflow.com/q/52279646
tags question: http://stackoverflow.com/q/52367518
tags question: http://stackoverflow.com/q/52388005
tags question: http://stackoverflow.com/q/52419849
tags question: http://stackoverflow.com/q/52389892
tags question: http://stackoverflow.com/q/52388154
tags question: http://stackoverflow.com/q/52341463
tags question: http://stackoverflow.com/q/52383459
tags question: http://stackoverflow.com/q/52323069
tags question: http://stackoverflow.com/q/52302060
tags question: http://stackoverflow.com/q/52425038
tags question: http://stackoverflow.com/q/52413585
tags question: http://stackoverflow.com/q/52422610
tags question: http://stackoverflow.com/q/52419170
tags question: http://stackoverflow.com/q/52313838
tags question: http://stackoverflow.com/q/52283037
tags question: http://stackoverflow.com/q/52301123
tags question: http://stackoverflow.com/q/52343540
tags question: http://stackoverflow.com/q/52402473
tags question: http://stackoverflow.com/q/52365440
tags question: http://stackoverflow.com/q/52338355
tags question: http://stackoverflow.com/q/52320919
tags question: http://stackoverflow.com/q/52307410
tags question: http://stackoverflow.com/q/52411992
tags question: http://stackoverflow.com/q/52299082
tags question: http://stackoverflow.com/q/52329931
tags question: http://stackoverflow.com/q/52303618
tags question: http://stackoverflow.com/q/52310501
tags question: http://stackoverflow.com/q/52297315
tags question: http://stackoverflow.com/q/52317459
tags question: http://stackoverflow.com/q/52376306
tags question: http://stackoverflow.com/q/52288243
tags question: http://stackoverflow.com/q/52422195
tags question: http://stackoverflow.com/q/52387295
tags question: http://stackoverflow.com/q/52358034
tags question: http://stackoverflow.com/q/52274481
tags question: http://stackoverflow.com/q/52366219
tags question: http://stackoverflow.com/q/52377194
tags question: http://stackoverflow.com/q/52357918
tags question: http://stackoverflow.com/q/52413147
tags question: http://stackoverflow.com/q/52350703
tags question: http://stackoverflow.com/q/52273761
tags question: http://stackoverflow.com/q/52276757
tags question: http://stackoverflow.com/q/52349227
tags question: http://stackoverflow.com/q/52356732
tags question: http://stackoverflow.com/q/52339031
tags question: http://stackoverflow.com/q/52365878
tags question: http://stackoverflow.com/q/52394909
tags question: http://stackoverflow.com/q/52389622
tags question: http://stackoverflow.com/q/52289488
tags question: http://stackoverflow.com/q/52382522
tags question: http://stackoverflow.com/q/52357618
tags question: http://stackoverflow.com/q/52332892
tags question: http://stackoverflow.com/q/52395173
tags question: http://stackoverflow.com/q/52349818
tags question: http://stackoverflow.com/q/52335680
tags question: http://stackoverflow.com/q/52332822
tags question: http://stackoverflow.com/q/52293445
tags question: http://stackoverflow.com/q/52300777
tags question: http://stackoverflow.com/q/52397513
tags question: http://stackoverflow.com/q/52324695

http://stackoverflow.com/q/52378934
type: AnsweredQuestion
has body: I have a string here: test = "I saw 3 horses, 17 cat, and 14 rabbits!" Now, without using regex and lists, I tried to extract integers from this string and find the maximum integer: def largestNumber(text): largestNumber = 0 for ii in range(len(text)): if text[ii].isdigit(): if int(text[ii]) &gt; largestNumber: largestNumber = int(text[ii]) else: continue if noNumber(text): return None return largestNumber def noNumber(s): for ii in range(len(s)): if s[ii].isdigit(): return False return True Unfortunately, this returns 7, which is the maximum integer, if you are looking at one digit at a time! How do I fix this so that it detects 17 and not 7? Again, without using regex and lists
has answer: http://stackoverflow.com/a/52378997
score: -1
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/52379018
upvote count: 0
has title: Extracting integers out from a string in Python without using re.findall
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/52379018
accepted answer: http://stackoverflow.com/a/52378997
downvote count: 1

http://stackoverflow.com/a/52390693
type: Answer
accepted answer of: http://stackoverflow.com/q/52380572
upvote count: 23
has comment: http://stackoverflow.com/comment/91798804
answers question: http://stackoverflow.com/q/52380572
downvote count: 0
score: 23
has body: (Spyder maintainer here) You can install the first beta of Spyder 4 to get code folding. If you use Anaconda, you need to use the following commands: conda update anaconda conda update spyder or if you use pip, then you need to run pip install -U --pre spyder This beta is quite stable and it has been tested for more than a year.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91787540
has comment: http://stackoverflow.com/comment/97556708

http://stackoverflow.com/a/52417808
has body: epoch time is independent of timezone. It is calculated from midnight - Jan 1 1970 in UTC timezone.No matter where you are currently, it shows the same epoch time everywhere.But you can convert a given epoch time to other timezone. Use pytz.all_timezones to see all the available time zones. Following is one of the approaches. from datetime import datetime import pytz epoch_time=1537414453837/1000 weekdays = ('Monday','Tuesday','Wednesday','Thursday', 'Friday') weekends = ('Saturday', 'Sunday') local_time=datetime.fromtimestamp(epoch_time, tz= pytz.timezone('Hongkong')) hours = local_time.hour day = datetime.fromtimestamp(epoch_time).strftime("%A") if (day in weekdays): if (hours in range(9,23)): print("its Dayparting Schedule and a weekday") elif (day in weekends): if (hours in range(10,23)): print("its Dayparting Schedule and a weekend") else: print("no such day")
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52417195

http://stackoverflow.com/comment/91593908
has text: Very simply, you need to make some data structure to keep track of which letters you've covered. Think about how you would do this with pen and paper; then, how can you represent that with Python data types. After each successful letter identified, update that structure, and check whether you have all five columns yet. Does that get you moving?
score: 0
comment on: http://stackoverflow.com/q/52323191
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91658231
score: 0
has text: I noticed that plt.bar worked fine with how you said to do it.
type: AnswerComment
comment on: http://stackoverflow.com/a/52341042
type: Comment

jquery-select2
tags question: http://stackoverflow.com/q/52333812
tag name: jquery-select2
type: Tag

http://stackoverflow.com/q/52354997
linked to: http://stackoverflow.com/q/47541274
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52355238
has comment: http://stackoverflow.com/comment/91656153
type: Question
has title: How Save image when there is no exact src for image attribute?
tagged with: python
has comment: http://stackoverflow.com/comment/91707607
answer count: 1
score: 0
tagged with: selenium
tagged with: web-crawler
has body: I want to crawl and save image from some page which the page source is this: screenshot I tried several python libraries to save this image like scrappy and selenium but because of src of image they didn't work correctly! import urllib from selenium import webdriver driver = webdriver.Firefox() driver.get('https://example.com/aportal/') img = driver.find_element_by_xpath("//img") src = img.get_attribute('src') urllib.urlretrieve(src, "test.jpeg") What is the correct way to download images like this?
has comment: http://stackoverflow.com/comment/91657972

http://stackoverflow.com/comment/107607760
has text: Could you explain why? "" I wouldn't recommend this, specifically using the global variable to save state, for all scenarios"" Is it a problem if the global variable names are distinct names and are repeated elsewhere in the app?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52375407

http://stackoverflow.com/comment/91511080
type: Comment
comment on: http://stackoverflow.com/a/52280724
has text: Thank you sacul, that does seem to work for performing the operation. However, it doesn't resolve my assignment issue. How could this be used to save into the appropriate row of `cleanText['count']` such that my df then contains only the percentage values?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91619856
comment on: http://stackoverflow.com/q/52335731
type: Comment
type: QuestionComment
has text: send me the code ?
score: 0

http://stackoverflow.com/a/52319561
has body: Look into using BCP with a Format File. Then you can specify that, for example, the last column is terminated by a double-quote followed by a CRLF. The other columns are terminated by double-quote followed by semi-colon. For each column, any characters not matching the combination of characters that make up the terminator for that column will be ignored.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52319008

http://stackoverflow.com/a/52358595
has body: From my guess X must be a 3D tensor, since it usually represents a batch of training data. As far as the functionality of this function is concerned, it randomly permutes the input data tensor X and it does this using the following steps: First it initializes the tensor b with values sampled from uniform distribution. Next this tensor is sorted along dimension 0 and the sorting indices are pulled out to tensor idx. The tensor adx is just an integer tensor of values ranging from 0 to 63. Now, the below line is where all the magic happens: X[idx, adx[None, :]].transpose(1, 2) We use the indices we got before idx and adx (adx[None, :] is simply a row vector of two dimension). Once we have that, we transpose the axes 1 and 2 exactly like what we did at the beginning of the function in the line: X = X.transpose(1, 2) Here is a contrived example, for better understanding: # our input tensor In [51]: X = torch.rand(64, 64, 32) In [52]: X = X.transpose(1, 2) In [53]: X.shape Out[53]: torch.Size([64, 32, 64]) In [54]: b = torch.rand((X.size(0), X.size(1))) # sort `b` which returns a tuple and take only indices In [55]: idx = b.sort(0)[1] In [56]: idx.shape Out[56]: torch.Size([64, 32]) In [57]: adx = torch.arange(0, X.size(1)).long() In [58]: adx.shape Out[58]: torch.Size([32]) In [59]: X[idx, adx[None, :]].transpose(1, 2).shape Out[59]: torch.Size([64, 64, 32]) The important thing to note here is how we got the same shape in the last step as the shape of the input tensor which is (64, 64, 32).
score: 0
has comment: http://stackoverflow.com/comment/91664546
has comment: http://stackoverflow.com/comment/91669615
type: Answer
answers question: http://stackoverflow.com/q/52342514
has comment: http://stackoverflow.com/comment/91663653

http://stackoverflow.com/q/52344932
has comment: http://stackoverflow.com/comment/91635750
has title: python - list comprehensions including conditions like if and else/ error handling
has comment: http://stackoverflow.com/comment/91635749
type: UnansweredQuestion
tagged with: python
has body: is there a neat way to include conditions in list comprehensions in order to do the following: index = [y for y, s in enumerate(data_time_filtered) if next0 in s] I'd like to add the following conditions in the index definition above: if next0 in s: data_filtered.append(data_time_filtered[index[0]]) else: missing_data.append(next0) currently what's happening in my code is: IndexError: list index out of range when the value can not be found. Is it more efficient to handle it with else and if conditions or is there another / better way for error handling in this case? EXTENSION: data_time_filtered is a list of strings like: https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/002/MYD021KM.A2018002.1330.006.2018003152138.hdf https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/004/MYD021KM.A2018004.1330.006.2018005220236.hdf https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/006/MYD021KM.A2018006.1330.006.2018007165439.hdf https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/009/MYD021KM.A2018009.1330.006.2018010190624.hdf next0 are strings in the form of: /XXX/ for example /002/ The index function is looking for the line in data_time_filtered where next0 appears and is returning a index which is used in order to extract that line and append it to a different list. The problem is that sometimes, the string given by next0 is not contained in the list creating the error message above. What I would like is: If index comes a cross such a number it should append this number in a missing_data list instead of breaking and producing the error. UPDATE: i tried this: try: index = [y for y, s in enumerate(data_time_filtered) if next0 in s] data_filtered.append(data_time_filtered[index[0]]) except IndexError: missing_data.append(next0) and it worked :). However, in a later stage on a different line an IndexError is occurring. still checking how to sort this out
has comment: http://stackoverflow.com/comment/91636072
tagged with: conditional-statements
tagged with: list
has comment: http://stackoverflow.com/comment/91635715
has answer: http://stackoverflow.com/a/52352628
type: Question
linked to: http://stackoverflow.com/q/4260280
has comment: http://stackoverflow.com/comment/91635898
has comment: http://stackoverflow.com/comment/91636034
tagged with: list-comprehension
score: 0
has answer: http://stackoverflow.com/a/52345347
answer count: 3
has comment: http://stackoverflow.com/comment/91635872
has answer: http://stackoverflow.com/a/52345151

http://stackoverflow.com/q/52374689
tagged with: flask
has body: Currently, responses from the database for empty sets include HTTP codes that might suggest to user's there is an error retrieving data that might be there. Here are two examples: @app.route("/api/products", methods=["GET"]) def get_products(): offset = request.args['offset'] limit = request.args['limit'] products = Product.query.order_by( Product.post_date.desc()).offset(offset).limit(limit) products_serialized = [] for product in products: products_serialized.append(product.serialize()) if products: return jsonify(products=products_serialized) return jsonify(error=True), 403 @app.route("/api/user", methods=["GET"]) @requires_auth def get_user(): return jsonify(result=g.current_user) I'm open for any other suggestions to handle this.
upvote count: 1
favorite count: 0
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: python
has title: How to handle http status codes in python flask routes
score: 1
linked to: http://stackoverflow.com/q/11746894
tagged with: http
type: Question
duplicate of: http://stackoverflow.com/q/11746894
tagged with: api

http://stackoverflow.com/comment/91758765
has text: You might have some luck with [dask](http://dask.pydata.org/en/latest/)
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52407474
type: QuestionComment

http://stackoverflow.com/q/52420038
tagged with: python
score: 8
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91786282
has title: What datatype is captured with cv2.VideoCapture.read() method in OpenCV?
has body: I am wondering what kind of data type is being captured using the cv2.VideoCapture.read() method. I have been reading the OpenCV documents and I found this explanation: I have followed a couple of basic tutorials with OpenCV where a webcam can capture data and outputs the frames. In the picture below the frame data is being shown. And here follows the code that outputs these frames: import cv2, time, base64 framesCaptured = 0; video=cv2.VideoCapture(0) &lt;====== Video capture for the webcam # Save camera frames as movie fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('recording.avi', fourcc, 20.0, (640, 480)) while True: framesCaptured += 1 check, frame = video.read() &lt;====== Grabs and retrieves frames and decode # Write video frames out.write(frame) # Print out statements #print(check) print(frame) &lt;====== Print out frame data (as shown in the cmd picture below) gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow("frame", gray) key=cv2.waitKey(1) if key == ord('q'): break #print('Frames captured: ' + str(framesCaptured)) video.release() out.release() cv2.destroyAllWindows So I am wondering what kind of data type is being printed from the 'frame' variable? In the end I want to use this 'frame' data to re-construct the images to a video in a C# application.
accepted answer: http://stackoverflow.com/a/52420549
type: Question
tagged with: opencv
tagged with: types
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91784374
has answer: http://stackoverflow.com/a/52420549
upvote count: 8

http://stackoverflow.com/q/52369623
has title: Close existing toplevel when a new is created. Tkinter Python 3
has answer: http://stackoverflow.com/a/52369715
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: tk-toolkit
type: Question
answer count: 1
tagged with: toplevel
upvote count: 1
accepted answer: http://stackoverflow.com/a/52369715
tagged with: window
favorite count: 0
has body: Ive got a button in a program that opens a toplevel window. If the button is pressed again I want the old toplevel to be destroyed and a new one to be created. I've searched for hours and tried implementing different ways but nothing seems to work. Ive tried these approaches in various forms: if toplevel is None or not toplevel.winfo_exists(): toplevel.destroy() try: toplevel.destroy() except: pass if toplevel.winfo_exists() == "1": toplevel.destroy() My code looks like this: def translate(): #(I would like to check for and close existing toplevels here) toplevel = Toplevel() ...stuff I greatly appreciate all the help I can get!
tagged with: tkinter

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/52354491
tags question: http://stackoverflow.com/q/52368636
tags question: http://stackoverflow.com/q/52377710
tags question: http://stackoverflow.com/q/52359432
tags question: http://stackoverflow.com/q/52350429
tags question: http://stackoverflow.com/q/52338215
tags question: http://stackoverflow.com/q/52361716
tags question: http://stackoverflow.com/q/52390968
tags question: http://stackoverflow.com/q/52414967
tags question: http://stackoverflow.com/q/52348874
tags question: http://stackoverflow.com/q/52429996
tags question: http://stackoverflow.com/q/52359461
tags question: http://stackoverflow.com/q/52423510
tags question: http://stackoverflow.com/q/52425163
tags question: http://stackoverflow.com/q/52341748
tags question: http://stackoverflow.com/q/52409704
tags question: http://stackoverflow.com/q/52316615
tags question: http://stackoverflow.com/q/52375317
tags question: http://stackoverflow.com/q/52310586
tags question: http://stackoverflow.com/q/52295245
type: Tag
tags question: http://stackoverflow.com/q/52417494
tags question: http://stackoverflow.com/q/52366891
tags question: http://stackoverflow.com/q/52327186
tags question: http://stackoverflow.com/q/52386964
tags question: http://stackoverflow.com/q/52344684
tags question: http://stackoverflow.com/q/52319562
tags question: http://stackoverflow.com/q/52381428
tags question: http://stackoverflow.com/q/52428124
tags question: http://stackoverflow.com/q/52354313
tags question: http://stackoverflow.com/q/52385584
tags question: http://stackoverflow.com/q/52383294
tags question: http://stackoverflow.com/q/52295425
tags question: http://stackoverflow.com/q/52382111
tags question: http://stackoverflow.com/q/52280584
tags question: http://stackoverflow.com/q/52429774
tags question: http://stackoverflow.com/q/52359838
tags question: http://stackoverflow.com/q/52294649
tags question: http://stackoverflow.com/q/52398066
tags question: http://stackoverflow.com/q/52416293
tags question: http://stackoverflow.com/q/52399776
tags question: http://stackoverflow.com/q/52387762
tags question: http://stackoverflow.com/q/52352463
tags question: http://stackoverflow.com/q/52354662
tags question: http://stackoverflow.com/q/52376693
tags question: http://stackoverflow.com/q/52386849
tags question: http://stackoverflow.com/q/52356414
tags question: http://stackoverflow.com/q/52334086
tags question: http://stackoverflow.com/q/52414550
tags question: http://stackoverflow.com/q/52336915
tags question: http://stackoverflow.com/q/52406058
tags question: http://stackoverflow.com/q/52286676

http://stackoverflow.com/a/52414887
type: Answer
accepted answer of: http://stackoverflow.com/q/52408701
has body: The page is JavaScript rendered. You need Selenium. Here is some code to start on: from selenium import webdriver url = 'https://www.scoreboard.com/uk/football/england/premier-league/' driver = webdriver.Chrome() driver.get(url) stages = driver.find_elements_by_class_name('stage-scheduled') driver.close() Or you could pass driver.content in to the BeautifulSoup method. Like this: soup = BeautifulSoup(driver.page_source, 'html.parser') Note: You need to install a webdriver first. I installed chromedriver. Good luck!
answers question: http://stackoverflow.com/q/52408701
score: 9
type: AcceptedAnswer
downvote count: 0
upvote count: 9

http://stackoverflow.com/q/52329005
answer count: 2
downvote count: 0
has title: Kubernetes: How do I get all pods in a namespace using the python api?
favorite count: 0
has body: I am using python to access my cluster. The only thing I came across, that is close is list_namespaced_pod, which does not give me the actual names of the pods.
tagged with: kubernetes
tagged with: python
has answer: http://stackoverflow.com/a/68028722
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/54078849
tagged with: namespaces
has comment: http://stackoverflow.com/comment/91608702
upvote count: 9
score: 9
type: Question
has comment: http://stackoverflow.com/comment/91605219

http://stackoverflow.com/a/52275834
has body: I went ahead and created a solution using networkx. It goes as follows (extended example) import networkx as nx import pandas as pd df = pd.DataFrame({ 'id': range(7), 'vmns': ('nan', 'a', 'a;b;c', 'c', 'b', 'd;e', 'e') }) which yields id vmns 0 0 nan 1 1 a 2 2 a;b;c 3 3 c 4 4 b 5 5 d;e 6 6 e Then I create nodes from rows without semicolon and edges from rows with semicolon. Rows with nan are ignored. # determine which rows contains nodes and which contains edges edges_mask = df['vmns'].str.contains(';') nodes_mask = ~df['vmns'].str.contains(';') &amp; (df['vmns'] != 'nan') def create_pairwise_edges(lst): return [(lst[0], value) for value in lst[1:]] # create the graph with nodes and edges G = nx.Graph() G.add_nodes_from(df.loc[nodes_mask, 'vmns']) G.add_edges_from([st for row in df.loc[edges_mask, 'vmns'].str.split(';').map(create_pairwise_edges) for st in row]) # determine the connected components and write to df Gcc = nx.connected_components(G) new_map = dict() for g, ids in enumerate(Gcc): for id in ids: new_map[id] = g new_map['nan'] = 'nan' df['combined_group'] = df['vmns'].str.split(';').map(lambda x: new_map[x[0]]) The result is id vmns combined_group 0 0 nan nan 1 1 a 0 2 2 a;b;c 0 3 3 c 0 4 4 b 0 5 5 d;e 1 6 6 e 1
score: 0
answers question: http://stackoverflow.com/q/52274795
type: Answer

http://stackoverflow.com/comment/91513407
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52277166
type: Comment
has text: Last quesiton, is the use of classes required? After that I'll go through and do this over how I would approach it

http://stackoverflow.com/q/52358844
tagged with: list
downvote count: 3
possible better answer: http://stackoverflow.com/a/52358948
type: Question
has answer: http://stackoverflow.com/a/52358948
upvote count: 0
has title: Replace integers in a list with a string Python
has body: I am working on a coding assignment in Python and I am struggling to understand why my code is not working. Write a function in Python called "BooHoo" which takes in an integer, n, and stores all integers from 1 to n in a list. However, if an integer in the list is divisible by 3, the list should instead contain "Boo". If the integer is divisible by 5 the list should instead contain "Hoo". If the integer is divisible by both 3 and 5, the list should instead contain "BooHoo". def BooHoo(n): ''' A function which returns a list of integers, and replaces integers divisible by 3 with "Boo" and integers divisible by 5 with "Hoo" and integers divisible by 3 and 5 with "BooHoo" Parameters ------- n: an integer Returns -------- final_list: a Python list ''' main_list = [] for x in range(n): main_list.append(x) for idx, j in enumerate(main_list): if not (idx % 3) and not (idx % 5): main_list.pop(idx) main_list.insert(idx, 'BooHoo') elif not (idx % 3): main_list.pop(idx) main_list.insert(idx, 'Boo') elif not (idx % 5): main_list.pop(idx) main_list.insert(idx, 'Hoo') else: continue final_list = [main_list] return final_list
has answer: http://stackoverflow.com/a/52359007
has answer: http://stackoverflow.com/a/52358882
answer count: 3
has comment: http://stackoverflow.com/comment/91662136
tagged with: python
favorite count: 0
score: -3
has comment: http://stackoverflow.com/comment/91662172
accepted answer: http://stackoverflow.com/a/52358882
type: AnsweredQuestion

http://stackoverflow.com/comment/91780243
comment on: http://stackoverflow.com/q/52418405
type: Comment
type: QuestionComment
has text: @jezrael I have updated my codes already please take a look (if u look at the first sentence, it has the same word - image
score: 0

http://stackoverflow.com/comment/91625419
comment on: http://stackoverflow.com/q/52337870
type: Comment
type: QuestionComment
has text: yeah, I only got 3 lines of code and it's everything that appears in the console
score: 1

curses
tags question: http://stackoverflow.com/q/52393234
tag name: curses
type: Tag
tags question: http://stackoverflow.com/q/52414352

http://stackoverflow.com/q/52282098
accepted answer: http://stackoverflow.com/a/52282222
type: Question
tagged with: user-defined-functions
tagged with: telegraf
has title: kapacitor : not opening http port when a python udf is specified
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52282222
has body: I am trying to learn about kapacitor User Defined Functions (udf) from this URL https://www.youtube.com/watch?v=LL8g4qiBCNo kapacitor starts and listens on http port 9092 when I do not specify a python udf. My [udf] section in kapacitor.conf looks like [udf] [udf.functions] [udf.functions.geoSum] prog = "/usr/bin/python" args = ["-u", "/tmp/geo.py"] timeout = "20s" My python udf (geo.py) looks like the following import sys from agent import Agent, Handler import udf_pb2 class GeoSum(Handler): def __init__(self): self._field = '' self.size = 0 def info(self): response = udf_pb2.Response() response.info.wants = udf_pb2.STREAM response.info.provides = udf_pb2.STREAM response.info.options['field'].valueTypes.append(udf_pb2.STRING) response.info.options['size'].valueTypes.append(udf_pb2.INT) response.info.options['magic'].valueTypes.extend([ udf_pb2.INT, udf_pb2.DOUBLE, udf_pb2.DURATION ]) return response if __name__ == '__main__': agent = Agent() handler = GeoSum() agent.handler = handler print &gt;&gt; sys.stdout, "Starting GeoSum ..." agent.start() agent.wait() print &gt;&gt; sys.stdout, "Stoping GeoSum ..." With the above udf section kapacitor does not listen on http port 9092
tagged with: python
tagged with: influxdb
type: AnsweredQuestion
tagged with: kapacitor

http://stackoverflow.com/q/52332756
has body: We have this code: data = [['BQXBTC', '9/14/2018', '5:15:00', 4.792e-05, 4.8e-05, 4.777e-05, 4.783e-05, 30027.0], ['BQXBTC', '9/14/2018', '5:30:00', 4.79e-05, 4.817e-05, 4.78e-05, 4.811e-05, 10151.0], ['BQXBTC', '9/14/2018', '5:45:00', 4.788e-05, 4.811e-05, 4.764e-05, 4.767e-05, 9682.0], ['BQXBTC', '9/14/2018', '6:00:00', 4.766e-05, 4.796e-05, 4.759e-05, 4.761e-05, 22046.0], ['BQXBTC', '9/14/2018', '6:00:00', 4.766e-05, 4.796e-05, 4.759e-05, 4.761e-05, 22094.0], ['BQXBTC', '9/14/2018', '6:15:00', 4.761e-05, 4.77e-05, 4.761e-05, 4.763e-05, 26761.0], ['ETCBTC', '9/14/2018', '2:15:00', 0.001712, 0.001718, 0.001711, 0.001713, 9065.28], ['ETCBTC', '9/14/2018', '2:30:00', 0.001712, 0.001718, 0.001712, 0.001716, 11504.56], ['ETCBTC', '9/14/2018', '2:45:00', 0.001717, 0.001719, 0.00171, 0.001711, 10365.09], ['ETCBTC', '9/14/2018', '3:00:00', 0.001712, 0.001721, 0.001709, 0.001716, 8922.49], ['ETCBTC', '9/14/2018', '3:00:00', 0.001712, 0.001721, 0.001709, 0.001714, 8924.85], ['ETCBTC', '9/14/2018', '3:15:00', 0.001716, 0.001718, 0.001709, 0.00171, 14429.7]] df = pd.DataFrame(data) print(df) returning this: 0 1 2 3 4 5 6 7 0 BQXBTC 9/14/2018 5:15:00 0.000048 0.000048 0.000048 0.000048 30027.00 1 BQXBTC 9/14/2018 5:30:00 0.000048 0.000048 0.000048 0.000048 10151.00 2 BQXBTC 9/14/2018 5:45:00 0.000048 0.000048 0.000048 0.000048 9682.00 3 BQXBTC 9/14/2018 6:00:00 0.000048 0.000048 0.000048 0.000048 22046.00 4 BQXBTC 9/14/2018 6:00:00 0.000048 0.000048 0.000048 0.000048 22094.00 5 BQXBTC 9/14/2018 6:15:00 0.000048 0.000048 0.000048 0.000048 26761.00 6 ETCBTC 9/14/2018 2:15:00 0.001712 0.001718 0.001711 0.001713 9065.28 7 ETCBTC 9/14/2018 2:30:00 0.001712 0.001718 0.001712 0.001716 11504.56 8 ETCBTC 9/14/2018 2:45:00 0.001717 0.001719 0.001710 0.001711 10365.09 9 ETCBTC 9/14/2018 3:00:00 0.001712 0.001721 0.001709 0.001716 8922.49 10 ETCBTC 9/14/2018 3:00:00 0.001712 0.001721 0.001709 0.001714 8924.85 11 ETCBTC 9/14/2018 3:15:00 0.001716 0.001718 0.001709 0.001710 14429.70 The pro…
has answer: http://stackoverflow.com/a/52332831
accepted answer: http://stackoverflow.com/a/52332831
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
has title: Python - Partially Duplicate Rows - Keeping only the last one
type: Question
score: 0
tagged with: pandas
answer count: 1

http://stackoverflow.com/q/52303658
tagged with: image
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52305372
favorite count: 0
has answer: http://stackoverflow.com/a/52304092
type: UnansweredQuestion
has body: I am reading an image like so: img = np.array(Image.open(test_dir + image_name)) What I want to do is find a region in the array where the value is high (250 or more) and reduce it by 10: rows = img.shape[0] cols = img.shape[1] pixel = [] for x in range(0,rows): for y in range(0, cols): if x &gt;= 122 and x &lt;= 160 and y &gt;= 34 and y &lt;= 71: if img[x,y]&gt;= 250: img[x,y] = img[x,y] -10 pixel.append(img[x,y]) So the region I am looking at according the the unaltered image should be a box from (122, 34) to (160,71), and it should have some pixels over 250, but somehow when I run this code I end up with nothing in the pixel list
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/52305562
upvote count: 1
type: Question
tagged with: numpy
has title: Edit pixel values in an image as numpy array
tagged with: python-3.6
has answer: http://stackoverflow.com/a/52309436

http://stackoverflow.com/a/52316772
score: 9
accepted answer of: http://stackoverflow.com/q/52316689
has body: Using idxmin and slicing x.loc[2:x['value'].gt(0).idxmin(),:] 2 3 3 2 4 1 5 0 Name: value Edit: For a general formula, use index = 7 threshold = 2 x.loc[index:x.loc[index:,'value'].gt(threshold).idxmin(),:] From your description in comments, seemed like you want to begin from index+1 and not index. So, if that is the case, just use x.loc[index+1:x.loc[index+1:,'value'].gt(threshold).idxmin(),:]
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91593120
upvote count: 9
answers question: http://stackoverflow.com/q/52316689
has comment: http://stackoverflow.com/comment/91592340

http://stackoverflow.com/comment/91745571
comment on: http://stackoverflow.com/a/52400611
type: AnswerComment
type: Comment
has text: Yes first you have to install pandas using your python terminal.
score: 0

http://stackoverflow.com/comment/91596907
score: 2
comment on: http://stackoverflow.com/q/52324967
has text: `current_scene` is only defined within the `play()` method, and the `current_scene.enter()` line is not a part of that method.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52282589
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52282914
accepted answer: http://stackoverflow.com/a/52282621
has answer: http://stackoverflow.com/a/52282914
tagged with: python
has body: Replacing Select Dataframe Columns (based on other conditions) Issue df.loc[df.gender=='boy',:]['names'] = df.loc[df.gender=='boy',:]['names'].replace(',','/',regex=False) print df (result) gender names 0 boy bob, joe 1 boy john, nick 2 girl sarah, ally 3 girl maria, sally df['names'] = df.loc[df.gender=='boy',:]['names'].replace(',','/',regex=False) print df (result) gender names 0 boy bob, joe 1 boy john, nick 2 girl NaN 3 girl NaN I also tried df['names'].str.replace(',','/',regex=False,inplace=True), but received the error message TypeError: replace() got an unexpected keyword argument 'inplace'. Desired Result gender names 0 boy bob/ joe 1 boy john/ nick 2 girl sarah, ally 3 girl maria, sally
has comment: http://stackoverflow.com/comment/91513573
type: AnsweredQuestion
has title: Replacing Select Dataframe Columns (based on other conditions) Issue
has answer: http://stackoverflow.com/a/52282621
type: Question
tagged with: replace
score: 0

http://stackoverflow.com/q/52298964
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52300687
downvote count: 1
score: -1
has answer: http://stackoverflow.com/a/52301149
has answer: http://stackoverflow.com/a/52300425
type: Question
has answer: http://stackoverflow.com/a/52300092
upvote count: 0
tagged with: polynomials
has title: Function multiplying two polynomials gives wrong result
has comment: http://stackoverflow.com/comment/91569354
has body: I want to create a function called multipoly(x,y) which takes two lists as input, multiplies the lists and returns the answers. Polynomial is represented as follows: for instance x^4+2X^3 is represented as [(1,4),(2,3)]. Here is something I get but it returns wrong answer for some test cases: def multipoly(p1,p2): x=max(p1,p2) y=min(p1,p2) p1=x p2=y for i in range(len(x)): for item in p2: p1[i] = ((p1[i][0] * item[0]), (p1[i][1] + item[1])) p2.remove(item) return p1 print(multipoly([(1,1),(-1,0)],[(1,2),(1,1),(1,0)]))
tagged with: python
answer count: 4
favorite count: 0

http://stackoverflow.com/q/52332678
has body: Is the code below a bad practice? It works the way I want it, but couldn't find any other examples where an exception is raised within another exception. If it is a bad practice, what would be the ideal way to do this? This code is in my low-level handler, and I want to have specific exceptions for codes HTTP 400/401 - as well as a generic exception for the other HTTP codes - in order to ease exception handling handling in my high-level wrapper(s). Ideally there should be only one location where the HTTP codes are matched to a specific message or sub-exception. class APIRequestError(APIError): def __init__(self, code=-1, message="N/A"): if code == 400: raise Exceptions.APIBadRequest(message) elif code == 401: raise Exceptions.APIAuthentication(message) elif code == 404: Exception.__init__(self, "HTTP 404 : API resource not found!") elif code == 500: Exception.__init__(self, "HTTP 500 : Server-side error!") else: Exception.__init__(self, f"Unhandled HTTP error ({code}).") class APIBadRequest(APIRequestError): def __init__(self, message="N/A"): message_out = str(message)[:Exceptions.MSG_MAX] Exception.__init__(self, f"Bad API request : {message_out}") class APIAuthentication(APIRequestError): def __init__(self, message="N/A"): message_out = str(message)[:Exceptions.MSG_MAX] Exception.__init__(self, f"Authentication error : {message_out}")
tagged with: python
has title: Python 3 : Raising exceptions within excpetions
answer count: 0
has comment: http://stackoverflow.com/comment/91612411
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91612498
has comment: http://stackoverflow.com/comment/91613209
has comment: http://stackoverflow.com/comment/91612748
type: Question
score: 0
tagged with: exception
has comment: http://stackoverflow.com/comment/91612686

http://stackoverflow.com/a/52373845
upvote count: 3
type: Answer
has body: First, setup your conditions: c1 = df.Value.sub(df.Value.shift()).gt(0.1) c2 = df.Value.diff().lt(0.1) &amp; df.TransactionId.gt(0) Now use np.select: df.assign(ChargerState=np.select([c1, c2], ['Charging', 'Not Charging'], 'Vacant')) TransactionId Value ChargerState Timestamp 2018-01-07 22:00:00 633025 674.87 Vacant 2018-01-07 22:15:00 633025 676.11 Charging 2018-01-07 22:30:00 633025 677.06 Charging You may need to tweak c1, because in this example, although it has both a TransactionId and a Value, it shows up as Vacant, because there is no previous row. One potential option would be to assume that if a device has a Value and TransactionID, it has started charging, which we could accomplish using fillna on c1: c1 = df.Value.sub(df.Value.shift().fillna(0)).gt(0.1) # Notice the fillna c2 = df.Value.diff().lt(0.1) &amp; df.TransactionId.gt(0) df.assign(ChargerState=np.select([c1, c2], ['Charging', 'Not Charging'], 'Vacant')) TransactionId Value ChargerState Timestamp 2018-01-07 22:00:00 633025 674.87 Charging 2018-01-07 22:15:00 633025 676.11 Charging 2018-01-07 22:30:00 633025 677.06 Charging
has comment: http://stackoverflow.com/comment/91692900
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/91693102
accepted answer of: http://stackoverflow.com/q/52373764
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91692749
answers question: http://stackoverflow.com/q/52373764

http://stackoverflow.com/q/52314581
tagged with: python
tagged with: solver
has title: Initial Guess/Warm start in CVXPY: give a hint of the solution
has comment: http://stackoverflow.com/comment/91587208
has answer: http://stackoverflow.com/a/67320310
type: Question
has body: In this bit of code: import cvxpy as cvx # Examples: linear programming # Create two scalar optimization variables. x = cvx.Variable() y = cvx.Variable() # Create 4 constraints. constraints = [x &gt;= 0, y &gt;= 0, x + y &gt;= 1, 2*x + y &gt;= 1] # Form objective. obj = cvx.Minimize(x+y) # Form and solve problem. prob = cvx.Problem(obj, constraints) prob.solve(warm_start= True) # Returns the optimal value. print ("status:", prob.status) print ("optimal value", prob.value) print ("optimal var", x.value, y.value) I'm looking for a way to choose the warm start value myself (for example: x = 1/2 and y = 1/2), not the previous solver result. Is there any way to give the solver this input? And if not, is there a non-commercial alternative to cvxpy?
tagged with: optimization
answer count: 2
has comment: http://stackoverflow.com/comment/91599190
tagged with: cvxpy
downvote count: 0
favorite count: 0
score: 8
upvote count: 8
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53038424

http://stackoverflow.com/comment/91788470
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52421405
type: QuestionComment
has text: @GiacomoAlzetta,file was created with `save ('test_buoysimoptions.mat', '-v7', '-struct', 'buoysimoptions')` in Matlab, the standard way to do so.

pyqt
type: Tag
tags question: http://stackoverflow.com/q/52359924
tags question: http://stackoverflow.com/q/52308937
tags question: http://stackoverflow.com/q/52313073
tags question: http://stackoverflow.com/q/52401233
tags question: http://stackoverflow.com/q/52286177
tags question: http://stackoverflow.com/q/52288632
tags question: http://stackoverflow.com/q/52294677
tags question: http://stackoverflow.com/q/52423429
tags question: http://stackoverflow.com/q/52338500
tags question: http://stackoverflow.com/q/52321938
tags question: http://stackoverflow.com/q/52368510
tags question: http://stackoverflow.com/q/52336807
tags question: http://stackoverflow.com/q/52314931
tags question: http://stackoverflow.com/q/52323548
tags question: http://stackoverflow.com/q/52376364
tags question: http://stackoverflow.com/q/52377073
tags question: http://stackoverflow.com/q/52359042
tags question: http://stackoverflow.com/q/52416449
tags question: http://stackoverflow.com/q/52384362
tags question: http://stackoverflow.com/q/52315520
tags question: http://stackoverflow.com/q/52389811
tags question: http://stackoverflow.com/q/52293422
tags question: http://stackoverflow.com/q/52361059
tags question: http://stackoverflow.com/q/52276524
tags question: http://stackoverflow.com/q/52291585
tags question: http://stackoverflow.com/q/52332534
tags question: http://stackoverflow.com/q/52379426
tags question: http://stackoverflow.com/q/52282780
tags question: http://stackoverflow.com/q/52304519
tags question: http://stackoverflow.com/q/52338366
tags question: http://stackoverflow.com/q/52372134
tags question: http://stackoverflow.com/q/52328859
tags question: http://stackoverflow.com/q/52345457
tag name: pyqt
tags question: http://stackoverflow.com/q/52404221
tags question: http://stackoverflow.com/q/52382736
tags question: http://stackoverflow.com/q/52339932
tags question: http://stackoverflow.com/q/52358258
tags question: http://stackoverflow.com/q/52414654
tags question: http://stackoverflow.com/q/52410731

http://stackoverflow.com/q/52383287
has answer: http://stackoverflow.com/a/52383401
type: Question
has title: Concatenate dataframes in a for loop
has body: I wrote a class to scrape public holiday data, but i would like to iterate my class with many years like : outputt_path = "C:/Users/N000193384/Downloads/countries/" recent_years = ["2015", "2016", "2017", "2018"] for year in recent_years : PBC = Event_Scraper("italy", year, outputt_path) df = PBC._read_html_() df = df.append(df) my class took the country's name and the year, outputt_path is useless there. _read_html_() builds a cleaned dataframe and i would like to append each dataframe. Here is an example of the dataframe for one year : Date Holiday Name Holiday Type 0 2018-01-01 New Year's Day National holiday 1 2018-01-06 Epiphany National holiday 2 2018-03-20 March Equinox Season 3 2018-03-30 Good Friday Observance 4 2018-04-01 Easter Day National holiday
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91710746
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2

http://stackoverflow.com/comment/91750464
comment on: http://stackoverflow.com/q/52402824
type: Comment
type: QuestionComment
has text: Is you machine in a corporate environment? Is yes there is probabaly a (transparent ?) proxy between your machine and the global internet, and you should contact your support...
score: 0

http://stackoverflow.com/a/52412271
score: 1
has comment: http://stackoverflow.com/comment/91768572
has comment: http://stackoverflow.com/comment/91768661
accepted answer of: http://stackoverflow.com/q/52412102
has comment: http://stackoverflow.com/comment/91768910
answers question: http://stackoverflow.com/q/52412102
has comment: http://stackoverflow.com/comment/91768435
has comment: http://stackoverflow.com/comment/91768981
upvote count: 2
type: AcceptedAnswer
downvote count: 1
has body: You can use a QDialog. http://pyside.github.io/docs/pyside/PySide/QtGui/QDialog.html https://wiki.qt.io/Qt_for_Python_Tutorial_SimpleDialog Do something like below. from PySide import QtGui # from PySide2 import QtWidgets or from qtpy import QtWidgets dialog = QtGui.QDialog() lay = QtGui.QFormLayout() dialog.setLayout(lay) slider = QtGui.QSlider() lay.addRow(QtGui.QLabel('Slider'), slider) ... # Accept buttons ans = dialog.exec_() # This will block until the dialog closes # Check if dialog was accepted? value = slider.value() ... # Continue code. Similar to the exec_ QMessageBox is this exmaple. https://gist.github.com/tcrowson/8152683242018378a00b You can probably use a QMessageBox and set the layout to change the look. What is going on? Essential PySide works by running an event loop. It runs this infinite while loop that takes events off of a queue an processes them. Any mouse movement or button click is an event. app = QApplication([]) app.exec_() # This is running the event loop until the application closes. print('here') # This won't print until the application closes You could manually reproduce this with any widget. app = QApplication([]) # Required may be automatic with IPython slider = QSlider() # No Parent slider.show() # Slider is not visible until the application processes the slider.show() event app.processEvents() while slider.isVisible(): # When user clicks the X on the slider it will hide the slider app.processEvents() # Process events like the mouse moving the slider print('here') # This won't print until the Slider closes ... # Continue code script
has comment: http://stackoverflow.com/comment/91768502
has comment: http://stackoverflow.com/comment/91768624
has comment: http://stackoverflow.com/comment/91768787
has comment: http://stackoverflow.com/comment/91768814
type: Answer
has comment: http://stackoverflow.com/comment/91768921
has comment: http://stackoverflow.com/comment/91768465
has comment: http://stackoverflow.com/comment/91768552

http://stackoverflow.com/comment/91591419
type: Comment
has text: @user3203275 How about post your real data , I can not address the question and problem now , my out put show above same as your expected out put
comment on: http://stackoverflow.com/a/52321429
type: AnswerComment
score: 0

http://stackoverflow.com/a/52426848
has body: instead of {{test.rdno}} {{test.ipno}} do this {{test[0]}} {{test[1]}}
type: Answer
upvote count: 1
score: 1
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52425073
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52425073

http://stackoverflow.com/comment/91727128
type: QuestionComment
has text: Now, I understand it. Thank you very much, If you post your answer, I will accept it. Thanks again.
score: 0
comment on: http://stackoverflow.com/q/52387537
type: Comment

http://stackoverflow.com/q/52314376
tagged with: conda
score: 0
has answer: http://stackoverflow.com/a/52316608
answer count: 1
type: UnansweredQuestion
has body: I keep find the below problem during RNN model restoration in Tensorflow. The model works well but the restoration has an issue. below is my code. What could be the issue. I have deleted and cleaned all the previous session but the same issue persists. saver = tf.train.import_meta_graph(os.path.join(logs_path, 'Multi_Layer_RNN_model.ckpt-499999.meta')) with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(logs_path) saver.restore(sess, tf.train.latest_checkpoint(logs_path)) THE ERROR InvalidArgumentError: Assign requires shapes of both tensors to match. lhs shape= [105,400] rhs shape= [111,400] [[Node: save/Assign_11 = Assign[T=DT_FLOAT, _class=["loc:@rnn/lstm_cell/kernel"], use_locking=true, validate_shape=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](rnn/lstm_cell/kernel/RMSProp_1, save/RestoreV2:11)]] Caused by op 'save/Assign_11', defined at: File "C:\Users\ADMN\AppData\Local\conda\conda\envs\tensorflow\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Users\ADMN\AppData\Local\conda\conda\envs\tensorflow\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\ADMN\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\ipykernel_launcher.py", line 16, in &lt;module&gt; app.launch_new_instance() File "C:\Users\ADMN\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance app.start() .................
tagged with: python
has title: Tensorflow Model restoration issues
tagged with: tensorflow
type: Question

record
type: Tag
tags question: http://stackoverflow.com/q/52347437
tag name: record

http://stackoverflow.com/comment/91596564
score: 1
comment on: http://stackoverflow.com/q/52323636
has text: Not sure about what example should I post. The string you see in my question is the same I am using in my code. The code just call that string to execute an operation; so to show the whole infrastructure I should post 1.2 MB of code. That string works fine in OSX but when I use it on windows I get the error I mention above. I did fix the quotes and then a new error did trigger, because I need to convert the `/` in `\`; I did that and then the error triggered because the location in which the app file (which is an exe of the same name on Windows), is in a different place.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52349511
upvote count: 1
has comment: http://stackoverflow.com/comment/91644302
score: 1
answers question: http://stackoverflow.com/q/52349497
has body: Try this: a = [(0,0,0), (0,1,1), (1,0,1), (1,1,0)] b = [0, 2, 1, 1, 2, 2] x = [] for index in b: x += list(a[index]) x = tuple(x) print(x) Which shortens to: x = tuple(sum(list(a[index]) for index in b)) Explanation of first method: create a variable to hold current sum for each index number specified in b, do the following: add a[index] to the sum So on each loop cycle, a[index] becomes a[0], a[2], a[1] ... a[2] In the sum method, those cycles are added together as the function takes the generator expression and exhausts it.
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91648136
type: Comment
has text: kind of, but only if you make an inplace copy.
comment on: http://stackoverflow.com/a/52351401
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91553143
score: 2
has text: `df.groupby(['ID', df.date.dt.month])['values'].apply(lambda x: x.mode())`
comment on: http://stackoverflow.com/q/52302605
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91521902
comment on: http://stackoverflow.com/a/52286531
score: 0
type: AnswerComment
type: Comment
has text: @U9-Forward Thank you very much for your help

http://stackoverflow.com/comment/91524608
has text: Do you mean the encoding is different?
comment on: http://stackoverflow.com/q/52288283
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52300323
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91553340
tagged with: command-line
has answer: http://stackoverflow.com/a/52300424
has body: https://github.com/dtcarls/ff_bot https://github.com/dtcarls/ff_bot/blob/master/ff_bot/ff_bot.py I am trying to figure out a way to manually have this python script run certain functions, like get_trophies from the terminal. Currently the script is scheduled to send certain messages each week, at a specific time, but I would really like to be able to manually resend the message through the shell. Something like "python3 ff_bot.py get_trophies" and have the bot send that message again. Not sure if this is possible, and I am very limited in my programming knowledge. The app was auto deployed to heroku per the readme on GitHub
has comment: http://stackoverflow.com/comment/91553562
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52300417
has title: Manually running python3 script and commands from shell console
has comment: http://stackoverflow.com/comment/91548493
answer count: 2
downvote count: 0
tagged with: shell
favorite count: 0
tagged with: python-3.x

list
tags question: http://stackoverflow.com/q/52304947
type: Tag
tags question: http://stackoverflow.com/q/52341877
tags question: http://stackoverflow.com/q/52380592
tags question: http://stackoverflow.com/q/52287965
tags question: http://stackoverflow.com/q/52354081
tags question: http://stackoverflow.com/q/52376681
tags question: http://stackoverflow.com/q/52397940
tags question: http://stackoverflow.com/q/52399091
tags question: http://stackoverflow.com/q/52273841
tags question: http://stackoverflow.com/q/52395023
tags question: http://stackoverflow.com/q/52319804
tags question: http://stackoverflow.com/q/52413881
tags question: http://stackoverflow.com/q/52360234
tags question: http://stackoverflow.com/q/52345633
tags question: http://stackoverflow.com/q/52307091
tags question: http://stackoverflow.com/q/52301123
tags question: http://stackoverflow.com/q/52344942
tags question: http://stackoverflow.com/q/52275245
tags question: http://stackoverflow.com/q/52413470
tags question: http://stackoverflow.com/q/52357926
tags question: http://stackoverflow.com/q/52419417
tags question: http://stackoverflow.com/q/52298296
tags question: http://stackoverflow.com/q/52411234
tags question: http://stackoverflow.com/q/52422937
tags question: http://stackoverflow.com/q/52307503
tags question: http://stackoverflow.com/q/52415629
tags question: http://stackoverflow.com/q/52322211
tags question: http://stackoverflow.com/q/52308493
tags question: http://stackoverflow.com/q/52338454
tags question: http://stackoverflow.com/q/52335283
tags question: http://stackoverflow.com/q/52355260
tags question: http://stackoverflow.com/q/52284823
tags question: http://stackoverflow.com/q/52364321
tags question: http://stackoverflow.com/q/52342187
tags question: http://stackoverflow.com/q/52358634
tags question: http://stackoverflow.com/q/52286904
tags question: http://stackoverflow.com/q/52350313
tags question: http://stackoverflow.com/q/52427397
tags question: http://stackoverflow.com/q/52424375
tags question: http://stackoverflow.com/q/52329426
tags question: http://stackoverflow.com/q/52407630
tags question: http://stackoverflow.com/q/52376981
tag name: list
tags question: http://stackoverflow.com/q/52423525
tags question: http://stackoverflow.com/q/52326709
tags question: http://stackoverflow.com/q/52292286
tags question: http://stackoverflow.com/q/52334113
tags question: http://stackoverflow.com/q/52356607
tags question: http://stackoverflow.com/q/52312950
tags question: http://stackoverflow.com/q/52329341
tags question: http://stackoverflow.com/q/52326223
tags question: http://stackoverflow.com/q/52307575
tags question: http://stackoverflow.com/q/52354124
tags question: http://stackoverflow.com/q/52284137
tags question: http://stackoverflow.com/q/52395750
tags question: http://stackoverflow.com/q/52292196
tags question: http://stackoverflow.com/q/52307410
tags question: http://stackoverflow.com/q/52354011
tags question: http://stackoverflow.com/q/52357831
tags question: http://stackoverflow.com/q/52296466
tags question: http://stackoverflow.com/q/52298662
tags question: http://stackoverflow.com/q/52376009
tags question: http://stackoverflow.com/q/52345435
tags question: http://stackoverflow.com/q/52377699
tags question: http://stackoverflow.com/q/52367388
tags question: http://stackoverflow.com/q/52404133
tags question: http://stackoverflow.com/q/52311526
tags question: http://stackoverflow.com/q/52402583
tags question: http://stackoverflow.com/q/52309210
tags question: http://stackoverflow.com/q/52370310
tags question: http://stackoverflow.com/q/52271910
tags question: http://stackoverflow.com/q/52401321
tags question: http://stackoverflow.com/q/52310741
tags question: http://stackoverflow.com/q/52429260
tags question: http://stackoverflow.com/q/52313288
tags question: http://stackoverflow.com/q/52373014
tags question: http://stackoverflow.com/q/52360916
tags question: http://stackoverflow.com/q/52316409
tags question: http://stackoverflow.com/q/52343181

http://stackoverflow.com/q/52357964
has body: My question is similar to 'Combine pandas string columns with missing values ' and 'How to merge/combine columns in pandas?' but as the cells I want to combine contain lists, all the given answers don't work. Simplified, my df looks like this: players players1 players2 players3 1 ['1','2'] 2 ['2','4'] 3 ['1','4'] 4 ['1','5'] 5 ['3','5'] 6 7 ['3','4'] (So i know there will never be values in two of the columns.) Now I want to add a new column combining the lists: players players1 players2 players3 players_combine 1 ['1','2'] ['1','2'] 2 ['2','4'] ['2','4'] 3 ['1','4'] ['1','4'] 4 ['1','5'] ['1','5'] 5 ['3','5'] ['3','5'] 6 7 ['3','4'] ['3','4'] I tried many things - mainly variations of the linked answers, my last idea was a cascading np.where. But it didn't work. Only the values from 'players' showed up in the combined column. df['players_combine'] = np.where(df.players.notnull(),df.players.values,np.where(df.players1.notnull(),df.players1.values,np.where(df.players2.notnull(),df.players2.values,np.where(df.players3.notnull(),df.players3.values,np.nan)))) EDIT: As asked in the comments: df.head(5).to_dict() {'players': {'5b41800eaffb061b88c4beac': ['57005', '124021', '132037', '78523', '111742', '133892', '76431', '78066', '138749', '132358', '77857', '69756', '133745', '278877', '247798', '108106', '127464', '296770'], '5b41800eaffb061b88c4bead': ['18929', '110183', '28401', '302853', '296768', '94912', '93671', '52060', '43282', '132364', '140646', '77861', '19787', '133790', '312666', '76336', '317219', '137849'], '5b41800daffb061b88c4bc7f': 'nan', '5b41800eaffb061b88c4bd62': 'nan', '5b41800eaffb061b88c4bd65': 'nan'}, 'players1': {'5b41800eaffb061b88c4beac': nan, '5b41800eaffb061b88c4bead': nan, '5b41800daffb061b88c4bc7f': ['57005', '124021', '132037', '78523', '111742', '133892', '296770', '78066', '138749', '132358', '77857', '69756', '133745', '278877', '247798', '108106', '127464', '76431'], '5b41800eaffb061b88c4bd62': '', '5b41800eaffb061b88c4bd65': ''}, 'pl…
has comment: http://stackoverflow.com/comment/91660680
possible better answer: http://stackoverflow.com/a/52358078
downvote count: 0
has comment: http://stackoverflow.com/comment/91660504
has comment: http://stackoverflow.com/comment/91660483
favorite count: 0
has answer: http://stackoverflow.com/a/52413546
linked to: http://stackoverflow.com/q/46563833
tagged with: python
has comment: http://stackoverflow.com/comment/91660551
has answer: http://stackoverflow.com/a/52358094
has comment: http://stackoverflow.com/comment/91660433
linked to: http://stackoverflow.com/q/45976585
answer count: 4
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91660546
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52413546
has comment: http://stackoverflow.com/comment/91660511
has title: Combine Pandas columns containing list objects
has answer: http://stackoverflow.com/a/52358196
has answer: http://stackoverflow.com/a/52358078
has comment: http://stackoverflow.com/comment/91660436
tagged with: numpy
tagged with: pandas
has comment: http://stackoverflow.com/comment/91660437

http://stackoverflow.com/q/52372690
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91690117
tagged with: python
accepted answer: http://stackoverflow.com/a/52376110
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/91693321
has answer: http://stackoverflow.com/a/52376110
tagged with: scipy
has comment: http://stackoverflow.com/comment/91727208
has comment: http://stackoverflow.com/comment/91690164
type: Question
has comment: http://stackoverflow.com/comment/91690226
tagged with: numpy
has comment: http://stackoverflow.com/comment/91692307
has comment: http://stackoverflow.com/comment/91693256
score: -1
has body: I have been trying to find out a way in order to eliminate outliers from a dataset. The outliers are removed the following way: Any value which results into a 10% reduction in R2 value needs to be removed. When 4.2 in A-data set got replaced with 1.3 (in B-dataset), it changed the R2 >10% and thus was eliminated in the C-dataset. However, when 0.7 in A was replaced with 0.9, it would not change the correlation coefficient by 10% and thus was not removed from C-dataset. An image is attached herewith. In the image, -plot A has R2 of 1.0 -plot B has R2 of 0.8294 (1.3 is the outlier since it causes >10% lowering of R2 values) -plot C has R2 of 1.0 (on removing 1.3 from the dataset) How do I go about this issue. I need to use python to get to the solution. Out of the 10 data points a maximum of only 3 data points can be removed inorder to improve the correlation. I apologize if this question was asked before. Thanks a ton for the help!
answer count: 1
downvote count: 1
has title: Keep eliminating data points until good correlation coefficient is obtained
tagged with: scikit-learn

http://stackoverflow.com/q/52406665
downvote count: 0
score: 1
type: Question
has body: I'm building an app using Python. I used CX_Freeze to package it for Mac. However when I install on latest Mac High Sierra version it gives this error: errorrequests.exceptions.SSLError: HTTPSConnectionPool(host='api.keygen.sh', port=443): Max retries exceeded with url: /v1/accounts/xxxxx/licenses/actions/validate-key (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",))
has title: How to fix openssl error in Mac Python app?
upvote count: 1
tagged with: macos
favorite count: 0
tagged with: cx-freeze
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91716278
type: AnswerComment
comment on: http://stackoverflow.com/a/52385976
has text: You should probably mention plain no arg `super()`
score: 0
type: Comment

http://stackoverflow.com/comment/91592943
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52322385
has text: `columns = df.columns` `if __name__ == '__main__':` `pool = mp.Pool(4)` `resultpool = pool.map(processing, columns)`. Is it Right?

confidence-interval
tags question: http://stackoverflow.com/q/52308659
tag name: confidence-interval
type: Tag

http://stackoverflow.com/q/52424647
score: 1
linked to: http://stackoverflow.com/q/52424560
has comment: http://stackoverflow.com/comment/91792824
favorite count: 0
has title: Unable to split a string wirh remainder in python 2
linked to: http://stackoverflow.com/q/10792970
has comment: http://stackoverflow.com/comment/91792241
type: Question
duplicate of: http://stackoverflow.com/q/52424560
tagged with: python
has body: In python I have e.g. the following string 433 65040 9322 /opt/conda/envs/python2/bin/python -m ipykernel_launcher which I can split according to the following code in python 3: text = " 433 65040 9322 /opt/conda/envs/python2/bin/python -m ipykernel_launcher" pid,rss,etime,*remainder = text.split() However, when I try the same in python 2.7.12, I get a SyntaxError: In [1]: text = " 433 65040 9322 /opt/conda/envs/python2/bin/python -m ipykernel_launcher" In [2]: a,b,c,*d = text.split() File "&lt;ipython-input-2-a87c46b7bdb7&gt;", line 1 a,b,c,*d = text.split() ^ SyntaxError: invalid syntax How can I do that in python2?
upvote count: 1
has comment: http://stackoverflow.com/comment/91792057
duplicate of: http://stackoverflow.com/q/16563623
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91792590
tagged with: python-2.7
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/91703173
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52378957
has text: Is there a reason you don't parse this into a tree? A common approach is to convert into a variant which serializes into RPN, i.e. the root of each expression is the operator, and the branches are the operands.
score: 1

http://stackoverflow.com/q/52308735
has comment: http://stackoverflow.com/comment/91565006
downvote count: 3
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91564572
type: UnansweredQuestion
tagged with: shapes
has answer: http://stackoverflow.com/a/52308882
tagged with: python
tagged with: matplotlib
type: Question
answer count: 2
has body: I'm trying to get values in array (files) and I want to save them in a directory so I'm using plt.imsave(os.path.join()) and I have a problem : code : for i in tab: plt.imsave(os.path.join(target_directory,str(i)), tab) I get this error AttributeError: 'list' object has no attribute 'shape' Someone has an idea please ? Thanks
score: -2
has title: AttributeError: 'list' object has no attribute 'shape' problem
has answer: http://stackoverflow.com/a/52308783

http://stackoverflow.com/q/52387656
favorite count: 0
has answer: http://stackoverflow.com/a/52388367
has body: I am using the python kubernetes api with list_namespaced_pod to get the pods in my namespace. Now I would like to filter them, using the optional label selector parameter. The documention describes this parameter as A selector to restrict the list of returned objects by their labels. Defaults to everything. It does not bother to give an example. On this website, I found several possibilities on how to use the attribute. I already tried label_selector='label=my_label' label_selector='label:my_label' label_selector='my_label' non of which is working. How do I use the parameter label_selector correctly?
tagged with: kubernetes
tagged with: python
answer count: 4
accepted answer: http://stackoverflow.com/a/52388367
upvote count: 24
type: AnsweredQuestion
score: 24
has answer: http://stackoverflow.com/a/70300151
type: Question
has answer: http://stackoverflow.com/a/55141320
has answer: http://stackoverflow.com/a/58093744
has title: How can I get pods by label, using the python kubernetes api?
downvote count: 0
tagged with: label
possible better answer: http://stackoverflow.com/a/55141320

http://stackoverflow.com/comment/91659863
comment on: http://stackoverflow.com/q/52357560
has text: @PedroLobito But that has no explanation?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91560837
type: QuestionComment
has text: And also, can you show us what you have tried so far?
type: Comment
comment on: http://stackoverflow.com/q/52306666
score: 0

http://stackoverflow.com/comment/91748372
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52401479
has text: Or just use the cache framework https://docs.djangoproject.com/en/2.1/topics/cache/
score: 0

http://stackoverflow.com/a/52423290
upvote count: 2
has comment: http://stackoverflow.com/comment/91916193
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52414555
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52414555
downvote count: 0
has body: You may want to check if the service account used by your deployed App Engine app holds the necessary permissions for logging. It's usually a service account like PROJECT_ID@appspot.gserviceaccount.com, unless you have changed it. You may add the logging > Logs writer role to that service account in the Developer Console > IAM &amp; Admin section.

http://stackoverflow.com/comment/91757144
type: QuestionComment
comment on: http://stackoverflow.com/q/52391412
score: 0
has text: I'm not that familiar with Python, much less the libraries for it. I could create something in C, but there should already be examples of CRC8 implemented in C.
type: Comment

http://stackoverflow.com/comment/91516813
has text: For the array append to work, `E` has to start as a (0,2) shape array, and `D[i]` has to be turned into a (1,2) shaped array. Even I had to hunt-n-peck to get that right.
score: 1
comment on: http://stackoverflow.com/q/52284137
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91526173
has text: I have pip installed properly and easy install also
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52285684
type: Comment

http://stackoverflow.com/comment/91738576
has text: @Devin I am not sure why, but somewhat just replaces with `'\\1\\2'`
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52396961

http://stackoverflow.com/comment/91667794
has text: Eval is evil. No matter if it's Python, PHP or anything else. Have my upvote for telling OP
score: 0
comment on: http://stackoverflow.com/a/52361681
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91833030
type: Comment
has text: i have added view. can make me clear with this example ?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52423588

http://stackoverflow.com/comment/110214355
comment on: http://stackoverflow.com/a/57466875
type: AnswerComment
has text: Hi Jitesh, thanks for your answer. We tried these zip codes 03060 and 03062. They worked fine with or without 'False' but when we used 03060 and 02222, the same error returned for False & True.
score: 0
type: Comment

http://stackoverflow.com/q/52313237
tagged with: numpy
answer count: 2
possible better answer: http://stackoverflow.com/a/52313613
has answer: http://stackoverflow.com/a/52313613
has answer: http://stackoverflow.com/a/52314476
tagged with: python-xarray
score: 0
has body: I have a big problem in computing a mask containing zeros and one's but preserving the nan-values. Lets say I have a numpy-ndarray ab = numpy.arange(0,10,0.5) Now I emulate to have a nan-value: ab[3]=0. Now 'ab' looks like: ab= array([ 0. , 0.5, 1. , nan, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5.,5.5, 6. , 6.5, 7. , 7.5, 8. , 8.5, 9. , 9.5]) Now I want to mask all values below 5 to be '0' and all others to be '1' except for the nan-values, which should remain in the result. I cannot do this with 'numpy.where' because it deletes the nan-values: In [12]: numpy.where(a &lt; 5, 1.0, 0.0) /usr/bin/ipython3:1: RuntimeWarning: invalid value encountered in less #!/usr/bin/env python3 Out[12]: array([ 1., 1., 1., 0., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) What do I have to do to preserve the nan-values? Update: The solution with xarray is easy because the latest version supports a three-argument where-functionality. However, the NaN-Values remain in the result file.
has title: Where function with numpy or xarray giving back the results including nan values
has comment: http://stackoverflow.com/comment/91578865
tagged with: python
accepted answer: http://stackoverflow.com/a/52314476
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91602899
has comment: http://stackoverflow.com/comment/91606788
type: Question

http://stackoverflow.com/q/52310022
downvote count: 0
has title: TensorFlow how to separate building from executing for data parallelism
accepted answer: http://stackoverflow.com/a/52311391
answer count: 1
favorite count: 0
upvote count: 2
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52311391
tagged with: tensorflow
type: Question
has body: In TensorFlow usually modules are encapsulated in functions or classes and abstract the creation of the needed variables to call them for example net = slim.fully_connected(inputs=input, num_output=neurons ..) net = tf.layers.conv2d(net, num_filters, filter_size ..) Here the weights and biases for each of each operation will be created at first and then reused. When we want to achieve data parallelism we want the variables to be created and stored on the CPU, and then sent into the GPUs along with the data, like in the following diagram In the cifar10_multi_gpu_train example you can see that they don't use the tf.layers if you examine cifar10.py on the same directory you'll see that they use the lower level operations of fully_connected and conv2d and manually create the kernels, weights and biases on the CPU. This could be very cumbersome if we want to use complicated structures that are already implemented for ease of use in TensorFlow. My question is: Can we use high level module abstractions (from slim/tf.layers and others that abstract the variables creation) in a fashion where the variables will be created on the CPU but the operations will execute on GPU?
score: 2

http://stackoverflow.com/comment/91664695
type: AnswerComment
has text: Closing double quote is missing, I think.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52359980

http://stackoverflow.com/q/52302453
has title: How to read a dictionary from this text file?
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91553214
score: 1
has answer: http://stackoverflow.com/a/52302618
possible better answer: http://stackoverflow.com/a/52302613
has answer: http://stackoverflow.com/a/52302613
has body: I am still new to python and I am playing around with saving data to text files. My problem is that when I try to access a dictionary it comes up with this error TypeError: string indices must be integers but I don't know how to convert them. This is what's inside my file: Student 1/:{ "Topic 1" : 0,"Topic 2" : 0,"Topic 3" : 0,"Topic 4" : 4} Student 2/:{ "Topic 1" : 1,"Topic 2" : 2,"Topic 3" : 0,"Topic 4" : 0} Student 3/:{ "Topic 1" : 1,"Topic 2" : 0,"Topic 3" : 0,"Topic 4" : 1} This is my code: import ast #I thought this would fix the problem def main(): data = {} with open("test.txt") as f: for line in f: content = line.rstrip('\n').split('/:') data[content[0]] = ast.literal_eval(content[1]) f.close() print(data["Student 1"["Topic 1"]]) # works if I only do data[Student 1] main() If there is a more efficient way of storing the data?
answer count: 2
has comment: http://stackoverflow.com/comment/91552900
has comment: http://stackoverflow.com/comment/91552870
accepted answer: http://stackoverflow.com/a/52302618
has comment: http://stackoverflow.com/comment/91553681
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x

http://stackoverflow.com/q/52372780
favorite count: 0
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/91690486
has body: I want to convert a Python Script into an exe File. I used Pyinstaller but when I run the exe, it opens a console and closes immediately. The script contains os.system, which means that it executes commands to the console. Could it be that this is the problem? Where is my mistake? import os import pandas import twitterscraper os.system("twitterscraper Trump --limit 10 -c --output=Trump.csv") df = pandas.read_csv("Trump.csv") print(df)
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91690215
tagged with: execution
has title: Can Python Scripts with os.system be converted to a standalone exe?
tagged with: operating-system
tagged with: python
tagged with: exe

http://stackoverflow.com/comment/91647810
score: 3
comment on: http://stackoverflow.com/q/52351217
has text: @TheScientificMethod: Once the input string has been consumed in full, why would you treat the fact that there is nothing left as the empty string? And if you do, shouldn't this result in an infinite loop? By this logic there is always an empty string left.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91822231
type: AnswerComment
comment on: http://stackoverflow.com/a/52437803
type: Comment
has text: Hi,I have another question, when I `sudo apt install build-essential raspberrypi-kernel-headers`, the kernel-headers version is different between `/lib/modules/(kernel-headers-version)` with `$(uname -r)`
score: 0

http://stackoverflow.com/a/52278736
answers question: http://stackoverflow.com/q/52278686
has comment: http://stackoverflow.com/comment/91506512
type: Answer
has comment: http://stackoverflow.com/comment/91506900
has comment: http://stackoverflow.com/comment/91505857
has comment: http://stackoverflow.com/comment/91506084
upvote count: 1
has comment: http://stackoverflow.com/comment/91507047
has comment: http://stackoverflow.com/comment/91506816
has comment: http://stackoverflow.com/comment/91505501
has comment: http://stackoverflow.com/comment/91505823
score: 1
has comment: http://stackoverflow.com/comment/91505819
has comment: http://stackoverflow.com/comment/91506700
has comment: http://stackoverflow.com/comment/91506654
has body: escape all of your backslashes by putting another backslash in front of them... hex_string = "\\xad\\x07\\x40\\x00" print "\x01" * 28 + hex_string that should do the trick! EDIT: regarding your question... import re hex_string = "\\xad\\x07\\x40\\x00" other_string = 28*"\\x01" hex_string = re.sub("\\\\", "", hex_string) other_string = re.sub("\\\\", "", other_string) print(other_string + hex_string) gives...
has comment: http://stackoverflow.com/comment/91506546
has comment: http://stackoverflow.com/comment/91506469
has comment: http://stackoverflow.com/comment/91506989
downvote count: 0

http://stackoverflow.com/a/58888405
upvote count: 1
has body: I was having the same issue. I resolved this error by downgrading open cv. pip install opencv-python==3.3.0.9
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52349669
score: 1

iframe
tags question: http://stackoverflow.com/q/52428409
tag name: iframe
type: Tag
tags question: http://stackoverflow.com/q/52303910

http://stackoverflow.com/comment/92438200
comment on: http://stackoverflow.com/a/52416260
has text: If I want to change specific value, e.g, '0' value only to '0.000' in specific column, what should I do? If I use your method above, it will change all '0's in all columns including value '110', not specific '0' only.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52336831
favorite count: 0
has answer: http://stackoverflow.com/a/52336897
tagged with: python
accepted answer: http://stackoverflow.com/a/52336897
score: 2
type: AnsweredQuestion
upvote count: 2
has title: HackerRank Python print STDOUT doesn't seem to work
type: Question
has answer: http://stackoverflow.com/a/55973529
has body: I am very new to Python so am trying out the 'Counting Valleys' question on HackerRank. I have written my solution in PyCharm and it works fine/gives the correct answer to the expected output of the solution. I have tried to search on this site but nothing concrete seems to have come up for this, so I must have missed out something obvious. The problem is that when I port the code across to HackerRank, it just says 'Wrong Answer'. I would like to understand what the issue is by using 'print' or anything else to get feedback. Below I have added 'print' lines to different places to show areas I have tried too. This is the second solution that I have run into this problem, any advice/suggestions would be appreciated as its super annoying and frustrating to continue working with, any help appreciated. # !/bin/python import math import os import random import re import sys import logging # Complete the countingValleys function below. def countingValleys(n, s): print('Please print') if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(raw_input()) s = raw_input() sea_level = 0 valleys = 0 last_step = '' in_same_valley = False print('Ok maybe here?') for step in s: if step == 'D': if last_step == 'D' and sea_level &lt;= 0: if not in_same_valley: valleys += 1 in_same_valley = True sea_level -= 1 else: sea_level += 1 in_same_valley = False last_step = step print('Ok perhaps here?') fptr.write(str('valleys') + '\n') fptr.close() print('Ok try here?')
tagged with: stdout
possible better answer: http://stackoverflow.com/a/55973529
tagged with: printing
answer count: 2
downvote count: 0

matplotlib
tags question: http://stackoverflow.com/q/52353791
tags question: http://stackoverflow.com/q/52284040
tags question: http://stackoverflow.com/q/52321077
tags question: http://stackoverflow.com/q/52368870
tags question: http://stackoverflow.com/q/52287321
tags question: http://stackoverflow.com/q/52290426
tags question: http://stackoverflow.com/q/52312350
tags question: http://stackoverflow.com/q/52322764
tags question: http://stackoverflow.com/q/52338675
tags question: http://stackoverflow.com/q/52407063
tags question: http://stackoverflow.com/q/52349684
tags question: http://stackoverflow.com/q/52344307
tags question: http://stackoverflow.com/q/52273546
tags question: http://stackoverflow.com/q/52389489
tags question: http://stackoverflow.com/q/52410618
tags question: http://stackoverflow.com/q/52408274
tags question: http://stackoverflow.com/q/52339088
tags question: http://stackoverflow.com/q/52420515
tags question: http://stackoverflow.com/q/52366673
tags question: http://stackoverflow.com/q/52384406
tags question: http://stackoverflow.com/q/52427826
tags question: http://stackoverflow.com/q/52402473
tags question: http://stackoverflow.com/q/52358016
tags question: http://stackoverflow.com/q/52375243
tags question: http://stackoverflow.com/q/52285104
tags question: http://stackoverflow.com/q/52328595
tags question: http://stackoverflow.com/q/52358798
tags question: http://stackoverflow.com/q/52405971
tags question: http://stackoverflow.com/q/52412406
tags question: http://stackoverflow.com/q/52331662
tags question: http://stackoverflow.com/q/52305912
tags question: http://stackoverflow.com/q/52376329
tags question: http://stackoverflow.com/q/52362504
tag name: matplotlib
tags question: http://stackoverflow.com/q/52284019
tags question: http://stackoverflow.com/q/52411520
tags question: http://stackoverflow.com/q/52387433
tags question: http://stackoverflow.com/q/52410172
tags question: http://stackoverflow.com/q/52318464
tags question: http://stackoverflow.com/q/52409115
tags question: http://stackoverflow.com/q/52304186
tags question: http://stackoverflow.com/q/52291423
tags question: http://stackoverflow.com/q/52377946
tags question: http://stackoverflow.com/q/52364815
tags question: http://stackoverflow.com/q/52420582
tags question: http://stackoverflow.com/q/52320969
tags question: http://stackoverflow.com/q/52427782
tags question: http://stackoverflow.com/q/52312174
tags question: http://stackoverflow.com/q/52387815
tags question: http://stackoverflow.com/q/52423697
tags question: http://stackoverflow.com/q/52369543
tags question: http://stackoverflow.com/q/52320644
tags question: http://stackoverflow.com/q/52429323
tags question: http://stackoverflow.com/q/52390757
tags question: http://stackoverflow.com/q/52273543
tags question: http://stackoverflow.com/q/52420470
tags question: http://stackoverflow.com/q/52282194
tags question: http://stackoverflow.com/q/52355093
tags question: http://stackoverflow.com/q/52411321
tags question: http://stackoverflow.com/q/52298821
tags question: http://stackoverflow.com/q/52339645
tags question: http://stackoverflow.com/q/52350642
tags question: http://stackoverflow.com/q/52359008
tags question: http://stackoverflow.com/q/52362966
tags question: http://stackoverflow.com/q/52277625
tags question: http://stackoverflow.com/q/52381689
tags question: http://stackoverflow.com/q/52331622
tags question: http://stackoverflow.com/q/52317507
tags question: http://stackoverflow.com/q/52403381
tags question: http://stackoverflow.com/q/52331377
tags question: http://stackoverflow.com/q/52281055
tags question: http://stackoverflow.com/q/52335555
tags question: http://stackoverflow.com/q/52349227
tags question: http://stackoverflow.com/q/52423635
tags question: http://stackoverflow.com/q/52383129
tags question: http://stackoverflow.com/q/52293445
tags question: http://stackoverflow.com/q/52308735
tags question: http://stackoverflow.com/q/52412289
tags question: http://stackoverflow.com/q/52316683
tags question: http://stackoverflow.com/q/52393611

http://stackoverflow.com/comment/91730469
type: Comment
has text: can you tell me what is the output?
comment on: http://stackoverflow.com/a/52389785
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91578863
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52313468
has text: I'm a bit perplexed that `gboffi1` comes out slower than `RaunaqJain`, I have to ponder about my _"Calling a built-in should be more efficient than a function call and a loop, shouldn't it?"_ for a while...

http://stackoverflow.com/a/74600006
has body: Isn't it like trying to host H2O models in python apps? Looks like a bridge from python to Java is required here too. Such bridges are not stable at all, been there, tested them. Just a general suggestion: do not mix languages between ML algos and apps code, train in python, serve in python, re-validate also in python. Legacy R and H2O models can be always re-fitted in python.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52393301

http://stackoverflow.com/q/52285862
type: Question
answer count: 6
has answer: http://stackoverflow.com/a/52285989
score: 4
tagged with: argument-unpacking
has answer: http://stackoverflow.com/a/52285894
has answer: http://stackoverflow.com/a/52285933
has body: See below example: &gt;&gt;&gt;f = [[1],[2],[3]] &gt;&gt;&gt;max(f) Out[21]: [3] &gt;&gt;&gt;max(*f) Out[22]: [3] The unpack operator did not have an effect here, I am trying to unpack a list and get a maximal value of matrix(two dim list).
has comment: http://stackoverflow.com/comment/91520106
possible better answer: http://stackoverflow.com/a/52285916
favorite count: 0
has comment: http://stackoverflow.com/comment/91543967
has answer: http://stackoverflow.com/a/52285916
has answer: http://stackoverflow.com/a/52285961
tagged with: python
upvote count: 4
type: AnsweredQuestion
has title: Why does max(*list) and max(list) do the same thing in python?
has answer: http://stackoverflow.com/a/52285913
downvote count: 0
accepted answer: http://stackoverflow.com/a/52285989

http://stackoverflow.com/comment/91547945
type: Comment
type: QuestionComment
has text: Also, just as a formatting matter: if you indent code with four spaces, you no longer need the ` character. It just messes things up.
score: 1
comment on: http://stackoverflow.com/q/52299780

http://stackoverflow.com/comment/91751741
type: QuestionComment
has text: @CalebHoward so if `graphics` is imported - you want to use their Point and Rectangle or you want to use your own implementations?
comment on: http://stackoverflow.com/q/52403954
score: 0
type: Comment

http://stackoverflow.com/q/52401321
tagged with: random
has title: Generate list of 'almost' random tuples
answer count: 1
has comment: http://stackoverflow.com/comment/91746820
has comment: http://stackoverflow.com/comment/91746573
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/91746511
has answer: http://stackoverflow.com/a/52401572
tagged with: python
type: AnsweredQuestion
tagged with: list
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/91746673
has comment: http://stackoverflow.com/comment/91746473
accepted answer: http://stackoverflow.com/a/52401572
has comment: http://stackoverflow.com/comment/91746493
score: -1
tagged with: list-comprehension
has body: Let's say that list 'l' contains tuples and has an even number of elements. Every tuple consists of 3 numbers (int) 0 &lt;= x &lt;= 255 And now the fun part, there is a following pattern: l[0] = l[1], l[2] = l[3], l[4] = l[5] ..... So the list looks for example like this: l[0] = (100, 200, 10) l[1] = (100, 200, 10) l[2] = (250, 45, 30) l[3] = (250, 45, 30) l[4] = (30, 10, 5) l[5] = (30, 10, 5) ....... The problem is not how to generate the list because that's easy, I want to know if there is any way to do it in one line, using some smart tricks and list comprehension etc. Right now the code looks like this: from random import randint b = [] for _ in range(4): b += [(randint(0, 255), randint(0, 255), randint(0, 255))]*2 # example for how b looks: # [(206, 89, 40), (206, 89, 40), (36, 115, 91), (36, 115, 91), (232, 55, 96), (232, 55, 96), (183, 114, 179), (183, 114, 179)]
tagged with: tuples

http://stackoverflow.com/q/52280117
has answer: http://stackoverflow.com/a/52282401
score: 0
answer count: 1
has title: Reverse of tf.parse_single_example
type: UnansweredQuestion
has body: I have a pipeline that takes as inputs tfrecords, applies some transformations and writes again to tfrecords. I am using tf.parse_single_example to parse the single examples. This returns a dictionary of keys and tensors to which I apply the transformations. I am not able to convert that dictionary back to a tf.Example. I wanted to do this by using example = {some_key: tf.train.Feature(bytes_list=tf.train.BytesList(value=[some_value])) example = tf.train.Example(features=tf.train.Features(feature=example)) but I think this was meant for numpy arrays as tf complains that it cannot iterate through tensors (some_value here) unless in eager mode. Any idea how to inverte tf.parse_single_example?
tagged with: python
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/52322764
type: Question
score: 0
tagged with: pandas
answer count: 1
has body: I have the following code for 27 subplots in a 9x3 single plot. I want to add specific individual titles to each subplot, eg. "District 7 - Brooklyn." However, this code repeats both the data and the title for all 27 subplots, presumably because of the last line of code. I have consulted this previous SO question and tried all three of those methods, but each one erases the data in the subplot when the title is added or is broadcast incorrectly. fig, axes = plt.subplots(9,3,figsize=(30,80)) for ax in axes.flatten(): ax1 = district_1_change.drop(['TOTAL'], axis=1).plot.bar(legend=True, ax=ax) ax1.set_title("District 1: Eastern Long Island", fontsize=18) ax2 = district_2_change.drop(['TOTAL'], axis=1).plot.bar(legend=True, ax=ax) ax2.set_title("District 2: Southern Long Island", fontsize=18) ax3 = district_3_change.drop(['TOTAL'], axis=1).plot.bar(legend=True, ax=ax) ax3.set_title("District 3: Northern Long Island", fontsize=18) ax4 = district_4_change.drop(['TOTAL'], axis=1).plot.bar(legend=True, ax=ax) ax4.set_title("District 4: Central, Southern Nassau County", fontsize=18) ax5 = district_5_change.drop(['TOTAL'], axis=1).plot.bar(legend=True, ax=ax) ax5.set_title("District 5: Queens", fontsize=18) ax6 = district_6_change.drop(['TOTAL'], axis=1).plot.bar(legend=True, ax=ax) ax6.set_title("District 6: Queens", fontsize=18) ax7 = district_7_change.drop(['TOTAL'], axis=1).plot.bar(legend=True, ax=ax) ax7.set_title("District 7: Queens", fontsize=18) ax8 = district_8_change.drop(['TOTAL'], axis=1).plot.bar(legend=True, ax=ax) ax8.set_title("District 8: Brooklyn, Queens", fontsize=18) ax9 = district_9_change.drop(['TOTAL'], axis=1).plot.bar(legend=True, ax=ax) ax9.set_title("District 9: Brooklyn", fontsize=18) ax10 = district_10_change.drop(['TOTAL'], axis=1).plot.bar(legend=True, ax=ax) ax10.set_title("District 10: Upper West Side, FiDi, Greenwich Village, Borough Park (BK)", fontsize=18) ax11 = district_11_change.drop(['TOTAL'], axis=1).plot.bar(legend=True, ax=ax) ax11…
has comment: http://stackoverflow.com/comment/91616233
linked to: http://stackoverflow.com/q/25239933
has answer: http://stackoverflow.com/a/52323222
tagged with: python
accepted answer: http://stackoverflow.com/a/52323222
has title: Specific Titles for Subplots in for-loop Plot repeats last subplot
tagged with: plot
duplicate of: http://stackoverflow.com/q/25239933
type: AnsweredQuestion
tagged with: matplotlib

http://stackoverflow.com/q/52332268
type: Question
has body: RuntimeError: CMake must be installed to build the following extensions: dlib Failed building wheel for dlib Running setup.py clean for dlib Failed to build dlib
linked to: http://stackoverflow.com/q/48503646
has answer: http://stackoverflow.com/a/55792701
score: 0
has comment: http://stackoverflow.com/comment/91611685
favorite count: 0
has answer: http://stackoverflow.com/a/64035724
has comment: http://stackoverflow.com/comment/91647614
tagged with: python
upvote count: 4
answer count: 4
downvote count: 4
has answer: http://stackoverflow.com/a/59627334
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/115637223
has answer: http://stackoverflow.com/a/52564257
has title: pip install face_recognition giving error
tagged with: face-recognition

http://stackoverflow.com/q/52275277
has title: Printing all texts, required only one
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/52275333
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52275414
has answer: http://stackoverflow.com/a/52276184
tagged with: selenium
has answer: http://stackoverflow.com/a/52275414
type: Question
has body: I have a html file: Some Text1 Hello Some Text2 Some Text3 Hi1 Hi2 </strong I want to print only Hello in my python script using selenium, so I tried: element = driver.find_element_by_xpath("//div[@class='panel-heading']") for element in driver.find_elements_by_tag_name('strong'): print (element.text) The result is: Hello Hi1 Hi2 But I want only: Hello
has answer: http://stackoverflow.com/a/52275354
score: 0
tagged with: for-loop
accepted answer: http://stackoverflow.com/a/52275354
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91498075
tagged with: element

http://stackoverflow.com/a/52367869
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/110671007
type: Answer
has comment: http://stackoverflow.com/comment/110485793
score: 16
has comment: http://stackoverflow.com/comment/111095058
upvote count: 16
has comment: http://stackoverflow.com/comment/110653010
accepted answer of: http://stackoverflow.com/q/52353962
has body: I found my answer, hope it can help someone else. Base on django docs. A test runner is a class defining a run_tests() method. Django ships with a DiscoverRunner class that defines the default Django testing behavior. This class defines the run_tests() entry point, plus a selection of other methods that are used to by run_tests() to set up, execute and tear down the test suite. In case of this question, there is 2 helpful methods in this class.setup_databases and teardown_databases so we can overwrite them to initialize data for all test classes. from django.test.runner import DiscoverRunner as BaseRunner class MyMixinRunner(object): def setup_databases(self, *args, **kwargs): temp_return = super(MyMixinRunner, self).setup_databases(*args, **kwargs) # do something return temp_return def teardown_databases(self, *args, **kwargs): # do somthing return super(MyMixinRunner, self).teardown_databases(*args, **kwargs) class MyTestRunner(MyMixinRunner, BaseRunner): pass after defining test runner class we need to add TEST_RUNNER to settings: TEST_RUNNER = 'path.to.MyTestRunner'
has comment: http://stackoverflow.com/comment/110703028
has comment: http://stackoverflow.com/comment/111094974
answers question: http://stackoverflow.com/q/52353962
has comment: http://stackoverflow.com/comment/111095021

http://stackoverflow.com/comment/91548152
comment on: http://stackoverflow.com/q/52281454
has text: Try like this Example [How to extract a subset](https://docs.python.org/3/library/tarfile.html#tar-examples)
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91653740
comment on: http://stackoverflow.com/a/52354342
has text: ['1', '5:00', '5:59', '6:00', '6:59', '13:00', '13:59', '14:00', '14:59', '21:00', '21:59', '22:00', '22:59']. In this example I have a gap between 6:59 and 13:00. Hence my first slot would start at 5 an finish at 6:69. Second would start at 13 and finish at 14:59, since there is break between 14:59 and 21:00. Essentially if there is break in sequence.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52399156
has comment: http://stackoverflow.com/comment/91742699
has comment: http://stackoverflow.com/comment/91743191
upvote count: 1
has body: Try it this way: import datetime try: [your_code] except KeyboardInterrupt as e: # catch SIGINT print("{}: {}".format(datetime.datetime.now(), e), flush=True) except: # catch unknown exception print("{}: other exception!".format(datetime.datetime.now()), flush=True)
has comment: http://stackoverflow.com/comment/91743098
score: 1
has comment: http://stackoverflow.com/comment/91742571
has comment: http://stackoverflow.com/comment/91742534
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52397724
downvote count: 0
has comment: http://stackoverflow.com/comment/91743393
has comment: http://stackoverflow.com/comment/91743479
type: Answer
has comment: http://stackoverflow.com/comment/91742845
accepted answer of: http://stackoverflow.com/q/52397724

jsp
tags question: http://stackoverflow.com/q/52359195
type: Tag
tag name: jsp

http://stackoverflow.com/a/52379777
has comment: http://stackoverflow.com/comment/91798977
has comment: http://stackoverflow.com/comment/91924160
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/52379649
type: Answer
answers question: http://stackoverflow.com/q/52379649
has comment: http://stackoverflow.com/comment/91929879
has body: You must not provide the --concurrency parameter as a command line argument, but in the config file only.

http://stackoverflow.com/comment/91776586
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52416568
has text: this is in a function correct

http://stackoverflow.com/q/52322794
favorite count: 0
has title: Keras: Model Predict, Error When Checking Input Shape
type: UnansweredQuestion
upvote count: 3
score: 3
has answer: http://stackoverflow.com/a/52323455
type: Question
answer count: 2
downvote count: 0
tagged with: keras
has body: I have a Keras model and a numpy array that I want to call predict on. Specifically, I have: a numpy.ndarray called test that looks like this: 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, 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, 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, 0, 0, 0, 0, 12920, 11891, 4605, 2425, 6780, 5096, 13821, 4405, 10345, 4468, 5910, 11891, 10906, 14994, 12073, 8581, 3544, 13846, 3110, 2425, 3407, 9631, 13846, 4479, 9964, 2556, 4479, 2686, 8895, 10959, 1531, 11891, 1494, 10376, 13846, 12856, 13846, 3110, 2425, 3407, 3267, 181, 4479, 14842, 4639, 7723, 11891, 11449, 2425, 5662, 2282, 5129, 2518, 13846, 4479, 4780, 2598, 4926, 543, 7304, 12020, 8143, 10998, 13846, 12853, 13846, 12856, 11891, 3785, 9131, 7448, 13846, 10376, 13846, 8245, 3788, 12211, 2425, 13614, 10049, 2556, 8245, 1406, 6423, 3110, 2425, 3407, 5726, 2619, 1494, 13694, 7434, 12086, 7304, 3267, 9184]) When I do test.shape, I see: (180,) When I do model.predict(test), I get back: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "...python2.7/site-packages/keras/engine/training.py", line 1152, in predict x, _, _ = self._standardize_user_data(x) File "...python2.7/site-packages/keras/engine/training.py", line 754, in _standardize_user_data exception_prefix='input') File "...python2.7/site-packages/keras/engine/training_utils.py", line 136, in standardize_input_data str(data_shape)) ValueError: Error when checking input: expected sequence to have shape (180,) but got array with shape (1,) Any idea what I'm doing incorrectly? Thanks!
has answer: http://stackoverflow.com/a/52323349
tagged with: python

http://stackoverflow.com/a/52300723
type: Answer
answers question: http://stackoverflow.com/q/52295087
score: 0
has body: I have implemented the content of our discussion in the comments above in the following manner; the computation is done on the bi-dimensional gray matrix that you have extracted. I have assigned zeroes and ones to the values of interest for the matrix being fed to the clusterer, which is in this case KMeans, although it can be replaced with other models as necessary. import cv2 import numpy as np filename = 'Dog.jpg' img = cv2.imread(filename) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) gray = np.float32(gray) dst = cv2.cornerHarris(gray,2,3,0.04) dst = cv2.dilate(dst,None) gray[dst&gt;0.01*dst.max()] = 1 gray[dst&lt;=0.01*dst.max()] = 0 from sklearn.cluster import KMeans km = KMeans(n_clusters=2) km.fit(gray) centers = km.cluster_centers_ from sklearn.metrics.pairwise import cosine_distances print(cosine_distances(centers)) The output is: [[0. 0.60477114] [0.60477114 0. ]] which is the matrix containing the pair-wise cosine distances of the centers. Further tweaking can be done on the call to .cornerHarris(), and in all truth, it should be checked whether the clusters extracted correspond at least vaguely to the tail and mouth of the dog. Additionally, generalisation of this method on other images may not be possible. It is unclear what would happen, for example, if the dog were to bite its tail: clusters would very likely be identified in ways unrelated to either the tail, the mouth or both. The more tweaking is done on the code for this particular image, then, the lower the potential for generalisation of this model: it's thus a dog chasing its own tail.

http://stackoverflow.com/q/52329220
answer count: 1
tagged with: dataframe
has body: I tried to convert the data frame to series But it shows the following error. I used pandas.Series(Dataframe) -> to convert Dataframe to series I want a output in the format of 1st image
has title: Convert dataframe to series for multiple column
upvote count: 5
accepted answer: http://stackoverflow.com/a/52332456
has comment: http://stackoverflow.com/comment/110683636
tagged with: series
linked to: http://stackoverflow.com/q/33246771
has comment: http://stackoverflow.com/comment/91611147
tagged with: pandas
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/91605544
favorite count: 0
type: Question
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52332456

http://stackoverflow.com/q/52284072
tagged with: conda
has comment: http://stackoverflow.com/comment/97087875
downvote count: 0
type: UnansweredQuestion
favorite count: 0
has title: Conda create is stuck at "solving package specifications"
tagged with: python-2.7
has answer: http://stackoverflow.com/a/75992654
type: Question
has answer: http://stackoverflow.com/a/77237331
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/135508391
has comment: http://stackoverflow.com/comment/119327858
has answer: http://stackoverflow.com/a/57986137
tagged with: python
has answer: http://stackoverflow.com/a/60983295
score: 18
has answer: http://stackoverflow.com/a/55323751
tagged with: anaconda
has body: I'm trying to create a Python 2.7 virtual environment with Anaconda so I can download some packages that are not compatible with Python 3.4. I'm working in Conda version 4.2.13. When I type the command conda create -n chemistry python=2.7 anaconda the whole thing freezes at the solving package specifications stage. Does anyone know what causes this or how I can go about fixing it?
linked to: http://stackoverflow.com/q/66888484
answer count: 5
upvote count: 18

http://stackoverflow.com/comment/91697997
comment on: http://stackoverflow.com/q/52376424
type: Comment
type: QuestionComment
score: 0
has text: @yogkm Sorry, I did not understand what you asked me. In Python I have that function called when I access one URL, in Android I put four parameters: I get name and city from two EditTexts and I format lat lon after calculating them from address with Geocode. At first lat lon are two `double` variables, for example, 45.4516914 9.161441700000001 but after the format they are 45,451691 9,161442.

http://stackoverflow.com/comment/91492303
type: Comment
has text: @rcshon no problem. I formulated it as an answer.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52272393

http://stackoverflow.com/a/52340347
has comment: http://stackoverflow.com/comment/91627865
type: Answer
accepted answer of: http://stackoverflow.com/q/52340318
answers question: http://stackoverflow.com/q/52340318
has comment: http://stackoverflow.com/comment/91627763
score: 0
has comment: http://stackoverflow.com/comment/91627782
has body: The problem is the unequal height and width in the default figsize. Use a square figure size with equal width und height as fig, ax = plt.subplots(figsize=(6,6)) with the correct desired output as below. Alternatively you can also use the following line of code (put anywhere after defining the ax and before showing) to make an equal aspect ratio as ax.set_aspect('equal') Output
type: AcceptedAnswer

http://stackoverflow.com/comment/91709733
comment on: http://stackoverflow.com/q/52316556
score: 0
type: Comment
type: QuestionComment
has text: I want to know that the pink circle and the grey circle are on the same level. So the green background should be level 0. bluk k and yellow B level 1. pink circle and grey circle : level 2. Is more clear ? ^^

http://stackoverflow.com/q/52287923
has comment: http://stackoverflow.com/comment/91523534
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/52351768
favorite count: 0
has comment: http://stackoverflow.com/comment/91523648
linked to: http://stackoverflow.com/q/5911382
has answer: http://stackoverflow.com/a/52351768
tagged with: python
type: AnsweredQuestion
has body: I'm trying to understand why some functions fail with threading in python. For example, I'm trying to use VideoCapture to grab an image from a webcam. This example works fine: from VideoCapture import Device cam = Device() cam.saveSnapshot('image.jpg') But when I put it on a thread I get an error. import threading from VideoCapture import Device def grab(): cam = Device() cam.saveSnapshot('image.jpg') thr = threading.Thread(target=grab) thr.start() thr.join() File "C:\Program Files\Python36\lib\site-packages\VideoCapture__init__.py", line 60, in init self.dev = vidcap.new_Dev(devnum, showVideoWindow) vidcap.Error: Creation of the filter graph failed. According to this reference, this function is not thread-safe. So is there any workaround to bypass similar issues like this? I tried to use threading.lock but got the same error. If I need to change the code, which part should I check?
has comment: http://stackoverflow.com/comment/91535013
downvote count: 0
score: 1
tagged with: multithreading
type: Question
has title: Make a function thread safe

http://stackoverflow.com/comment/91693343
comment on: http://stackoverflow.com/q/52373113
type: Comment
type: QuestionComment
has text: I also noticed that `download_dir` is different than `filename`. So the program is downloading one file and then trying to send another.
score: 0

http://stackoverflow.com/q/52327944
type: AnsweredQuestion
has title: Django Rest Framework model serializer: Set all fields to read only except one
type: Question
has body: The model that I'm using has a lot of fields. I want to be able to set all the fields to be read only except for one i.e. I want to allow only one particular field to be writable. Is there a shortcut to do this? I'm only aware of using "read_only_fields=('x','y') and I really don't want to type out all the fields especially if I'm going to make changes to the models later. "exclude =" also doesn't apply in this case.
has answer: http://stackoverflow.com/a/52328292
downvote count: 0
answer count: 1
tagged with: django-rest-framework
favorite count: 0
upvote count: 8
tagged with: django
tagged with: python
score: 8
accepted answer: http://stackoverflow.com/a/52328292

http://stackoverflow.com/q/52395837
has answer: http://stackoverflow.com/a/52406020
type: Question
has title: Table extraction with Scrapy failing
answer count: 1
score: 0
tagged with: python
tagged with: xpath
type: UnansweredQuestion
has body: I need to extract links in a table from a Website (classname internal), but I always get Crawled 0 pages, but downloader get a bunch of bytes. class geneDetails(scrapy.Spider): name = "details" def start_requests(self): urls = ['https://ecocyc.org/gene?orgid=ECOLI&amp;id=G7688'] for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): details = response.xpath('//*[contains(@class,"internal")]/tbody/tr').extract() for det in details: gene_det = det.xpath('./text()').extract() Already tried a lot of things, but never worked, the code above was my last try, sorry for anything, not a specialist on scrapy/xpath.
tagged with: web-scraping
tagged with: scrapy

http://stackoverflow.com/a/52425059
has comment: http://stackoverflow.com/comment/91795583
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91851814
has body: You missed the header argument in the above code that's why it is throwing header in every file append. df, header = pd.read_html(page) If you put header as 0 then it will give the results as you want but still you miss the top header as you default appending to empty file which don't has any data import csv from urllib.request import urlopen import pandas as pd contents = [] with open('WV_urls.csv','r') as csvf: # Open file in read mode urls = csv.reader(csvf) for url in urls: contents.append(url) # Add each url to list contents for url in contents: # Parse through each url in the list. page = urlopen(url[0]).read() df, header = pd.read_html(page,header=0) df.to_csv('WV_Licenses_Daily.csv', index=False, header=None, mode='a') You can create a empty data frame with required columns. After that you can append the data frames to it. import csv from urllib.request import urlopen import pandas as pd contents = [] df = pd.DataFrame(columns=['WV Number', 'Company', 'DBA', 'Address', 'City', 'State', 'Zip','County', 'Phone', 'Classification*', 'Expires']) #initialize the data frame with columns with open('WV_urls.csv','r') as csvf: # Open file in read mode urls = csv.reader(csvf) for url in urls: contents.append(url) # Add each url to list contents for url in contents: # Parse through each url in the list. page = urlopen(url[0]).read() df1, header = pd.read_html(page,header=0)#reading with header df=df.append(df1) # append to dataframe df.to_csv('WV_Licenses_Daily.csv', index=False)
has comment: http://stackoverflow.com/comment/91793245
accepted answer of: http://stackoverflow.com/q/52422610
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52422610

http://stackoverflow.com/comment/91511899
type: QuestionComment
has text: @OlivierMelançon I gather they don't want to print the backspaces.
comment on: http://stackoverflow.com/q/52281909
score: 0
type: Comment

http://stackoverflow.com/comment/91770107
has text: you can actually use `df.query` in case you didn't know http://pandas.pydata.org/pandas-docs/version/0.22.0/generated/pandas.DataFrame.query.html
comment on: http://stackoverflow.com/q/52413147
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52328448
has body: Classification needs discrete label as it predicts class(which is any one of the label) and Regression works with continuous data. As your output is class label, you need to perform classification
answers question: http://stackoverflow.com/q/52318155
score: 0
type: Answer

http://stackoverflow.com/q/52398563
has answer: http://stackoverflow.com/a/54836769
answer count: 3
has answer: http://stackoverflow.com/a/52398894
tagged with: amazon-web-services
tagged with: flask
tagged with: amazon-elastic-beanstalk
has title: Can't get flask to log to opt/python/log on Elastic Beanstalk AWS
tagged with: python
has body: I have been trying to get my Flask app to log to a log file. In elastic beanstalk I have a logger in my flask app that logs files to opt/python/log The file is successfully created but when I try to do something like log.warning('ERROR') The line does not show up correctly. I have tested to make sure my logger works correctly on localhost. I have read many stack overflow responses and believe it's a permissions issue, however when I try adding commands: 01_change_permissions: command: chmod g+s /opt/python/log 02_change_owner: command: chown root:wsgi /opt/python/log to .ebextensions Or even something like files: "/opt/elasticbeanstalk/tasks/taillogs.d/history.conf" : mode: "000755" owner: root group: root content: | /opt/log/python/history.log Nothing seems to work. Any help would be appreciated!
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/27552859
has comment: http://stackoverflow.com/comment/91743971
type: Question
has comment: http://stackoverflow.com/comment/91906109
has answer: http://stackoverflow.com/a/54575435
tagged with: ebcli
score: 0

http://stackoverflow.com/comment/91833774
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52337636
has text: if w was a data that is fed to network, what should I do? I want to send w and encoded output as a 28X28X2 filter to decoded part. is it possible? does concatenate do this for me?
score: 0

http://stackoverflow.com/comment/91730199
type: QuestionComment
type: Comment
has text: Thanks for clarifying the missing pieces. Typically the user would run the program directly from the command prompt, and the existing script was written in a batch script hybrid with javascript. I can write an additional batch script to wrap the command execution or python script.
score: 0
comment on: http://stackoverflow.com/q/52392242

http://stackoverflow.com/comment/91659088
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52300637
score: 0
has text: @jpmc26 `connection` need not strictly be a singleton object. Typically it's a method to get a connection object, it can do whatever it likes behind the scenes; I'm not sure what you call that pattern. A good ORM reduces complexity by hiding SQL compatibility issues, managing schema migrations, hiding table and column names, managing relationships, allowing queries to be built upon (ie. adding an order by or limit) etc... It works out far, far better than manual SQL. ORM quality varies. I like Sequel. Or use a SQL builder like Knex.js.

http://stackoverflow.com/q/52304492
upvote count: 2
has title: Error: Could not find or load main class net.minecraft.launchwrapper.Launch when launching Minecraft 1.12.2 with Forge
has comment: http://stackoverflow.com/comment/91591636
answer count: 1
accepted answer: http://stackoverflow.com/a/52452320
tagged with: java
has comment: http://stackoverflow.com/comment/91574605
has comment: http://stackoverflow.com/comment/91586852
type: AnsweredQuestion
score: 2
tagged with: minecraft
downvote count: 0
tagged with: ubuntu
favorite count: 0
has comment: http://stackoverflow.com/comment/91587402
type: Question
has answer: http://stackoverflow.com/a/52452320
tagged with: windows
has comment: http://stackoverflow.com/comment/91587353
has body: I've written a launcher for Minecraft 1.12.2 in Python, which just prepares a command and runs it using subprocess. This is the command formed on Linux Ubuntu: #!/usr/bin/env bash java -Xmx4G -XX:+UnlockExperimentalVMOptions -XX:+UseG1GC -XX:G1NewSizePercent=20 -XX:G1ReservePercent=20 -XX:MaxGCPauseMillis=50 -XX:G1HeapRegionSize=32M -Djava.library.path=/tmp/tmp2dl6pidh -cp /home/kuba/Desktop/launch/package/libraries/org/apache/maven/maven-artifact/3.5.3/maven-artifact-3.5.3.jar:/home/kuba/Desktop/launch/package/libraries/org/apache/httpcomponents/httpcore/4.3.2/httpcore-4.3.2.jar:/home/kuba/Desktop/launch/package/libraries/org/apache/httpcomponents/httpclient/4.3.3/httpclient-4.3.3.jar:/home/kuba/Desktop/launch/package/libraries/org/apache/logging/log4j/log4j-core/2.8.1/log4j-core-2.8.1.jar:/home/kuba/Desktop/launch/package/libraries/org/apache/logging/log4j/log4j-api/2.8.1/log4j-api-2.8.1.jar:/home/kuba/Desktop/launch/package/libraries/org/apache/commons/commons-compress/1.8.1/commons-compress-1.8.1.jar:/home/kuba/Desktop/launch/package/libraries/org/apache/commons/commons-lang3/3.5/commons-lang3-3.5.jar:/home/kuba/Desktop/launch/package/libraries/org/lwjgl/lwjgl/lwjgl_util/2.9.4-nightly-20150209/lwjgl_util-2.9.4-nightly-20150209.jar:/home/kuba/Desktop/launch/package/libraries/org/lwjgl/lwjgl/lwjgl-platform/2.9.4-nightly-20150209/lwjgl-platform-2.9.4-nightly-20150209-natives-linux.jar:/home/kuba/Desktop/launch/package/libraries/org/lwjgl/lwjgl/lwjgl/2.9.4-nightly-20150209/lwjgl-2.9.4-nightly-20150209.jar:/home/kuba/Desktop/launch/package/libraries/org/scala-lang/scala-xml_2.11/1.0.2/scala-xml_2.11-1.0.2.jar:/home/kuba/Desktop/launch/package/libraries/org/scala-lang/scala-compiler/2.11.1/scala-compiler-2.11.1.jar:/home/kuba/Desktop/launch/package/libraries/org/scala-lang/scala-reflect/2.11.1/scala-reflect-2.11.1.jar:/home/kuba/Desktop/launch/package/libraries/org/scala-lang/scala-swing_2.11/1.0.1/scala-swing_2.11-1.0.1.jar:/home/kuba/Desktop/launch/package/libraries…
tagged with: python
has comment: http://stackoverflow.com/comment/91591471

python-3.x
tags question: http://stackoverflow.com/q/52392644
tags question: http://stackoverflow.com/q/52278177
tags question: http://stackoverflow.com/q/52301568
tags question: http://stackoverflow.com/q/52383294
tags question: http://stackoverflow.com/q/52273070
tags question: http://stackoverflow.com/q/52301486
tags question: http://stackoverflow.com/q/52277625
tags question: http://stackoverflow.com/q/52359411
tags question: http://stackoverflow.com/q/52424811
tags question: http://stackoverflow.com/q/52351333
tags question: http://stackoverflow.com/q/52350581
tags question: http://stackoverflow.com/q/52403943
tags question: http://stackoverflow.com/q/52392102
tags question: http://stackoverflow.com/q/52358600
tags question: http://stackoverflow.com/q/52354599
tags question: http://stackoverflow.com/q/52387376
tags question: http://stackoverflow.com/q/52378294
tags question: http://stackoverflow.com/q/52337901
tags question: http://stackoverflow.com/q/52406293
tags question: http://stackoverflow.com/q/52372305
tags question: http://stackoverflow.com/q/52300046
tags question: http://stackoverflow.com/q/52411268
tags question: http://stackoverflow.com/q/52317507
tags question: http://stackoverflow.com/q/52406211
tags question: http://stackoverflow.com/q/52317459
tags question: http://stackoverflow.com/q/52409726
tags question: http://stackoverflow.com/q/52419117
tags question: http://stackoverflow.com/q/52350801
tags question: http://stackoverflow.com/q/52306563
tags question: http://stackoverflow.com/q/52352302
tags question: http://stackoverflow.com/q/52354011
tags question: http://stackoverflow.com/q/52376476
tags question: http://stackoverflow.com/q/52310283
tags question: http://stackoverflow.com/q/52420291
tags question: http://stackoverflow.com/q/52378288
tags question: http://stackoverflow.com/q/52295134
tags question: http://stackoverflow.com/q/52357918
tags question: http://stackoverflow.com/q/52413906
tags question: http://stackoverflow.com/q/52418170
tags question: http://stackoverflow.com/q/52298365
tags question: http://stackoverflow.com/q/52356646
tags question: http://stackoverflow.com/q/52276220
tags question: http://stackoverflow.com/q/52370298
tags question: http://stackoverflow.com/q/52297958
tags question: http://stackoverflow.com/q/52393904
tags question: http://stackoverflow.com/q/52346620
tags question: http://stackoverflow.com/q/52304296
tags question: http://stackoverflow.com/q/52291998
tags question: http://stackoverflow.com/q/52357782
tags question: http://stackoverflow.com/q/52398189
tags question: http://stackoverflow.com/q/52373180
tags question: http://stackoverflow.com/q/52284271
tags question: http://stackoverflow.com/q/52371503
tags question: http://stackoverflow.com/q/52309772
tags question: http://stackoverflow.com/q/52353860
tags question: http://stackoverflow.com/q/52406323
tags question: http://stackoverflow.com/q/52293445
tags question: http://stackoverflow.com/q/52350309
tags question: http://stackoverflow.com/q/52329835
tags question: http://stackoverflow.com/q/52324220
tags question: http://stackoverflow.com/q/52429173
tags question: http://stackoverflow.com/q/52373167
tags question: http://stackoverflow.com/q/52380080
tags question: http://stackoverflow.com/q/52348199
tags question: http://stackoverflow.com/q/52295689
tags question: http://stackoverflow.com/q/52412289
tags question: http://stackoverflow.com/q/52350074
tags question: http://stackoverflow.com/q/52426355
tags question: http://stackoverflow.com/q/52383595
tags question: http://stackoverflow.com/q/52384307
tags question: http://stackoverflow.com/q/52279863
tags question: http://stackoverflow.com/q/52319008
tags question: http://stackoverflow.com/q/52382780
tags question: http://stackoverflow.com/q/52335731
tags question: http://stackoverflow.com/q/52345435
tags question: http://stackoverflow.com/q/52351608
tags question: http://stackoverflow.com/q/52331576
tags question: http://stackoverflow.com/q/52414070
tags question: http://stackoverflow.com/q/52424527
tags question: http://stackoverflow.com/q/52421388

http://stackoverflow.com/comment/91668007
type: AnswerComment
comment on: http://stackoverflow.com/a/52343546
type: Comment
has text: That sounds like a separate question. From the looks of things, you’re trying to unpack the output of split into two values but split only retuned one value. Print lettura.split and you’ll probably see the problem
score: 0

http://stackoverflow.com/a/52333855
has body: You appear to be trying to get a list of URLs from a first URL and then wanting to get some information from each of these URLs. To do this, a request for each URL needs to be made and a separate BeautifulSoup parse is needed for each. Once you have the sub page, information can then be extracted, for example the name of the product and its price. Finally you could either print this information or write it to a file. The easiest way is to write it as a CSV file. In this example I show how you could write the URL and name and the price as a single row. The CSV library automatically formats correctly: from urllib3.exceptions import InsecureRequestWarning from bs4 import BeautifulSoup import requests import csv requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning) my_url = 'https://franke-market.com.ua/moyki.html?on_page=100' headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'} req = requests.get(my_url, headers=headers, verify=False) soup = BeautifulSoup(req.content, "html.parser") with open("products.csv", "w", newline="") as f_output: csv_output = csv.writer(f_output) csv_output.writerow(['URL', 'Title', 'Price']) # Find the URLs for all the products for div in soup.find_all('div', attrs={'class': 'product'})[:5]: url = div.a['href'] print(url) # For each URL, get the sub page and get the name and price req_sub = requests.get(url, headers=headers, verify=False) soup_sub = BeautifulSoup(req_sub.content, "html.parser") title = soup_sub.find('h1', class_='title').text price_info = soup_sub.find('div', class_='price_info').span.text # Write the url, name and price as a CSV file csv_output.writerow([url, title, price_info]) Giving you and output.csv file starting: URL,Title,Price https://franke-market.com.ua/franke_rol_610-38_101_0267_707_.html,Franke ROL 610-38 (101.0267.707),91795 https://franke-market.com.ua/franke-pmn-611i-101.0255.790.html,Franke Pami…
downvote count: 0
score: 1
type: Answer
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52275204
answers question: http://stackoverflow.com/q/52275204

http://stackoverflow.com/a/67974372
downvote count: 0
score: 7
upvote count: 7
answers question: http://stackoverflow.com/q/52335967
type: Answer
has body: I think this tool can help you do what you need. It can help you edit the contents of .npy files like spreadsheets. It also has options to visualize .npy files as 2D grayscale images and 3D point clouds: https://github.com/csmailis/NPYViewer

http://stackoverflow.com/a/62064067
has comment: http://stackoverflow.com/comment/109769365
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52397832
has body: bill = float(input()) paid = float(input()) Available = {100.0:0,50.0:0,20.0:0,10.0:0,5.0:0,1.0:0,0.25:0,0.10:0,0.01:0} due = paid-bill for change in sorted(Available,reverse = True): amt= max(0,due//change) due-=amt*change Available[change] = int(amt) print(Available)

http://stackoverflow.com/q/52365108
has comment: http://stackoverflow.com/comment/91674859
type: Question
has comment: http://stackoverflow.com/comment/91675070
answer count: 2
has comment: http://stackoverflow.com/comment/91679446
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/91674673
has comment: http://stackoverflow.com/comment/91674946
accepted answer: http://stackoverflow.com/a/52365658
has comment: http://stackoverflow.com/comment/91674852
favorite count: 0
tagged with: python-3.x
has body: How do I get this code into my gui? I tried adding it into a button but failed! I want all of def say_hi(self) inside the gui rather then printing it to the shell, also the printout works best in the console rather then python shell! import sys import time from random import randint import tkinter as tk class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.create_widgets() # self.roll is the button def create_widgets(self): self.roll = tk.Button(self) self.roll["text"] = "rolldice" self.roll["command"] = self.say_hi self.roll.pack(side="left") #self.quit is the kill button self.quit = tk.Button(self, text="QUIT", fg="red", command=root.destroy) self.quit.pack(side="right") self.label = tk.Label(self, text='ROLL THE DICE !') self.label.pack() # this is my loading result. def say_hi(self): d = 0 for x in range(0,7): for x in range (0,5): b = "Loading" + "." * x a = " " print (b, end="\r") time.sleep(0.1) print (a, end="\r") time.sleep(0) print("finished rolling!") time.sleep(2) for x in range(0,7): for x in range (0,5): b = "printing" + "." * x a = " " print (b, end="\r") time.sleep(0.1) print (a, end="\r") time.sleep(0) print ("printed") print ("here it is thankyou for using us!") print (" ") value = randint(1, 6) self.label['text'] = value self.label.pack() root = tk.Tk() app = Application(master=root) app.mainloop()
tagged with: python
has title: Python 3 tkinker - How do i get this code output into the gui?
has comment: http://stackoverflow.com/comment/91674970
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52366125
tagged with: tkinter
has answer: http://stackoverflow.com/a/52365658
has comment: http://stackoverflow.com/comment/91684246
has answer: http://stackoverflow.com/a/52366125
downvote count: 2

http://stackoverflow.com/a/52318994
type: Answer
has body: This seems to be the correct syntax for AJAX according to https://codehandbook.org/python-flask-jquery-ajax-post/ $.ajax({ url: '/signup_user', data: $('#signupForm').serialize(), type: 'POST', success: function(response) { console.log(response); }, error: function(error) { console.log(error); } }); You could also try getJSON for shorthand: $.getJSON('/signup_user', $('#signupForm').serialize(), function(res) { console.log(res) }); UPDATED: In my own use, I have found that methods=['POST'] isn't necessary for ajax calls in flask's @app.route. I could be wrong.
score: 0
answers question: http://stackoverflow.com/q/52318106

http://stackoverflow.com/comment/91797311
comment on: http://stackoverflow.com/q/52426691
score: 0
type: Comment
type: QuestionComment
has text: It looks like your function `hit` shares the same name as some other kind of object (`hit.counter`). Make sure to have unique names for different objects.

http://stackoverflow.com/comment/91613980
has text: ok cool, thanks for linking that and thanks for the help
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52283661
type: Comment

http://stackoverflow.com/q/52346412
has comment: http://stackoverflow.com/comment/91640335
answer count: 3
has comment: http://stackoverflow.com/comment/91644512
downvote count: 0
favorite count: 0
has title: Python - Date conversion
has answer: http://stackoverflow.com/a/52346656
has body: I'm using Python and I want to convert a date from the following formats: '30th Sep 2018' or 'Mon 30th Sep 2018' to the format: '2018-09-30 00:00:00' I already tried to use the strptime() and strftime() functions but I can't make this works with them. Anyone know how to accomplish this in Python?
tagged with: datetime
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91638619
has comment: http://stackoverflow.com/comment/91654257
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52347063
score: 1
accepted answer: http://stackoverflow.com/a/52347063
type: Question
possible better answer: http://stackoverflow.com/a/52346963
has answer: http://stackoverflow.com/a/52346963

http://stackoverflow.com/a/52426533
has comment: http://stackoverflow.com/comment/91798906
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91797493
has body: You can use the __dict__ attribute of the self object: class Name: def __init__(self,name,favfood,favcolour,favsport): self.name = name self.favfood = favfood self.favcolour = favcolour self.favsport = favsport for key, value in self.__dict__.items(): if value is not None: print('%s: %s' % (key, value)) henry = Name("Henry","Sushi","Blue",None) This outputs: name: Henry favfood: Sushi favcolour: Blue
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52426347

http://stackoverflow.com/comment/91662172
score: 0
type: Comment
type: QuestionComment
has text: There were some logical/implementational errors in your code. Check my answer below
comment on: http://stackoverflow.com/q/52358844

http://stackoverflow.com/q/52324937
type: UnansweredQuestion
has title: frames_to_video Python programme
tagged with: python
answer count: 0
has body: I am trying to write a programme to convert a set of frames to images. However, I am not getting the same smooth video but rather a continuous jump between frames. What I did was initially convert the video to frames and then convert back the frames to videos. My video is about 1 min long and has about 1500 pics (30FPS) so I can't think of anything wrong with my video-to-frames programme. Anyways I have attached my code below. The reason I am doing this is to apply FACE API to each frame and to blur each face(for the confidential purpose). Is there a better way? Or is there something wrong with my programme? import cv2 import argparse import os # Construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-ext", "--extension", required=False, default='png', help="extension name. default is 'png'.") ap.add_argument("-o", "--output", required=False, default='output.mp4', help="output video file") args = vars(ap.parse_args()) # Arguments dir_path = '******************' ext = args['extension'] output = args['output'] images = [] for f in os.listdir(dir_path): if f.endswith(ext): images.append(f) # Determine the width and height from the first image image_path = os.path.join(dir_path, images[0]) frame = cv2.imread(image_path) cv2.imshow('video',frame) height, width, channels = frame.shape # Define the codec and create VideoWriter object fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Be sure to use lower case out = cv2.VideoWriter(output, fourcc, 20.0, (width, height)) for image in images: image_path = os.path.join(dir_path, image) frame = cv2.imread(image_path) out.write(frame) # Write out frame to video cv2.imshow('video',frame) if (cv2.waitKey(1) &amp; 0xFF) == ord('q'): # Hit `q` to exit break # Release everything if job is finished out.release() cv2.destroyAllWindows() print("The output video is {}".format(output))
tagged with: video-processing
tagged with: image-processing
upvote count: 1
downvote count: 1
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/91686795
score: 0
has comment: http://stackoverflow.com/comment/91611457
has comment: http://stackoverflow.com/comment/91608873
favorite count: 0

http://stackoverflow.com/a/52397797
type: Answer
has comment: http://stackoverflow.com/comment/91740748
has body: Because type is a class, you need its __new__ method: &gt;&gt;&gt; type.__new__(type, 1) &lt;type 'int'&gt; Usually, cls(*args, **kwargs) is equivalent to cls.__new__(cls, *args, **kwargs) followed by calling .__init__(*args, **kwargs) on the returned object. Here's one possible implementation of this behavior of type(): class MyType(object): def __new__(cls, obj): return obj.__class__ def __init__(self, hahaha): pass See blhsing's answer for question 2.
answers question: http://stackoverflow.com/q/52397650
upvote count: 4
has comment: http://stackoverflow.com/comment/91740438
downvote count: 0
score: 4

corpus
tags question: http://stackoverflow.com/q/52391572
tag name: corpus
type: Tag

http://stackoverflow.com/a/62636347
has body: Here's my solution to the same problem using set() to remove the duplicates and sort() in reverse to find out the desired element. Hope it's the simplest way one can approach this problem. if __name__ == '__main__': n = int(input()) arr = map(int, input().split()) x = set(arr) x = list(x) x.sort(reverse=True) print(x[1])
upvote count: 2
downvote count: 1
type: Answer
score: 1
answers question: http://stackoverflow.com/q/52325949

http://stackoverflow.com/q/52296803
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have a 3d image and try to predict their slice outputs by using neural networks. The problem is that, after prediction, I would like to find a way to pack them back. I have an idea that uses grid method, however, I am not sure it is the best way to do it. fig=plt.figure(figsize=(20, 20)) columns = rangex_of_crop rows = rangey_of_crop for i, x in enumerate(cropped_images): img = x fig.add_subplot(rows, columns, i+1) plt.axis('off') plt.imshow(np.squeeze(x)) fig = plt.figure(figsize=(15, 15), frameon=False) plt.show() The output must be np.array of whole image and we have to assume that slices can be different sizes (not one by one, all together i.e. the all splitted images can be 32x32 or 64x64):
has comment: http://stackoverflow.com/comment/91541806
answer count: 0
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91541933
upvote count: 1
tagged with: grid
linked to: http://stackoverflow.com/q/16873441
type: Question
tagged with: numpy
has title: How do I pack multiple images to one image or numpy array in python?
has comment: http://stackoverflow.com/comment/91542010
has comment: http://stackoverflow.com/comment/91553642
has comment: http://stackoverflow.com/comment/91568455
has comment: http://stackoverflow.com/comment/91542062
tagged with: concatenation
downvote count: 0

http://stackoverflow.com/a/52392221
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/91729868
answers question: http://stackoverflow.com/q/52391099
type: AcceptedAnswer
downvote count: 0
has body: If you want to perform a conditional substitution, use a function as the replace parameter. This function accepts a match parameter (what has been caught) and its result is the text to be substituted in place of the match. To refer in the replace function to the capturing group named test, use group('test'). Example program: import re def replTxt(match): return 'yes' if match.group('test') else 'no' a = re.compile('(?P&lt;test&gt;.+)') result = a.sub(replTxt, 'word') print(result) But I have such a remark: There is no chance that no will ever be substituted by this program. If the regex doesn't match, replTxt function will just not be called. To have the possibility that test group matched nothing, but something has been matched: this capturing group should be conditional (? after it), in order not to match an empty text, the regex should contain something more to match, e.g. (?P&lt;test&gt;[a-z]+)?\d.
accepted answer of: http://stackoverflow.com/q/52391099
type: Answer

recurrent-neural-network
tags question: http://stackoverflow.com/q/52303130
tags question: http://stackoverflow.com/q/52324322
type: Tag
tags question: http://stackoverflow.com/q/52376142
tags question: http://stackoverflow.com/q/52418248
tags question: http://stackoverflow.com/q/52317804
tags question: http://stackoverflow.com/q/52363416
tags question: http://stackoverflow.com/q/52411530
tag name: recurrent-neural-network

http://stackoverflow.com/q/52313383
has comment: http://stackoverflow.com/comment/91618620
downvote count: 0
has body: group is supposed to yield the last match of a group of a regular expression, while the Python regex module also provides captures to yield all matches. When using group for a group with a group reference, the last match only of the named group is returned by group, ignoring the matches of the references returned by captures: &gt;&gt;&gt; import regex &gt;&gt;&gt; m = regex.fullmatch('(?P&lt;x&gt;.)*(?&amp;x)', 'abc') &gt;&gt;&gt; m.captures('x') ['a', 'b', 'c'] # all matches, both of x and &amp;x &gt;&gt;&gt; m.group('x') 'b' # last match only of matches of x, ignoring &amp;x Without a reference, just copying the named group, it works as expected: &gt;&gt;&gt; m = regex.fullmatch('(?P&lt;x&gt;.)(?P&lt;x&gt;.)(?P&lt;x&gt;.)', 'abc') &gt;&gt;&gt; m.captures('x') ['a', 'b', 'c'] &gt;&gt;&gt; m.group('x') 'c' # last match of all three matches Does anyone know if this is intended behavior or might be a bug? And if intended, why it is like this? Does the match object provide any information about to which part of the regex a match belongs, to the named group or the reference? I am using regex 2018.8.29, Python 3.6.5 and opensuse 15.0.
has comment: http://stackoverflow.com/comment/91616992
tagged with: regex
has title: What exactly is the last match of a regular expression with group references (in Python regex)?
tagged with: reference
favorite count: 0
has comment: http://stackoverflow.com/comment/91574366
type: UnansweredQuestion
upvote count: 1
tagged with: python
answer count: 0
score: 1
type: Question

sentry
tags question: http://stackoverflow.com/q/52288560
type: Tag
tag name: sentry

http://stackoverflow.com/a/52340190
upvote count: 3
has body: Create an intermediate dataframe from the raw data: first_df = pd.DataFrame(list1) Use the second column as the data for the final dataframe by reshaping it into a three-column 2D array. Use the first column's unique values as the index: pd.DataFrame(first_df[1].values.reshape(3, -1), index=first_df[0].unique()) # 0 1 2 #1 [dog, slow] [5, 4] [mice, cat] #2 [cat, fast] [6, 6] [cat, mice] #3 [tree, hurry] [7, 5] [mice, cat]
type: Answer
has comment: http://stackoverflow.com/comment/91631765
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/52340045
answers question: http://stackoverflow.com/q/52340045
type: AcceptedAnswer

http://stackoverflow.com/comment/91597318
has text: That is the error I just got, pasting in my code to your comment now
comment on: http://stackoverflow.com/a/52324987
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91597004
has text: Not all hereos wear capes, thanks man, can't believe I missed that.
comment on: http://stackoverflow.com/a/52325017
type: AnswerComment
type: Comment
score: 1

oop
tags question: http://stackoverflow.com/q/52423958
tags question: http://stackoverflow.com/q/52289225
tags question: http://stackoverflow.com/q/52357452
tags question: http://stackoverflow.com/q/52324480
tags question: http://stackoverflow.com/q/52324967
tags question: http://stackoverflow.com/q/52335799
tag name: oop
tags question: http://stackoverflow.com/q/52412777
tags question: http://stackoverflow.com/q/52341182
tags question: http://stackoverflow.com/q/52369981
tags question: http://stackoverflow.com/q/52305454
tags question: http://stackoverflow.com/q/52345091
tags question: http://stackoverflow.com/q/52428416
tags question: http://stackoverflow.com/q/52414135
tags question: http://stackoverflow.com/q/52387730
tags question: http://stackoverflow.com/q/52291135
tags question: http://stackoverflow.com/q/52402793
type: Tag
tags question: http://stackoverflow.com/q/52285155

http://stackoverflow.com/q/52364222
has body: let's say I have the following numpy matrix (simplified): matrix = np.array([[1, 1], [2, 2], [5, 5], [6, 6]] ) And now I want to get the vector from the matrix closest to a "search" vector: search_vec = np.array([3, 3]) What I have done is the following: min_dist = None result_vec = None for ref_vec in matrix: distance = np.linalg.norm(search_vec-ref_vec) distance = abs(distance) print(ref_vec, distance) if min_dist == None or min_dist &gt; distance: min_dist = distance result_vec = ref_vec The result works, but is there a native numpy solution to do it more efficient? My problem is, that the bigger the matrix becomes, the slower the entire process will be. Are there other solutions that handle these problems in a more elegant and efficient way?
accepted answer: http://stackoverflow.com/a/52364284
linked to: http://stackoverflow.com/q/52360834
type: AnsweredQuestion
upvote count: 5
linked to: http://stackoverflow.com/q/52366421
type: Question
tagged with: numpy
has title: Find closest/similar value(vector) inside a matrix
score: 5
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52364284
favorite count: 0
has comment: http://stackoverflow.com/comment/91713298
has comment: http://stackoverflow.com/comment/91675341
tagged with: python
has comment: http://stackoverflow.com/comment/91676782

http://stackoverflow.com/comment/91657972
type: Comment
type: QuestionComment
has text: I tried several ways to download the image, the screenshot is for when i open img in new tab and run the code.
comment on: http://stackoverflow.com/q/52354997
score: 0

http://stackoverflow.com/comment/91748980
comment on: http://stackoverflow.com/q/52402391
type: QuestionComment
has text: I've upvoted your comment because of this, and because recommending interesting libraries is useful to other people, but yes, it might be violating the prime directive a little too much for newbie questions.
score: 0
type: Comment

http://stackoverflow.com/q/52344228
has answer: http://stackoverflow.com/a/52344325
has title: can't write to database psql - INSERT INTO syntax
has comment: http://stackoverflow.com/comment/91634494
has body: still new to this but i have a PSQL table that's connected to my python(flask) app with this columns description id integer Auto Increment [nextval('users_id_seq')] name character varying pw character varying email character varying and this function that excute after the user visits @app.route("/registed" ,methods=["POST"]) def registed(): Name1 = "test" Email1 = "test1" pw1 = "test2" pwh = "test3" db.execute("INSERT INTO users (name,pw,email) VALUES (Name1,pw1,Email1)") db.commit() return render_template("registed.html",name=Name1,email=Email1,pw=pw1,pwh=pwh) it keep coming bk with this error LINE 1: INSERT INTO users (name,pw,email) VALUES (Name1,pw1,Email1) ^ HINT: Perhaps you meant to reference the column "users.name". [SQL: 'INSERT INTO users (name,pw,email) VALUES (Name1,pw1,Email1)'] (Background on this error at: http://*****/*/***) i used heroku for this test project
has answer: http://stackoverflow.com/a/52344823
upvote count: 1
accepted answer: http://stackoverflow.com/a/52344823
answer count: 4
has answer: http://stackoverflow.com/a/52367273
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/52344961
score: 1
tagged with: flask-sqlalchemy
favorite count: 0
has answer: http://stackoverflow.com/a/52344961
tagged with: python-3.x
tagged with: postgresql
type: Question
tagged with: python

http://stackoverflow.com/q/52388154
tagged with: windows
tagged with: python
score: 11
upvote count: 11
tagged with: visual-studio
has title: Visual Studio Code windows , Python Pandas . No module named pandas
has answer: http://stackoverflow.com/a/58326329
type: Question
has answer: http://stackoverflow.com/a/67787732
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52388424
tagged with: python-3.7
tagged with: pandas
has answer: http://stackoverflow.com/a/60495307
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/60495307
has answer: http://stackoverflow.com/a/54485676
has body: I set the variables for Env. All necessary modules for Pandas operation are installed by pip. I wanted to run the code to display it in "Output". I run with: Alt + CTRL + N(or right click -> Run code). In output returns the message: But when I run in the terminal (right click -> Run Python File in Terminal), the code works correctly. I would like the code to run correctly in output(right click -> Run code), not in the terminal. Any suggestions?
answer count: 5
accepted answer: http://stackoverflow.com/a/52388424

http://stackoverflow.com/comment/91508324
has text: You might try to negatize the image and detect white spots....
comment on: http://stackoverflow.com/q/52279916
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52370265
has comment: http://stackoverflow.com/comment/93298705
accepted answer of: http://stackoverflow.com/q/52370136
upvote count: 1
answers question: http://stackoverflow.com/q/52370136
score: 1
has comment: http://stackoverflow.com/comment/91685605
type: AcceptedAnswer
downvote count: 0
has body: Just an issue in your namespace, you overwrite the imported LSTM layer. Change LSTM to lstm in your model name. from keras import Sequential, Model from keras.layers import Embedding,LSTM, GlobalMaxPool1D embed_size=8 max_len = 1000 max_words = 10 lstm=Sequential() lstm.add(Embedding(max_words,embed_size,input_length=max_len)) lstm.add(LSTM(30, return_sequences=True,name='lstm_layer')) lstm.add(GlobalMaxPool1D()) Works fine Detailed explanation for newcomers: The import statement sets a local reference called LSTM that is a class implementing a Keras layer. Then, it is overwritten in the statement LSTM=Sequential(). Now the name LSTM is an instance of a Keras sequential model. Finally, in the statement LSTM.add(LSTM(...)) the inner operation LSTM(..) is a call to the model, implemented by __call__ method of the Sequential class (this feature is native in python). So the throwed error says sequential_6 was called with an input that isn't a symbolic tensor... , which means that an instance of the Sequential class (which was automatically name sequential_6 by the framework) is called, with an input that is incompatible with the implementation. This assertion is in the __call__ implementation of the Sequential class.
type: Answer

http://stackoverflow.com/q/52374770
has answer: http://stackoverflow.com/a/52374822
tagged with: python
type: AnsweredQuestion
upvote count: 2
possible better answer: http://stackoverflow.com/a/52374822
score: 1
has body: Preface: the question is to understand python internals, so pls don't answer with 'upgrade python' or 'import six' Let take for example, 'print' To replace the 'print' builtin, I can write my python function. python 2.6 : at runtime, I get syntax error solution from __future__ import print_function Now I can redefine print. Why ? I think because now my print declaration is the same as the new print function. python 2.4 : at runtime, I get syntax error There isn't from __future__ import print_function So, for print (or any other builtin): is it possible to monkey patch with a new function, with a different declaration - args and kwargs ? In other words. from __future__ import print_function substitutes the keyword with a function. I want to understand HOW, in general. Please don't be focused exclusively on print, it is an handy example.
downvote count: 1
accepted answer: http://stackoverflow.com/a/52375161
type: Question
has title: python: builtin function redefinition, with different arguments
has comment: http://stackoverflow.com/comment/91694429
tagged with: monkeypatching
linked to: http://stackoverflow.com/q/7075082
answer count: 2
tagged with: built-in
duplicate of: http://stackoverflow.com/q/7075082
has comment: http://stackoverflow.com/comment/91694662
has comment: http://stackoverflow.com/comment/91694421
favorite count: 0
has answer: http://stackoverflow.com/a/52375161
has comment: http://stackoverflow.com/comment/91694763
has comment: http://stackoverflow.com/comment/91694882

http://stackoverflow.com/q/52284968
upvote count: 1
has comment: http://stackoverflow.com/comment/91518350
has title: How to return a random character from a regex pattern? python 3
type: Question
has answer: http://stackoverflow.com/a/52285252
possible better answer: http://stackoverflow.com/a/52285252
accepted answer: http://stackoverflow.com/a/52285043
tagged with: char
answer count: 3
has answer: http://stackoverflow.com/a/52285737
downvote count: 0
tagged with: string
favorite count: 0
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/91519967
has body: I would like to know if its somehow possible to return a single random character from a regex pattern, written in short term. So here is my case.. I have created some Regex patterns contained in an Enum: import random from _operator import invert from enum import Enum import re class RegexExpression(Enum): LOWERCASE = re.compile('a-z') UPPERCASE = re.compile('A-Z') DIGIT = re.compile('\d') SYMBOLS = re.compile('\W') I want for these to be returned as a string containing all the characters that the regex expresses, based on this method below: def create_password(symbol_count, digit_count, lowercase_count, uppercase_count): pwd = "" for i in range(1, symbol_count): pwd.join(random.choice(invert(RegexExpression.SYMBOLS.value))) for i in range(1, digit_count): pwd.join(random.choice(invert(RegexExpression.DIGIT.value))) for i in range(1, lowercase_count): pwd.join(random.choice(invert(RegexExpression.LOWERCASE.value))) for i in range(1, uppercase_count): pwd.join(random.choice(invert(RegexExpression.UPPERCASE.value))) return pwd I have tried several thing, but the only option I find possible is using an Enum containing long regex patterns, or strings like in the below example: LOWERCASE = "abcdefghijklmnopqrstuvwxyz" ... And so on with the other variables in use. Any suggestions or solutions to this scenario? --EDIT-- Mad Physicist brought the solution for my issue - Thanks a lot! Here is the working code: def generate_password(length): tmp_length = length a = random.randint(1, length - 3) tmp_length -= a b = random.randint(1, length - a - 2) tmp_length -= b c = random.randint(1, length - a - b - 1) tmp_length -= c d = tmp_length pwd = "" for i in range(0, a): pwd += random.choice(string.ascii_lowercase) for i in range(0, b): pwd += random.choice(string.ascii_uppercase) for i in range(0, c): pwd += random.choice(string.digits) for i in range(0, d): pwd += random.choice(string.punctuation) pwd = ''.join(random.sample(pwd, len(pwd))) return pwd
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52285043
score: 1

http://stackoverflow.com/comment/91793805
comment on: http://stackoverflow.com/q/52425315
score: 0
type: Comment
has text: @DeepSpace Yes. In such an event, the unicode sequence will not be converted. I was thinking that perhaps there is a tool/library that can detect unicode sequences, and to only convert those rather than converting the whole line. But I haven't found such a solution yet - and this would be very slow indeed.
type: QuestionComment

http://stackoverflow.com/comment/91673076
score: 1
has text: And even if you had to use a raw query, you should **never** use string interpolation like that.
comment on: http://stackoverflow.com/q/52364483
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52324600
has answer: http://stackoverflow.com/a/52325140
favorite count: 0
has comment: http://stackoverflow.com/comment/91596481
has answer: http://stackoverflow.com/a/52326054
has title: strange terminal output when using colour/style formatting
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91596437
downvote count: 0
score: 1
tagged with: formatting
has comment: http://stackoverflow.com/comment/91598106
type: Question
answer count: 2
has body: I have the code: import sys for i in range(0, 20): for j in range(0, 20): sys.stdout.write('\x1b[1;32;40m' + ' ' + '\x1b[0m') sys.stdout.write("\n") which outputs 400 white squares in a 20x20 grid but also after about 180 squares outputs [1;32;40m in between some of the squares. It doesn't always output in the same place. Why is this happening, and how can it be fixed?
tagged with: terminal
upvote count: 1
has comment: http://stackoverflow.com/comment/91597077
tagged with: python

http://stackoverflow.com/a/52409570
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52409426
has body: The second answer to the question you linked can easily be adapted: complexes = [1, 2+3j, 1-2j, 6+1j] [i[0] for i in sorted(enumerate(complexes), key=lambda x:x[1].imag)] # [2, 0, 3, 1]
score: 1
answers question: http://stackoverflow.com/q/52409426

http://stackoverflow.com/q/52393119
has answer: http://stackoverflow.com/a/52393231
answer count: 4
upvote count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/52393473
type: Question
has body: Suppose you have a big grid represented by a dictionary. At some coordinates there are "players" while the other coordinates are empty. The dictionary d = {(500,100): "player1", (480, 230): "player"} (these are the locations of the players in the grid). Now if you have a coordinate of lets say (500, 90), which of the two players are the closest? I understand that the Pythagorean theorem will have to be implemented in some way in order to solve this, but I don't understand how to implement it in a function. This is the farthest I've come: d = {(500,100): "player1", (480, 230): "player"} def nearest_player(grid, x-cor, y-cor): '''print out (500,100) as the answer''' Any ideas would be greatly appreciated.
score: 0
has answer: http://stackoverflow.com/a/52393380
has title: Find the nearest key in dictionary grid
favorite count: 0
has answer: http://stackoverflow.com/a/52393695
type: UnansweredQuestion
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/52387090
has body: I've been struggling to try and parse some server logs with Python and regex. I want to be able parse user agent strings in these lines and then eventually put them into a Pandas dataframe or a simple Excel spreadsheet. So the following extract: 14/Aug/2018:00:44:50 +0000] 330 95.144.101.0, 34.255.205.1 GET pixelg.adswizz.com /one.png 200 - AlexaMediaPlayer/2.0.201528.0 (Linux;Android 5.1.1) ExoPlayerLib/1.5.9 client=VillaPlus&amp;oid=2069&amp;cid=22599&amp;ad=54063&amp;cr=August2018&amp;target=25plus&amp;action=ae&amp;eventId=&amp;cb=8874209&amp;listenerId=f78d5ea146e92c4666efd2a389a8d2e8f6174bfc6777496e5e22735c426c&amp;zone=679 - pixelg.adswizz.com https 533 TLSv1.2 DHE-RSA-AES128-GCM-SHA256, 15/Aug/2018:23:03:17 +0000] 330 79.77.250.195, 34.245.112.20 GET pixelg.adswizz.com /one.png 200 - Smooth/38 (iPhone; CPU iPhone OS 11_4_1 like Mac OS X) devicemap=mobile_tablet - pixelg.adswizz.com http 357 - - 0.000, 15/Aug/2018:23:17:01 +0000] 330 77.100.181.37 GET pixelg.adswizz.com /one.png 200 https://www.bonne-terre-data-layer.com/tag-manager.html?consumer=m.skybet.com Mozilla/5.0 (iPhone; CPU iPhone OS 11_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15G77 SkyBet/6.8b474 (Sky Bet Mobile App) client=SkyBet&amp;event_id=Summer17&amp;action=clientsitevisit&amp;event=/my-bets - pixelg.adswizz.com https 605 TLSv1.2 DHE-RSA-AES128-GCM-SHA256 0.000, 14/Aug/2018:01:00:55 +0000] 330 86.178.205.6, 34.244.204.228 GET pixelg.adswizz.com /one.png 200 - Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36 client=MyHermes&amp;oid=&amp;cid=22731&amp;ad=54477&amp;cr=Hermes&amp;target=selfemploy&amp;action=ae&amp;eventId=&amp;cb=7699694&amp;listenerId=0610d2ed750ab9f692daff922e1b2c04&amp;zone=87 - pixelg.adswizz.com https 546 TLSv1.2 DHE-RSA-AES128-GCM-SHA256 Becomes in a list: AlexaMediaPlayer/2.0.201528.0 (Linux;Android 5.1.1) ExoPlayerLib/1.5.9, Smooth/38 (iPhone; CPU iPhone OS 11_4_1 like Mac OS X),…
upvote count: 0
tagged with: database
has answer: http://stackoverflow.com/a/52387227
tagged with: pandas
answer count: 1
score: -2
favorite count: 0
downvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/52387227
has comment: http://stackoverflow.com/comment/91718893
type: AnsweredQuestion
has title: Parsing server logs Python
type: Question

http://stackoverflow.com/comment/91548656
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52280393
has text: And as an anedocte, much to my surprise, it is actually quite slower in pypy
score: 0

http://stackoverflow.com/a/52441622
has body: Use Latin-1 encoding. If You are using UTF-8 encoding, it may not be correct every time. so, better to use Latin-1 encoding. For eg: data_send = ("\x00\x01\x01\x01\x01\x00\x03\x08\x00\x00\x00\x14\x04\x00\x00\x00\x44\xf2\xfc").encode('Latin-1')
type: Answer
answers question: http://stackoverflow.com/q/52373121
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/comment/103515465
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52324322
has text: Did you get a solution for this issue ?

http://stackoverflow.com/a/52417967
type: Answer
has comment: http://stackoverflow.com/comment/111984235
score: 21
has body: Using searchsorted With sorted B, we can use searchsorted - A[B[np.searchsorted(B,A)] != A] From the linked docs, searchsorted(a,v) find the indices into a sorted array a such that, if the corresponding elements in v were inserted before the indices, the order of a would be preserved. So, let's say idx = searchsorted(B,A) and we index into B with those : B[idx], we will get a mapped version of B corresponding to every element in A. Thus, comparing this mapped version against A would tell us for every element in A if there's a match in B or not. Finally, index into A to select the non-matching ones. Generic case (B is not sorted) : If B is not already sorted as is the pre-requisite, sort it and then use the proposed method. Alternatively, we can use sorter argument with searchsorted - sidx = B.argsort() out = A[B[sidx[np.searchsorted(B,A,sorter=sidx)]] != A] More generic case (A has values higher than ones in B) : sidx = B.argsort() idx = np.searchsorted(B,A,sorter=sidx) idx[idx==len(B)] = 0 out = A[B[sidx[idx]] != A] Using in1d/isin We can also use np.in1d, which is pretty straight-forward (the linked docs should help clarify) as it looks for any match in B for every element in A and then we can use boolean-indexing with an inverted mask to look for non-matching ones - A[~np.in1d(A,B)] Same with isin - A[~np.isin(A,B)] With invert flag - A[np.in1d(A,B,invert=True)] A[np.isin(A,B,invert=True)] This solves for a generic when B is not necessarily sorted.
has comment: http://stackoverflow.com/comment/91779097
upvote count: 21
has comment: http://stackoverflow.com/comment/91781636
accepted answer of: http://stackoverflow.com/q/52417929
downvote count: 0
answers question: http://stackoverflow.com/q/52417929
has comment: http://stackoverflow.com/comment/111943737
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91779016

http://stackoverflow.com/q/52302361
has title: PyInstaller unbuffered stdio
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/69794590
type: UnansweredQuestion
tagged with: pyinstaller
tagged with: python
has answer: http://stackoverflow.com/a/66226019
has body: Problem Docker image sizes should commonly be as small as possible. Using full-blown environments like a standard python image results often, with all dependencies installed, in heavily bloated images. Packaging python into stand-alone executables (e.g. using pyinstaller) is a perfect way of reducing image sizes and overall complexity. Environment: python3.6, pyinstaller==3.4 The problem arising is, that python uses per default buffered stdio. This can be mitigated by running python scripts with python -u .... But becomes inaccessible when using pyinstaller. According to the docs it should be possible to add run-time options, such as u, v and W ... to the executable generated. But unfortunately in reality it doesn't seem to work. Both, v and W, work normally, but u seems to be completely ignored. The following snippet shows the usage: ... exe = EXE(... [('u', None, 'OPTION')], name="myapp", ...) ... Is this flag still valid? Since the others work - has it been removed without notice or update of the docs? Are there alternatives to disable buffering of stdio (with pyinstaller or as well externally), without modifying the python code, like so? Why would that be needed? Buffered IO is to be avoided, when running docker swarm services. In order to make the executable properly log in real-time to the docker daemon, it's necessary to attach a shell. But the attaching of a tty shell to the swarm tasks makes working with the logs much, much more complicated if even impossible.
type: Question
score: 10
tagged with: stdio
upvote count: 10
linked to: http://stackoverflow.com/q/107705
tagged with: docker
answer count: 2

http://stackoverflow.com/a/52324915
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52324838
has body: Using a module named shutil, the function copy2 can be called with the path of the source file and the corresponding destination directory you want to write to. For example, import shutil shutil.copy2('/src/test.txt','/dst/test_copy.txt')
has comment: http://stackoverflow.com/comment/91596856
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91817878
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52327186
has text: No I dont actually mean that...I mean when the user will sign up he/she will provide some email to complete the signup process...I want to get that email which the user provided during signup in every page of my django project...@SazzadurRahman

printing
tags question: http://stackoverflow.com/q/52350011
tags question: http://stackoverflow.com/q/52359579
tags question: http://stackoverflow.com/q/52336831
tags question: http://stackoverflow.com/q/52345435
tag name: printing
tags question: http://stackoverflow.com/q/52322906
tags question: http://stackoverflow.com/q/52289640
type: Tag
tags question: http://stackoverflow.com/q/52282580
tags question: http://stackoverflow.com/q/52401157

http://stackoverflow.com/comment/91735895
comment on: http://stackoverflow.com/a/52381315
has text: Thank you for your time. This also works. Just out of curiosity, those for loops may be time consuming when DataFrame is huge correct?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91535387
type: QuestionComment
has text: nice task - what did you try to solve it?
comment on: http://stackoverflow.com/q/52293809
score: 2
type: Comment

http://stackoverflow.com/q/52416770
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/54307210
has title: Tensorflow Model detects only 1 class
tagged with: tensorflow
type: Question
has body: I want to recognize my fist and palm. So I follow the Tensorflow Object Dection API But I could see my model recognizing only one palm I adjusted the number of images in the palm and fist to be the same. I also modified the label file, generate_tfrecord, ssd_mobilenet_v1_pets. I want to train the model to detect 2 classes, but after training it recognize only 1 class

http://stackoverflow.com/comment/91576459
type: Comment
has text: I have another question regex is better or replace with eval is better in performance. Because its a millions of data. or both same ?
comment on: http://stackoverflow.com/a/52314161
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91626496
type: QuestionComment
comment on: http://stackoverflow.com/q/52339523
has text: If you're allowing yourself to use recursion and logical operators, you can abuse short-circuit `and`/`or` to branch for the base case, but it's more of an uninteresting flaw in the problem spec than actually performing addition with bitwise operators.
score: 0
type: Comment

http://stackoverflow.com/a/52407257
upvote count: 1
has comment: http://stackoverflow.com/comment/91759647
score: 1
downvote count: 0
has body: What's wrong with just storing a reference to the passed function and constructing the call on the spot? i.e.: class Bar: def __init__(self, msg): self.msg = msg self.foo = foo # a reference to foo, not needed here but used as an example def foo_method(self, *args): return self.foo(*args, msg=self.msg) # or just: foo(*args, msg=self.msg)
has comment: http://stackoverflow.com/comment/91759366
answers question: http://stackoverflow.com/q/52406813
type: Answer

http://stackoverflow.com/a/52409888
has body: Try something like this: {"anyof":[ {"type":"string","allowed":[""]}, {"anyof_type":["float","integer"]} ]},
downvote count: 1
accepted answer of: http://stackoverflow.com/q/52380547
answers question: http://stackoverflow.com/q/52380547
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 1

http://stackoverflow.com/q/52415351
has title: Search or group time series data by time in pandas
possible better answer: http://stackoverflow.com/a/52415393
type: Question
has answer: http://stackoverflow.com/a/52415393
has body: I have a dataset like this dataset = pd.read_csv('1053.csv') print dataset.head(25) date power 0 2009-7-14 0:30:00 0.039 1 2009-7-14 1:00:00 0.147 2 2009-7-14 1:30:00 0.134 3 2009-7-14 2:00:00 0.131 4 2009-7-14 2:30:00 0.076 5 2009-7-14 3:00:00 0.039 6 2009-7-14 3:30:00 0.039 7 2009-7-14 4:00:00 0.052 8 2009-7-14 4:30:00 0.148 9 2009-7-14 5:00:00 0.136 10 2009-7-14 5:30:00 0.132 11 2009-7-14 6:00:00 0.060 12 2009-7-14 6:30:00 0.034 13 2009-7-14 7:00:00 0.034 14 2009-7-14 7:30:00 0.033 15 2009-7-14 8:00:00 0.326 16 2009-7-14 8:30:00 0.140 17 2009-7-14 9:00:00 0.133 18 2009-7-14 9:30:00 0.107 19 2009-7-14 10:00:00 0.161 20 2009-7-14 10:30:00 0.042 21 2009-7-14 11:00:00 1.259 22 2009-7-14 11:30:00 1.227 23 2009-7-14 12:00:00 0.167 24 2009-7-14 12:30:00 0.518 How to extract rows containing exact time? for example. I tried to do like this df = dataset[dataset.date.str.contains("2:00:00",regex=False)] df1 = df.reset_index() del df1['index'] print df1.head(7) But it is giving me this results. date power 0 2009-7-14 2:00:00 0.131 1 2009-7-14 12:00:00 0.167 2 2009-7-14 22:00:00 0.208 3 2009-7-15 2:00:00 0.085 4 2009-7-15 12:00:00 0.097 5 2009-7-15 22:00:00 0.203 6 2009-7-16 2:00:00 0.038 I want results to be like this date power 0 2009-7-14 2:00:00 0.131 1 2009-7-15 2:00:00 0.085 2 2009-7-16 2:00:00 0.038 3 2009-7-17 2:00:00 0.141 4 2009-7-18 2:00:00 0.039 5 2009-7-19 2:00:00 0.039 6 2009-7-20 2:00:00 0.079
tagged with: data-science
score: 0
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/52415385
tagged with: data-cleaning
tagged with: python
tagged with: regex
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52415385

http://stackoverflow.com/comment/91610695
type: AnswerComment
comment on: http://stackoverflow.com/a/52331963
score: 0
type: Comment
has text: I think this is only valid for transfer learning using the pretrained models on imagenet data i.e. For from scratch training I expect it to work though with two channel. My two channel contains two images i wanna compare.

http://stackoverflow.com/comment/91619508
has text: I see. It defaults to not clickable for a standalone `HeaderView`, but clickable if it is in a `TableView`. Saved my day.
comment on: http://stackoverflow.com/a/52335805
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52304651
score: -1
has body: I want to schedule a certain task from Python. I read the desired start time from a file and repeatedly compare this to the current time. Here is the code: from datetime import datetime import sys current_time = datetime.now() f = open("starttime.txt", "r") start_time = f.read() print(current_time) print(start_time) while True: if str(current_time) == str(start_time): print("the times match") sys.exit() else: print('not yet') The prints work correctly, but when the start time arrives, the program keeps printing 'not yet'. Is there any way to fix this? Edit: I tried the suggestions that Prune said in the answers section and I got an error when trying to convert a str obj into a datetime obj saying that the format is incorrect. Here is the line of code: start_time = datetime.strptime("2018-9-12 20:00:00.000000", '%Y, %m, %d, %H, %M, %S, %f') Edit 2: My code is finally working! Thanks Prune!
type: Question
answer count: 2
upvote count: 0
favorite count: 0
tagged with: datetime
has comment: http://stackoverflow.com/comment/91557606
has answer: http://stackoverflow.com/a/52304689
has comment: http://stackoverflow.com/comment/91556784
tagged with: python
possible better answer: http://stackoverflow.com/a/52304694
has answer: http://stackoverflow.com/a/52304694
downvote count: 1
type: AnsweredQuestion
has title: Trying to make a Python program do a task at a certain time using datetime but it is not working, no errors output
accepted answer: http://stackoverflow.com/a/52304689

http://stackoverflow.com/comment/91594461
comment on: http://stackoverflow.com/a/52323633
type: AnswerComment
has text: Thanks @ShadowRanger will amend my code and take this into account.
score: 0
type: Comment

http://stackoverflow.com/a/52386301
downvote count: 2
score: -2
upvote count: 0
type: AcceptedAnswer
has body: As suggested by @JonClements what solved my problem was to use error_bad_lines=False in the pd.read_csv so it just skipped that lines causing trouble and let me execute the rest of the for loop.
accepted answer of: http://stackoverflow.com/q/52364612
answers question: http://stackoverflow.com/q/52364612
type: Answer

http://stackoverflow.com/q/52412513
accepted answer: http://stackoverflow.com/a/52412551
tagged with: command-line-arguments
tagged with: optional-arguments
tagged with: argparse
type: AnsweredQuestion
score: 3
downvote count: 0
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/52412554
answer count: 2
has answer: http://stackoverflow.com/a/52412554
tagged with: python
has title: Requiring a command line argument if an optional argument is provided
has answer: http://stackoverflow.com/a/52412551
upvote count: 3
has body: I'm trying to write a script in which a user can choose from three different options: python foo.py python foo.py -a python foo.py -b address_arg data_arg If the user chooses the last option I need them to provide two additional arguments for address and data. I currently have it working so that it requires one argument, say for the address here: parser.add_argument('-b', '--boo', dest='address', type=str, help="Help message") Which works if I run python foo.py -b 0x00 But how do I require the user provide the second argument for data?

http://stackoverflow.com/comment/91590111
has text: Okay, profiled the code, found the pain point, and renamed the question so it's more directed to that problem. :) Wow.. profilers are so useful, haha. :)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52320919

recursion
type: Tag
tags question: http://stackoverflow.com/q/52349884
tags question: http://stackoverflow.com/q/52361783
tags question: http://stackoverflow.com/q/52344126
tags question: http://stackoverflow.com/q/52298662
tag name: recursion
tags question: http://stackoverflow.com/q/52414360
tags question: http://stackoverflow.com/q/52305557
tags question: http://stackoverflow.com/q/52323614
tags question: http://stackoverflow.com/q/52303451
tags question: http://stackoverflow.com/q/52396852
tags question: http://stackoverflow.com/q/52274533
tags question: http://stackoverflow.com/q/52356091
tags question: http://stackoverflow.com/q/52301197
tags question: http://stackoverflow.com/q/52350000
tags question: http://stackoverflow.com/q/52395030
tags question: http://stackoverflow.com/q/52305851
tags question: http://stackoverflow.com/q/52285155
tags question: http://stackoverflow.com/q/52310610

http://stackoverflow.com/comment/91623603
type: QuestionComment
has text: @gus I just added the error message
comment on: http://stackoverflow.com/q/52337283
score: 0
type: Comment

http://stackoverflow.com/q/52338261
type: Question
upvote count: 2
favorite count: 0
has body: EDIT: Added Ralf's recommendation to use os.environ Trying to implement a singleton logger so that everytime a logger instance is generated, it'll only write to a specific filename. Until a new filename is specified. import logging def singleton(myClass): instances = {} def getInstance(*args,**kwargs): if myClass not in instances: instances[myClass] = myClass(*args,**kwargs) return instances[myClass] return getInstance @singleton class Logger(object): def __init__(self): self.filename = os.environ['logger_filename'] self.log = self.init_logger() def init_logger(self): fh = logging.FileHandler(self.filename + '.log') fmt = logging.Formatter("%(asctime)-6s: %(name)s - %(levelname)s - %(message)s)") fh.setFormatter(fmt) local_logger = logging.getLogger(self.filename) local_logger.setLevel(logging.DEBUG) local_logger.addHandler(fh) return local_logger What i have above will always write in "test1.log" file. os.environ['logger_filename'] = "test1" a = Logger() b = Logger() a.log.debug("Hello A") b.log.debug("Hello B") os.environ['logger_filename'] = "test2" c = Logger() c.log.debug("Hello C") Since the singleton will contain the Logger class in the instances, thus it will just return that instance and not run the __init__ If I update the singleton with the following: def singleton(myClass): instances = {} def getInstance(*args,**kwargs): if myClass not in instances: instances[myClass] = myClass(*args,**kwargs) else: instances[myClass].update_logger() return instances[myClass] return getInstance @singleton class Logger(object): def __init__(self): self.filename = os.environ['logger_filename'] self.log = self.init_logger() def init_logger(self): fh = logging.FileHandler(self.filename + '.log') fmt = logging.Formatter("%(asctime)-6s: %(name)s - %(levelname)s - %(message)s)") fh.setFormatter(fmt) local_logger = logging.getLogger(self.filename) local_logger.setLevel(logging.DEBUG) local_logger.addHandler(fh) return local_logger def update_logger(self): self.filename = os.envi…
tagged with: singleton
answer count: 1
has answer: http://stackoverflow.com/a/52338435
accepted answer: http://stackoverflow.com/a/52338435
has title: Update a property in singleton (python)
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/52417885
type: Answer
score: 1
upvote count: 1
has body: This isn't a nice answer, but it provides a method to use the extension in python. Output sql commands to a file, then use subprocess to run the file directly into the command line, like so: import subprocess import uuid import os db_file = "trial02.db" sqlite_functions_file = "libsqlitefunctions.dll" sql_file = uuid.uuid4() + ".sql" with open(sql_file, 'w') as fsql: fsql.write('/* auto script */\n\n') #load extension sql = "SELECT load_extension('" + sqlite_functions_file + "');" fsql.write(sql + '\n') #sql scripts sql = "insert into t(c) values (log(2));" fsql.write(sql + '\n') args = [ 'sqlite3' , db_file , '&lt; ', sql_file ] print(' '.join(args)) out1 = subprocess.run(' '.join(args), shell=True) os.remove(sql_file)
downvote count: 0
answers question: http://stackoverflow.com/q/52416482

http://stackoverflow.com/comment/91639831
has text: always make sure that you include your code properly when submitting questions on **SE**.
comment on: http://stackoverflow.com/q/52346002
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52273320
tagged with: selenium
has answer: http://stackoverflow.com/a/52275289
tagged with: webdriver
has answer: http://stackoverflow.com/a/52283084
type: Question
answer count: 2
downvote count: 4
upvote count: 0
has body: Hello I tried to click on a radio button with the help of selenium driver in python and it does not works . This is HTML CODE : &lt;input aria-flowto="aria8" aria-label="private key" type="radio" ng-model="walletType" value="pasteprivkey" class="ng-pristine ng-valid ng-empty ng-touched" name="200"&gt; This is my line of code : browser.find_elements_by_xpath("input[type='radio'][value='pasteprivkey']").click() And I get this error : DevTools listening on ws://127.0.0.1:52666/devtools/browser/da96711c-0446-c01-a90d-0f722691ec4c Traceback (most recent call last): File "C:\Users\Andrei\Desktop\py\teste.py", line 6, in &lt;module&gt; browser.find_element_by_xpath("//*[@type='radio'][@value='pasteprivkey']").click() File "C:\Users\Andrei\AppData\Local\Programs\Python\Python37\lib\site-packages \selenium\webdriver\remote\webelement.py", line 80, in click self._execute(Command.CLICK_ELEMENT) File "C:\Users\Andrei\AppData\Local\Programs\Python\Python37\lib\site-packages \selenium\webdriver\remote\webelement.py", line 628, in _execute return self._parent.execute(command, params) File "C:\Users\Andrei\AppData\Local\Programs\Python\Python37\lib\site-packages \selenium\webdriver\remote\webdriver.py", line 320, in execute self.error_handler.check_response(response) File "C:\Users\Andrei\AppData\Local\Programs\Python\Python37\lib\site-packages \selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotVisibleException: Message: element not visible (Session info: chrome=68.0.3440.106) (Driver info: chromedriver=2.41.578737 (49da6702b16031c40d63e5618de03a32ff6c197e),platform=Windows NT 6.1.7601 SP1 x86_64) Someone can help me please ? I also tried to copy xpath with inspect element and I get this weird thing : /html/body/section[1]/div[1]/main/article[1]/div[2]/wallet-decrypt-drtv/article/section[1]/label[9]/input
tagged with: css-selectors
favorite count: 0
tagged with: xpath
type: UnansweredQuestion
score: -4
has comment: http://stackoverflow.com/comment/91494839
tagged with: python
has title: How to click on the element as per the HTML provided through selenium-webdriver and Python

http://stackoverflow.com/comment/91596813
comment on: http://stackoverflow.com/q/52323636
has text: You would add a logical condition to check if windows or not. Or let the `os.path` library handle it
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52331603
has comment: http://stackoverflow.com/comment/91609885
score: 3
answers question: http://stackoverflow.com/q/52331534
upvote count: 3
has body: I suggestion the following solution still based on zip() built-in function, without any needed import directive: constant = 3 A = [1,2,3] B = [0.1,0.2,0.3] ob = list(zip([constant]*len(A), A ,B)) print(ob) # [(3,1,0.1),(3,2,0.2),(3,3,0.3)]
type: Answer
downvote count: 0

http://stackoverflow.com/q/52352678
answer count: 1
tagged with: image-processing
tagged with: image
has title: keras ImageDataGenerator.flow with color_mode
has body: I am using python with keras, and wish to use keras image pre processing, some of my images are rgb while some are grayscale, I need to read all of them and changing the dimension of the grayscale images to x,x,3 or disposing them, and would like to do it as a part of the .flow function the same way I could use color_mode with .flow_from_directory, than can be set to rgb and read all the images as rgb even when they are grayscale, Is that possible?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52353149
downvote count: 0
tagged with: keras
favorite count: 0
type: Question
tagged with: deep-learning
score: 1
accepted answer: http://stackoverflow.com/a/52353149
upvote count: 1
tagged with: python

http://stackoverflow.com/q/52273076
type: UnansweredQuestion
tagged with: msys2
has comment: http://stackoverflow.com/comment/91493361
score: 3
has comment: http://stackoverflow.com/comment/91493756
type: Question
has answer: http://stackoverflow.com/a/52273643
has body: When I search for a Package like this pacman -Qs python local/python2 2.7.15-2 A high-level scripting language local/scons 3.0.1-1 (base-devel) Extensible Python-based build utility 2 packages are listed and no python-3 ackage is found but if I try to install any python like this pacman -S python resolving dependencies… looking for conflicts … Packages (2) mpdecimal-2.4.2-2 python-3.6.6-1 a python-3 package does appear ! What is the effective way to query packages using pacman ?
has title: How to search efficiently for a package using Msys2 pacman?
answer count: 1
downvote count: 1
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/91493721
favorite count: 0
tagged with: pacman-package-manager

http://stackoverflow.com/comment/91728351
score: 0
type: AnswerComment
type: Comment
has text: @pinoyyid Thanks! I've checked a folder's parents before and after a name change it doesn't appear to have changed how the list of parents is stored, but at least I know to avoid this issue before. And gotcha, that makes sense, but doesn't seem to allow for parameterized queries very easily.
comment on: http://stackoverflow.com/a/52336286

http://stackoverflow.com/a/52453363
accepted answer of: http://stackoverflow.com/q/52406058
answers question: http://stackoverflow.com/q/52406058
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91854883
has comment: http://stackoverflow.com/comment/91854958
type: Answer
has body: I hope that by the client machine, you mean some local server, that runs 24/7, and not some client's laptop/desktop. Please understand that any solution involving copying of database tables may be brittle, especially when there are foreign keys like created_by that point to a user, and in your local setup, they may have to point to some local user (or one dummy user). Moreover, there might be other database changes as well in the server application, and unless you change corresponding models in your client Django application also, you can't use the same at the client side, and if you are adding columns using some other tool, they may no longer be usable from Django. Any table created using django models, and changed otherwise, will push you into a hell lot of issues. So one thing is for sure, you will need to make changes to both applications separately, whenever you want to make any changes. Anyways, even if you manage to make schema changes locally, and manage to keep it "backward compatible", how will your client application know what to do with those new tables &amp; columns unless it's code is changed? So it's better to avoid tables copying and try to use some more standard way like using APIs to connect the 2 systems so that you have complete control over how the data is copied. You can expose selected tables on server application through an API, and on client side you can use a system like django-celery-beat to run a cron that hits the API, and fetches the latest data from server application, in form of JSON, and save it in desired format in local DB. Whenever there is some change in server application, and you need that change in local application. You add that data to respective API's response. And do changes in client application to fetch and save/utilise that data. Example, if there's a model purchases in the remote application: class Purchase(models.Model): customer_id = models.ForeignKey(CustomerTable, related_name='purchased_by') sales_agent = models.F…
upvote count: 1
score: 1

http://stackoverflow.com/comment/91774051
score: 0
type: Comment
type: QuestionComment
has text: Please confirm with pip freeze what version of "msrestazure" is installed, and edit your post with that version. Also, do you an infinite stacktrace where you can put some sections to give an idea of where is the loop?
comment on: http://stackoverflow.com/q/52415096

http://stackoverflow.com/comment/134264782
type: AnswerComment
score: 0
has text: "Your interpreter" is not "PHP" anything for Python code. Aside from that, OP already recognized this difference, accounted for it, and tried both versions anyway.
type: Comment
comment on: http://stackoverflow.com/a/72219052

http://stackoverflow.com/comment/91811312
type: Comment
comment on: http://stackoverflow.com/a/52417952
type: AnswerComment
has text: if this answers your question, could you accept it so other people looking for the same answer might see this?
score: 0

http://stackoverflow.com/comment/91734963
type: Comment
type: QuestionComment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/180302/discussion-between-thebluephantom-and-karthik-reddy).
comment on: http://stackoverflow.com/q/52393400
score: 0

http://stackoverflow.com/a/52319271
answers question: http://stackoverflow.com/q/52318734
upvote count: 1
type: Answer
has body: You can use a list comprehension: df['Firstname']= [names.get_first_name(gender) for gender in df['Gender'].str.lower()] And hear is a hack that reads all of the names by gender (together with their probabilities), and then randomly samples. import names def get_names(gender): if not isinstance(gender, (str, unicode)) or gender.lower() not in ('male', 'female'): raise ValueError('Invalid gender') with open(names.FILES['first:{}'.format(gender.lower())], 'rb') as fin: first_names = [] probs = [] for line in fin: first_name, prob, dummy, dummy = line.strip().split() first_names.append(first_name) probs.append(float(prob) / 100) return pd.DataFrame({'first_name': first_names, 'probability': probs}) def get_random_first_names(n, first_names_by_gender): first_names = ( first_names_by_gender .sample(n, replace=True, weights='probability') .loc[:, 'first_name'] .tolist() ) return first_names first_names = {gender: get_names(gender) for gender in ('Male', 'Female')} &gt;&gt;&gt; get_random_first_names(3, first_names['Male']) ['RICHARD', 'EDWARD', 'HOMER'] &gt;&gt;&gt; get_random_first_names(4, first_names['Female']) ['JANICE', 'CAROLINE', 'DOROTHY', 'DIANE']
downvote count: 0
score: 1

http://stackoverflow.com/q/52352797
tagged with: python
has comment: http://stackoverflow.com/comment/91650521
type: UnansweredQuestion
score: -4
has answer: http://stackoverflow.com/a/52353178
linked to: http://stackoverflow.com/q/8056130
has body: im having trouble figuring out how this works. can someone pls explain it to me. the code works btw. def foo(x, y): def goo(x, y): x = 2*x y = 3*y z = x+y print('x =', x, '; y =', y, '; z =', z) return z def hoo(x, y): x = x//2 y = y//3 z = x+y print('x =', x, '; y =', y, '; z =', z) return z z = hoo(x,y) + goo(y,x) print('x =', x, '; y =', y, '; z =', z) return z x = 10 y = 20 z = 30 print('x =', x, '; y =', y, '; z =', z) z = foo(x,y) print('x =', x, '; y =', y, '; z =', z)
type: Question
downvote count: 4
has title: im having trouble figuring out how this nested functions get the values. can someone pls explain it to me. the code works btw
tagged with: function
upvote count: 0
answer count: 1
favorite count: 0
tagged with: nested

http://stackoverflow.com/a/52382371
has body: It's because Spring-Redis has a default valueSerializer, it will serialize the raw byte[]. byte[] rawValue(Object value) { if (valueSerializer() == null &amp;&amp; value instanceof byte[]) { return (byte[]) value; } return valueSerializer().serialize(value); } So set Serializer to null solved this problem @Bean public RedisTemplate&lt;byte[], byte[]&gt; redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate&lt;byte[], byte[]&gt; template = new RedisTemplate&lt;&gt;(); template.setConnectionFactory(redisConnectionFactory); // set this false will keep all Serializer null template.setEnableDefaultSerializer(false); return template; }
answers question: http://stackoverflow.com/q/52381475
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52381475

http://stackoverflow.com/q/52338272
tagged with: python
tagged with: plotly
answer count: 0
downvote count: 0
type: UnansweredQuestion
has body: I made a simple line graph with matplotlib and now I want to make it with plotly so I can add a slider so I can iterate through years rather than be a static graph, this would be more interactive. Here is my code so far. df_summed = df_pre_2003.groupby(['year']) ['nAllNeonic'].sum().reset_index() q=df_summed.year r=df_summed.nAllNeonic data = [dict( visible = False, #line=dict(color='#00CED1', width=6), #name = ' = '+str(step), x = q, y = r )] print(data) #data[0] seems off but not getting an index out of range error so leaving for now data[0]['visible'] = True steps=[] for i in range (0,11,len(q)): steps.append(q) step=dict( method = 'restyle', args = ['visible', [False] * len(data)], ) step['args'][1][i] = True # Toggle i'th trace to "visible" steps.append(step) sliders=[dict( active = 11, currentvalue = {"prefix": "Year: "}, #pad = {"t": 50}, steps = steps )] layout = dict(sliders=sliders) fig = dict(data=data, layout=layout) plot(fig, filename='test slider') When I run it I get this error: Invalid element(s) received for the 'steps' property of layout.slider Invalid elements include: [0 1991 1 1992 2 1993 3 1994 4 1995 5 1996 6 1997 7 1998 8 1999 9 2000 10 2001 11 2002 Name: year, dtype: int64] The 'steps' property is a tuple of instances of Step that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.slider.Step - A list or tuple of dicts of string/value properties that will be passed to the Step constructor Supported dict properties: args,execute, label, etc I do not get why it is telling me that since it is exactly the years I want to step through with the slider. When I print the data is gives me this (which is right): [{'visible': False, 'x': 0 1991 1 1992 2 1993 3 1994 4 1995 5 1996 6 1997 7 1998 8 1999 9 2000 10 2001 11 2002 Name: year, dtype: int64, 'y': 0 0.0 1 0.0 2 0.0 3 11207.2 4 82134.0 5 101002.5 6 185898.7 7 166324.4 8 140227.8 9 133949.2 10 143690.4 11 168746.2 Name: nAllNeonic, dtype: float64}] When I print steps is …
score: 1
favorite count: 0
type: Question
has title: Plotly: ValueError: Invalid element(s) received for the 'steps' property of layout.slider
upvote count: 1

http://stackoverflow.com/comment/91643080
has text: It's doing a search by name like e.g. `max` and expects the format `max1234` for items in `nlist`. Eventually you will have a list (`versions`) only containing `'1234'` (sticking to my example). So if `nlist` also contained `max4321`, `versions` would look like this: `['1234', '4321']`.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52348707

http://stackoverflow.com/comment/91544524
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52297472
has text: Look into `np.isclose`
type: Comment

http://stackoverflow.com/a/52326622
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52325673
has body: Problem was in category_slug as two friends said that @Manjo Jadhav ,@JPG i used id instead of category_slug and it's working . tnx for help friends.

http://stackoverflow.com/comment/91762027
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52408850
has text: @chepner: that's the whole idea of my answer. If the instance has unique attributes, and it never uses them, it's rather a dict than a class. They should be moved up to cat
score: 0

http://stackoverflow.com/comment/91568608
comment on: http://stackoverflow.com/q/52304003
score: 0
type: Comment
has text: @MauritsEvers Yes I meant is aspect ratio. So the plot look more rectangular
type: QuestionComment

http://stackoverflow.com/a/52428486
score: 2
downvote count: 0
has body: First, get the data into RDD: rdd = sc.parallelize([10,21,90,34,40,98,21,44,59,21,90,34,29,19, 21,90,34,29,49,78]) Display the above given list and the first element of the list. rdd.collect() rdd.take(1) Also I want to display the sorted output (ascending and descending) through an RDD and display the distinct elements of the list using an RDD. rdd.distinct().sortBy(lambda x:x).collect() rdd.distinct().sortBy(lambda x:-x).collect() Display maximum and minimum of given list. rdd.max() rdd.min() Combine above list with a new input in the form: { 30,35,45,60,75,85} and display output. newrdd = sc.parallelize({30,35,45,60,75,85}) rdd.union(newrdd).collect() Provide the sum of the list elements using reduce with distinct values. rdd.distinct().reduce(lambda x,y:x+y) Provide the sum of the list elements using reduce. rdd.reduce(lambda x,y:x+y) P.S. In fact, if you sort your element in rdd descending, the max element is the first element of this rdd. So, You can get the max of this rdd without using max(), so, this is the code: rdd.distinct().sortBy(lambda x:-x).take(1)
has comment: http://stackoverflow.com/comment/91818808
type: Answer
has comment: http://stackoverflow.com/comment/91835068
upvote count: 2
has comment: http://stackoverflow.com/comment/91893617
answers question: http://stackoverflow.com/q/52428093

http://stackoverflow.com/q/52305912
has title: matplotlib subplots selective axis sharing
has comment: http://stackoverflow.com/comment/91565096
has comment: http://stackoverflow.com/comment/91562558
has comment: http://stackoverflow.com/comment/91593519
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/50971091
answer count: 0
score: 1
tagged with: matplotlib
linked to: http://stackoverflow.com/q/14503423
upvote count: 1
has body: I have 8 figures (4 rows, 2 columns). I want all figures to share axes, except for one. Is this possible in matplotlib without doing it by hand? Example: fig = plt.figure(); ax = fig.subplots(4,2,sharex='all',sharey='all') for j in np.arange(4): plt.sca(ax[j,0]) plt.plot(np.random.random(5),'.') plt.sca(ax[j,1]) plt.plot(np.arange(5),'.') plt.sca(ax[0,0]) # Code here to unlink this one axis from the shared system plt.gca().set_yscale('log',basey=10) # I only want this one axis to be log
type: Question

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

mlflow
type: Tag
tags question: http://stackoverflow.com/q/52372118
tags question: http://stackoverflow.com/q/52331254
tag name: mlflow

http://stackoverflow.com/comment/91646500
has text: What's the difference between *I receive the following output* and *the output should look like the following*?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52344570

http://stackoverflow.com/a/73420463
has body: From the django documentation: You can also use the syntax {% now "Y" as current_year %} to store the output (as a string) inside a variable. This is useful if you want to use {% now %} inside a template tag like blocktranslate for example: {% now "Y" as current_year %} {% blocktranslate %}Copyright {{ current_year }}{% endblocktranslate %}
upvote count: 2
answers question: http://stackoverflow.com/q/52296306
has comment: http://stackoverflow.com/comment/139908957
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/a/52335805
has body: If you check the source code of the creation of the xxxHeaderView you see the following: ... QHeaderView *vertical = new QHeaderView(Qt::Vertical, q); vertical-&gt;setSectionsClickable(true); vertical-&gt;setHighlightSections(true); q-&gt;setVerticalHeader(vertical); QHeaderView *horizontal = new QHeaderView(Qt::Horizontal, q); horizontal-&gt;setSectionsClickable(true); horizontal-&gt;setHighlightSections(true); q-&gt;setHorizontalHeader(horizontal); ... So what's missing is to enable setSectionsClickable(), you can also add setHighlightSections(True). def createTable(self): ... # Optional 1: use custom headerview, sorting not working hh =MyHeaderView(tv) tv.setHorizontalHeader(hh) # solution hh.setSectionsClickable(True) # &lt;--- +++ hh.setHighlightSections(True) # &lt;--- +++ # Optional 2: get tableview's header, sorting works # hh = tv.horizontalHeader() tv.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) tv.setShowGrid(True) hh.setSectionsMovable(True) hh.setStretchLastSection(False) hh.setSectionResizeMode(QtWidgets.QHeaderView.Stretch) tv.setSortingEnabled(True) return tv
accepted answer of: http://stackoverflow.com/q/52332534
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52332534
score: 5
type: Answer
upvote count: 5
has comment: http://stackoverflow.com/comment/91619508

http://stackoverflow.com/a/52301658
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Extending is handled by loaders rather than templates, so you need a loader. How about something like this? from jinja2 import DictLoader, Environment, Template def render_with_layout(template_string, layout, **kwargs): loader = DictLoader({ 'layout': layout, # wrap in Template() if necessary 'template': Template('{% extends "layout" %}' + template_string), }) env = Environment(loader=loader) return env.get_template('template').render(**kwargs)
accepted answer of: http://stackoverflow.com/q/52301447
answers question: http://stackoverflow.com/q/52301447
has comment: http://stackoverflow.com/comment/91552011
score: 1

http://stackoverflow.com/q/52338865
has answer: http://stackoverflow.com/a/52339952
duplicate of: http://stackoverflow.com/q/32846846
tagged with: matlab
type: Question
has body: In Matlab, there is the command repelem which works as follows (see https://www.mathworks.com/help/matlab/ref/repelem.html#buocbhj-2): e.g.: Create a matrix and repeat each element into a 3-by-2 block of a new matrix. A = [1 2; 3 4] B = repelem(A,3,2) A = (2×2) 1 2 3 4 B = (6×4) 1 1 2 2 1 1 2 2 1 1 2 2 3 3 4 4 3 3 4 4 3 3 4 4 What is the best way to do the same in Numpy? A = np.arange(1,5).reshape((2,2)) B = ...
tagged with: numpy
answer count: 2
linked to: http://stackoverflow.com/q/32846846
possible better answer: http://stackoverflow.com/a/52339952
downvote count: 0
score: 4
favorite count: 0
tagged with: python
has title: Repeat each element of a matrix in as a block into a new matrix
upvote count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52338907
accepted answer: http://stackoverflow.com/a/52338907

http://stackoverflow.com/comment/91659877
type: Comment
comment on: http://stackoverflow.com/a/52356791
type: AnswerComment
score: 0
has text: @hpaulj, Yep that is true. Big difference using click is that the above is an entire program. The framework injects the options and arguments directly into the decorated functions. Also click is generally more composable than argparse/optparse. Over time I find the programs more easily maintainable. Cheers.

http://stackoverflow.com/comment/91501593
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52276875
has text: Thank you @AlexanderMcFarlane

http://stackoverflow.com/comment/91539849
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52294098
has text: `send_file ( filepath, attachment_filename=filepath, as_attachment=True, conditional=True )` i get `TypeError: cannot use a string pattern on a bytes-like object`

http://stackoverflow.com/comment/91571393
has text: @user7727210 what is your expected output (in `seq_gen`)?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52306024

http://stackoverflow.com/a/52325844
has comment: http://stackoverflow.com/comment/91603739
downvote count: 0
answers question: http://stackoverflow.com/q/52321116
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/91602988
upvote count: 1
has body: As per the HTML you have shared to invoke click() on the checkbox you can use either of the following solutions: CSS_SELECTOR: driver.find_element_by_css_selector("label.has-checkbox.terms input.checkbox#order_terms").click() XPATH: driver.find_element_by_xpath("//label[@class='has-checkbox terms']//input[@class='checkbox' and @id='order_terms']").click() Update As you are seeing the error Other element would receive the click you can adopt either of the following solutions: Induce WebDriverWait: CSS_SELECTOR: WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "label.has-checkbox.terms input.checkbox#order_terms"))).click() XPATH: WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[@class='has-checkbox terms']//input[@class='checkbox' and @id='order_terms']"))).click() Using WebDriverWait and ActionChains: CSS_SELECTOR: myElement = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "label.has-checkbox.terms input.checkbox#order_terms"))) ActionChains(driver).move_to_element(myElement).click(myElement).perform() XPATH: myElement = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[@class='has-checkbox terms']//input[@class='checkbox' and @id='order_terms']"))) ActionChains(driver).move_to_element(myElement).click(myElement).perform()

http://stackoverflow.com/q/52411680
has body: I have a script that is iterating through two specific columns in an excel file and capturing the Item ID and the Item Value in to a dictionary. The problem I am having it that the Item IDs are floats and Python treats 1.1 the same as it would 1.10 The Item IDs are as follows: 1.1 -=&gt; this one is problematic with 1.10 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 1.11 It then continues to the 2.x series 2.1 -=&gt; this is treated the same as 2.10 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11 2.12 I have tried to se them as strings to make them different from each other but that does not appear to work. The final output form the date I compile is an excel file with the following columns: filename item_id item_value Currently it treats 1.1 any 1.10 as 1.10 in excel - I need them to be distinct... Anyone have any recommendations no how best to handle this?
has title: Python 3 - having issue with float variables
has comment: http://stackoverflow.com/comment/91767124
downvote count: 3
duplicate of: http://stackoverflow.com/q/13962837
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91767295
has comment: http://stackoverflow.com/comment/91767238
has comment: http://stackoverflow.com/comment/91767151
has answer: http://stackoverflow.com/a/52411841
linked to: http://stackoverflow.com/q/2574080
answer count: 1
has comment: http://stackoverflow.com/comment/91767198
has comment: http://stackoverflow.com/comment/91767137
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/91767217
linked to: http://stackoverflow.com/q/13962837

http://stackoverflow.com/q/52405481
has title: Python requests code from Postman is not working
has comment: http://stackoverflow.com/comment/91754718
downvote count: 0
type: UnansweredQuestion
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/91756772
has body: I've used postman for getting the access token from server and it's working fine. but when i copy the python code from postman and run that code in IDE it's showing some errors like max entries exceeded. import requests url = "https://web.com/oauth/token" payload = "type=authorizatio&amp;code=mycode&amp;id=abcdefghi&amp;client=kjsisjnsui675eaa9WqksiisP" headers = {'Content-Type': 'application/x-www-form-urlencoded'} response = requests.request("POST", url, data=payload, headers=headers) print(response.text)
has comment: http://stackoverflow.com/comment/91755101
has comment: http://stackoverflow.com/comment/91754717
tagged with: python
answer count: 0
upvote count: 1
tagged with: python-requests
has comment: http://stackoverflow.com/comment/91755223

http://stackoverflow.com/a/52355862
score: 1
accepted answer of: http://stackoverflow.com/q/52355758
has comment: http://stackoverflow.com/comment/91656685
answers question: http://stackoverflow.com/q/52355758
has comment: http://stackoverflow.com/comment/91656324
type: Answer
has comment: http://stackoverflow.com/comment/91656593
has comment: http://stackoverflow.com/comment/91656817
upvote count: 1
has comment: http://stackoverflow.com/comment/91656496
has comment: http://stackoverflow.com/comment/91656581
has comment: http://stackoverflow.com/comment/91656561
has comment: http://stackoverflow.com/comment/91656518
has comment: http://stackoverflow.com/comment/91656399
has body: You have this condition in your code: if row[0] == key: print(row[2]) status = row[2] status is not defined anywhere else, so if row[0] is not equal to key, status is undefined. What should status be in that case?
has comment: http://stackoverflow.com/comment/91656888
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52283184
has comment: http://stackoverflow.com/comment/91515758
accepted answer: http://stackoverflow.com/a/52283337
type: AnsweredQuestion
score: 3
has title: How to split a string with multiple delimiters without deleting delimiters in Python?
type: Question
has answer: http://stackoverflow.com/a/52283337
answer count: 1
has comment: http://stackoverflow.com/comment/91514629
favorite count: 0
has comment: http://stackoverflow.com/comment/91515776
upvote count: 3
has comment: http://stackoverflow.com/comment/91515352
has comment: http://stackoverflow.com/comment/91515075
tagged with: python
has comment: http://stackoverflow.com/comment/91514634
linked to: http://stackoverflow.com/q/2136556
downvote count: 0
has comment: http://stackoverflow.com/comment/91515036
has body: I currently have a list of filenames in a txt file and I am trying to sort them. The first this I am trying to do is split them into a list since they are all in a single line. There are 3 types of file types in the list. I am able to split the list but I would like to keep the delimiters in the end result and I have not been able to find a way to do this. The way that I am splitting the files is as follows: import re def breakLines(): unsorted_list = [] file_obj = open("index.txt", "rt") file_str = file_obj.read() unsorted_list.append(re.split('.txt|.mpd|.mp4', file_str)) print(unsorted_list) breakLines() I found DeepSpace's answer to be very helpful here Split a string with "(" and ")" and keep the delimiters (Python), but that only seems to work with single characters. EDIT: Sample input: file_name1234.mp4file_name1235.mp4file_name1236.mp4file_name1237.mp4 Expected output: file_name1234.mp4 file_name1235.mp4 file_name1236.mp4 file_name1237.mp4
linked to: http://stackoverflow.com/q/47001777
has comment: http://stackoverflow.com/comment/91515213

http://stackoverflow.com/q/52303977
has answer: http://stackoverflow.com/a/52304019
has answer: http://stackoverflow.com/a/52304087
possible better answer: http://stackoverflow.com/a/52304021
has comment: http://stackoverflow.com/comment/91555618
tagged with: python
type: AnsweredQuestion
has title: How do i find the biggest number that are not in a list?
has answer: http://stackoverflow.com/a/52304016
has answer: http://stackoverflow.com/a/52304021
type: Question
has comment: http://stackoverflow.com/comment/91557532
has body: I am trying to make a program that gives you the average, total, and biggest number entered. I am stuck at the biggest number part. My numbers are not in a list, so I don't know how to find the biggest one. num=0 total=0 average=0 count=0 while True: num=input("enter a number:") num=int(num) if num==-999: break total=total + num count=count+1 biggest = max(total) average=total/count #print the results print("the total is:", total) print("the biggest number is:", biggest) print("the average is:", average) I would like it to print the biggest number at the end. Thanks
has comment: http://stackoverflow.com/comment/91555611
has answer: http://stackoverflow.com/a/52305088
has answer: http://stackoverflow.com/a/52304106
accepted answer: http://stackoverflow.com/a/52304106
answer count: 7
has answer: http://stackoverflow.com/a/52304029
score: 0

http://stackoverflow.com/comment/91632980
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52343073
has text: Few improvements: 1) creating a class like that is, in my opinion, OOP abusing. You dont need a class and its object just to do some statements in python. 2) str(input()) is not necessary, for the input returns object of str type by itself (just write input()). 3) instead of "Loading {}". format (".." * i) use print("Loading", ".." * i) (print will automatically separate its parameters with whitespace)

http://stackoverflow.com/comment/91749625
has text: Thanks for all the replies, as you may have guessed I am new to the wacky world of python and this question had been driving me up the wall and in the end it turns out to be so simple an answer. thanks again..
comment on: http://stackoverflow.com/q/52391110
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91656965
type: Comment
comment on: http://stackoverflow.com/q/52356168
has text: Please post the code as text.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91708777
type: Comment
score: 0
type: AnswerComment
has text: Note that the Java code starts at `0` and not `1`, so it checks if the first and last elements sum up to `5`.
comment on: http://stackoverflow.com/a/52366824

http://stackoverflow.com/q/52376313
score: 4
upvote count: 4
has title: Converting py file to exe, Cannot find existing PyQt5 plugin directories
has answer: http://stackoverflow.com/a/52376965
downvote count: 0
has body: I'm quite new to phyton and I've just finished my first application. Now, I'm trying to compile my .py file to an .exe buy that doestn seem to work. I've looked everywhere for a solutio to my problem, but I just cant seem to find one. When I run this command: pyinstaller gui.py this error shows up: 4815 INFO: Loading module hooks... 4815 INFO: Loading module hook "hook-encodings.py"... 4913 INFO: Loading module hook "hook-pydoc.py"... 4913 INFO: Loading module hook "hook-PyQt5.py"... 5019 WARNING: Hidden import "PyQt5.sip" not found! 5019 INFO: Loading module hook "hook-PyQt5.QtCore.py"... 5096 WARNING: Unable to find Qt5 translations C:/qt5b/qt_1524647842210/_h_env/Library/translations\qtbase_*.qm. These translations were not packaged. 5096 INFO: Loading module hook "hook-PyQt5.QtGui.py"... Traceback (most recent call last): File "c:\users\ivo\anaconda3\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\users\ivo\anaconda3\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\Ivo\Anaconda3\Scripts\pyinstaller.exe\__main__.py", line 9, in &lt;module&gt; File "c:\users\ivo\anaconda3\lib\site-packages\PyInstaller\__main__.py", line 111, in run run_build(pyi_config, spec_file, **vars(args)) File "c:\users\ivo\anaconda3\lib\site-packages\PyInstaller\__main__.py", line 63, in run_build PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs) File "c:\users\ivo\anaconda3\lib\site-packages\PyInstaller\building\build_main.py", line 838, in main build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build')) File "c:\users\ivo\anaconda3\lib\site-packages\PyInstaller\building\build_main.py", line 784, in build exec(text, spec_namespace) File "&lt;string&gt;", line 17, in &lt;module&gt; File "c:\users\ivo\anaconda3\lib\site-packages\PyInstaller\building\build_main.py", line 241, in __init__ self.__postinit__() File "c:\users\ivo\anaconda3\lib\site-packages\PyInstaller\building\datastruct.py", line 15…
favorite count: 0
has answer: http://stackoverflow.com/a/52844042
linked to: http://stackoverflow.com/q/39736000
has answer: http://stackoverflow.com/a/56438976
answer count: 5
type: UnansweredQuestion
tagged with: pyinstaller
tagged with: python
tagged with: anaconda
tagged with: pyqt5
type: Question
has answer: http://stackoverflow.com/a/52675981
has answer: http://stackoverflow.com/a/53992095

http://stackoverflow.com/q/52376408
has answer: http://stackoverflow.com/a/52376497
tagged with: python
has body: I have a dataframe in the left side (in orange) with the LeadOrderIDs. I want to add a column to the left to see whether the list of OrderId in the right (purple) is in the LeadOrder (Orange). Don't use the inner join... How should I use python - Pandas to do this? Thanks for your help.
score: 0
tagged with: match
linked to: http://stackoverflow.com/q/19960077
answer count: 1
has comment: http://stackoverflow.com/comment/91697557
duplicate of: http://stackoverflow.com/q/19960077
type: UnansweredQuestion
tagged with: dataframe
has title: How to add a column to see whether they are match based on two lists of IDs?
tagged with: pandas
type: Question

http://stackoverflow.com/comment/91756866
comment on: http://stackoverflow.com/a/52406444
type: AnswerComment
has text: @brunodesthuilliers: thanks. I didn't know that (I try to avoid `isinstance`). Added it to the answer
score: 0
type: Comment

http://stackoverflow.com/q/52407275
type: Question
linked to: http://stackoverflow.com/q/47237378
answer count: 1
downvote count: 0
tagged with: python
favorite count: 0
has title: Python's Decimal type not Real?
upvote count: 1
duplicate of: http://stackoverflow.com/q/47237378
has answer: http://stackoverflow.com/a/52407430
accepted answer: http://stackoverflow.com/a/52407430
type: AnsweredQuestion
has body: Consider the following: from decimal import Decimal from numbers import Number, Complex, Real z = Decimal(0) # Expected: a == b == c == True # Actual (Python 3.6.5): a = isinstance(z, Number) # True b = isinstance(z, Complex) # False c = isinstance(z, Real) # False Decimal appears to implement everything that is needed to be considered Real according to PEP3141, so what gives? Notably, fractions.Fraction is correctly categorized by the above snippet (e.g. a == b == c == True).
score: 1

http://stackoverflow.com/comment/91531952
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52276973
has text: Is this a tensorflow question ?

http://stackoverflow.com/q/52317441
downvote count: 0
has body: I can draw 3 lines this way: sns.lineplot(x="week", y="mean", data=df) sns.lineplot(x="week", y="min", data=df) sns.lineplot(x="week", y="max", data=df) So we have here min max and average value, they have precomputed before: I want want fulfill with color between min and max, it have to look this way: How to do that?
type: Question
has comment: http://stackoverflow.com/comment/124359831
has comment: http://stackoverflow.com/comment/91582256
tagged with: matplotlib
score: 4
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52317485
accepted answer: http://stackoverflow.com/a/52317485
linked to: http://stackoverflow.com/q/16417496
tagged with: seaborn
tagged with: python
upvote count: 4
duplicate of: http://stackoverflow.com/q/16417496
type: AnsweredQuestion
has title: Fulfill between two lineschart in seaborn FacetGrid

http://stackoverflow.com/comment/138606479
comment on: http://stackoverflow.com/a/52405696
type: AnswerComment
score: 0
type: Comment
has text: This works but I wonder if it is different nowadays?

http://stackoverflow.com/q/52411090
tagged with: python
has answer: http://stackoverflow.com/a/52411336
has body: I am trying to solve a programming task, and i have ran into some trouble. The task reads: Consider the usual formula for computing solutions to the quadratic equation: ax2 + bx + c = 0 given by x = sqrt(b± b^2−4ac/2a) Write a program reads values for a,b and c from the command line. Use exceptions to handle missing arguments, and handle invalid input where b^2-4ac &lt; 0 My program is as follows: from math import sqrt import sys try: a = float(sys.argv[1]) b = float(sys.argv[2]) c = float(sys.argv[3]) bac = b**2 - 4*a*c if bac &lt; 0: raise ValueError except IndexError: while True: input("No arguments read from command line!") a = float(input("a = ? ")) b = float(input("b = ? ")) c = float(input("c = ? ")) bac = b**2 - 4*a*c if bac &gt; 0: break if bac &lt; 0: while True: print("Please choose values of a,b,c so\ that b^2 - 4ac &gt; 0") a = float(input("a = ? ")) b = float(input("b = ? ")) c = float(input("c = ? ")) bac = b**2 - 4*a*c if bac &gt; 0: break except ValueError: while True: input("Please choose values of a,b,c so that b^2 - 4ac &gt; 0") a = float(input("a = ? ")) b = float(input("b = ? ")) c = float(input("c = ? ")) if bac &gt; 0: break for i in range(-1,2,2): # i=-1, next loop &gt; i=1 x = (b + i*sqrt(bac)) / (2*a) print("x = %.2f"%(x)) It seems to be working fine, but in the case below it doesnt: terminal &gt; python quadratic_roots_error2.py No arguments read from command line! a = ? 1 b = ? 1 c = ? 1 Please choose values of a,b,c so that b^2 - 4ac &gt; 0 a = ? 5 b = ? 2 c = ? -3 No arguments read from command line! a = ? 5 b = ? 2 c = ? -3 x = -0.60 x = 1.00 Why does the program spit out the message "No arguments read from command line!"? I want the program to print every solution where b^2-4ac > 0, and whenever b^2-4ac &lt; 0 i want the message "Please chose values of a,b,c so that b^2 - 4ac > 0" to be printed, like it does.
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91766088
has answer: http://stackoverflow.com/a/52411212
has comment: http://stackoverflow.com/comment/91765865
has title: Repeated IndexError in terminal caused by exception
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52445172
tagged with: valueerror
favorite count: 0
linked to: http://stackoverflow.com/q/23294658
tagged with: exception
type: UnansweredQuestion
tagged with: input
upvote count: 1

http://stackoverflow.com/a/52383551
has comment: http://stackoverflow.com/comment/91711657
type: Answer
answers question: http://stackoverflow.com/q/52383473
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/91711409
has comment: http://stackoverflow.com/comment/91711778
has body: Use enumerate : for i, df in enumerate(dfs): print(i)
downvote count: 0
has comment: http://stackoverflow.com/comment/91711293

http://stackoverflow.com/comment/91745417
comment on: http://stackoverflow.com/a/52400611
type: AnswerComment
type: Comment
has text: i try the first standard code - but nothing print on screen. and i try the second code - panda - but there is an error ( Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> import pandas as pd ImportError: No module named pandas )
score: 0

http://stackoverflow.com/a/52430071
type: Answer
answers question: http://stackoverflow.com/q/52429988
has comment: http://stackoverflow.com/comment/122473801
downvote count: 1
has comment: http://stackoverflow.com/comment/92747877
has comment: http://stackoverflow.com/comment/91805425
has body: Use async for in your comprehension. See PEP 530 -- Asynchronous Comprehensions data = [i async for i in get_data()] Depending on what version of Python you're using, this may only be available in async def functions.
has comment: http://stackoverflow.com/comment/91806473
upvote count: 27
score: 26
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52429988
has comment: http://stackoverflow.com/comment/122473769

http://stackoverflow.com/comment/91682235
type: Comment
comment on: http://stackoverflow.com/a/52364100
type: AnswerComment
has text: I came across that, but unfortunately I didn't see how to call functions at whim, i.e. not periodically. The only way I could see to do that would be the relatively inconvenient solution of checking periodically for a flag, e.g. is_paused, and calling the appropriate function based on this flag. This becomes an issue when there are multiple flags being checked once every 60th of a second. I tend to mix up threads and processes, as I'm new to multithreading in Python. I assumed it would block the current process as I was spawning a new process which was being blocked by Pyglet's event loop.
score: 0

http://stackoverflow.com/a/52318711
score: 2
upvote count: 2
has body: CHOICES needs to be a list of 2--tuples consisting of the db value and the display value. For instance: GENDER_CHOICES = [ ("N", _('Non specificato')), ("U", _('Uomo')), ("D", _('Donna')) ]
downvote count: 0
answers question: http://stackoverflow.com/q/52318594
type: Answer

http://stackoverflow.com/q/52329820
score: 1
has title: Speeding up Pandas .apply function. Counting rows and doing operation with them
has body: I have a huge database of migratory movements and I wrote some scripts to get useful info from it but it's really really slow. I'm not a professional coder as you will see, and I was wondering how to make this data gathering more efficient. To start, the initial CSV database is structured as follows: 1 row = 1 person Age Sex City_start City_destination ... Person 1 Person 2 ..... The final database structure: Balance_2004 Balance_2005 .... City1 City2 .... For calculating this Balance per city and year I created a function that filters the initial database to count how many rows have a specific city in city_destination (INs), how many rows in city_start (OUTs) and then a simple sum to calculate the balance as INs - OUTs: # idb = initial database # City1 = pre-existing in final database def get_balance(city, df): ins = idb.City_start[idb.City_start == City1].count() outs = idb.City_destination[idb.City_destination == City1].count() balance = ins - outs return balance Then with this function I used pandas apply to populate the final database as: # fdb = final database fdb['Balance_2004'] = idb['City_start'].apply(get_balance, df=idb) This works good, the ending result is what I need and I'm using in total 42 apply functions to get more specific data like balance per sex, per ages groups... but to give an idea of how slow this is, I started the script (with 42 functions) 45min ago and is still running. Is there any way to do this in a less time-consuming way? Thanks in advance
has answer: http://stackoverflow.com/a/52329947
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: performance
has answer: http://stackoverflow.com/a/52329916
tagged with: apply
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91666799
favorite count: 0
tagged with: pandas

http://stackoverflow.com/comment/91611941
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52331326
has text: Not understand, sorry. Maybe need `purchase_data.groupby(['Gender'])["Price"].sum().reset_index()`

http://stackoverflow.com/a/52381659
answers question: http://stackoverflow.com/q/52358022
score: 4
type: Answer
upvote count: 4
has body: I guess you are doing some spelling mistake of BeautifulSoup, its case sensitive. if not, use requests in your code as: from teams.models import * from bs4 import BeautifulSoup from django.conf import settings import requests, os, string def scrapeTeamPage(url): res = requests.get(url) soup = BeautifulSoup(res.content, 'html.parser') teamInfo = soup.find('div', 'profile_info')
downvote count: 0

http://stackoverflow.com/comment/91797401
type: Comment
comment on: http://stackoverflow.com/a/52425251
score: 0
type: AnswerComment
has text: @schwobaseggl I mean in django templates. I tried to pass that `nested_dict` within the context to render the template in `django.views`.

http://stackoverflow.com/q/52331065
has title: Variable not defined error, even though it is?
tagged with: python
has comment: http://stackoverflow.com/comment/91608764
has comment: http://stackoverflow.com/comment/91609025
has comment: http://stackoverflow.com/comment/91609589
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91609237
linked to: http://stackoverflow.com/q/423379
downvote count: 1
tagged with: discord.py
has answer: http://stackoverflow.com/a/52331533
has comment: http://stackoverflow.com/comment/91609158
score: -1
has comment: http://stackoverflow.com/comment/91608845
has comment: http://stackoverflow.com/comment/91609187
type: Question
upvote count: 0
answer count: 1
tagged with: variables
has comment: http://stackoverflow.com/comment/91609299
tagged with: defined
has comment: http://stackoverflow.com/comment/91609166
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91608916
has body: I'm making a discord.py bot, and I'm trying to implement a command that will tell you how much time there is until the period ends. The code works by itself, but if I try to implement it into the bot I get this error: NameError: name 'timee' is not defined (The variable is called 'timee' since I also use the time.sleep() function later) This is the code it has a problem with: def setTime(): global timee print(timee) if timee &gt; 59 and timee &lt; 100: timee -= 100 timee += 60 elif timee &gt; 159 and timee &lt; 200: timee -= 100 timee += 60 elif timee &gt; 259 and timee &lt; 300: timee -= 100 timee += 60 I have the print(timee) there to test if it thinks it's defined or not, which it doesn't. This is my code that calls the setTime function (and should also set timee) if currentTime &lt; start: timee = start - currentTime print(timee) setTime() doThing() await client.send_message(message.channel, content = "School hasn't started yet! It starts in %s:%s" % (hours, minutes)) print("%s got the time left." % message.author) Edit: The 'timee' variable is declared outside of the if statement and the function as well. Edit 2: I tried what someone commented, (The comment is deleted now) which is doing def setTime(timee): instead of def setTime(): global timee And that works. I don't know if this is inefficient or what, but it works. ALSO, this exact same code works if It's not in the discord bot.

http://stackoverflow.com/a/52310156
has body: It would seem that you are mistaking how to reference docker containers from outside all containers. axios.get('http://127.0.0.1:5000/api/test')... Should refer to where the docker container is listening. Inside a container, this would indeed be backend, but outside, i.e. in your web browser, it would be a reference to the host running the container, followed by the port. Since you've mounted it on port 80 on the host (and 90 for the frontend), you should update the get to : axios.get('http://{hostname or ip}:80/api/test') If it's all running on the same host, then you could use 127.0.0.1 or localhost for your testing.
upvote count: 22
accepted answer of: http://stackoverflow.com/q/52309527
has comment: http://stackoverflow.com/comment/91567338
has comment: http://stackoverflow.com/comment/91567888
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91567444
answers question: http://stackoverflow.com/q/52309527
has comment: http://stackoverflow.com/comment/91567578
type: Answer
has comment: http://stackoverflow.com/comment/91567685
has comment: http://stackoverflow.com/comment/91568012
has comment: http://stackoverflow.com/comment/91567821
has comment: http://stackoverflow.com/comment/91567706
score: 22

http://stackoverflow.com/comment/91694866
comment on: http://stackoverflow.com/q/52374941
has text: i still new in fact can you help me with a code please
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/57670093
score: 4
accepted answer of: http://stackoverflow.com/q/52279068
type: Answer
upvote count: 4
has body: Hey I finally found a solution to my problem.I just need to use @app.after_request like this: @app.after_request def after_request(response): response.headers.set('Access-Control-Allow-Origin', '*') response.headers.set('Access-Control-Allow-Headers', 'Content-Type,Authorization') response.headers.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') return response This will take care of any cors errors
answers question: http://stackoverflow.com/q/52279068
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52340963
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52341132
tagged with: string
favorite count: 0
tagged with: python-3.x
has title: How to insert a newline character before a word(s) that contains a colon
type: Question
has comment: http://stackoverflow.com/comment/91628966
tagged with: python
has comment: http://stackoverflow.com/comment/91628952
upvote count: 1
tagged with: split
has answer: http://stackoverflow.com/a/52341136
has comment: http://stackoverflow.com/comment/91629070
has answer: http://stackoverflow.com/a/52341135
has answer: http://stackoverflow.com/a/52341150
tagged with: newline
has comment: http://stackoverflow.com/comment/91629521
answer count: 5
possible better answer: http://stackoverflow.com/a/52341266
accepted answer: http://stackoverflow.com/a/52341150
has answer: http://stackoverflow.com/a/52341266
has body: I have a string that is all one line like: Breed: Pembroke Welsh Corgi Price: $2,200 Gender: Female Nickname: Koko Age: 9 Weeks Old Color/Markings: yellow and white Size at Maturity: Medium Availability Date: 09/30/2018 Shipping Area: Worldwide Payment Method: Money Order/Cashier's Check, Paypal, Credit Cards, Cash And I want the output to be: Breed: Pembroke Welsh Corgi Price: $2,200 Gender: Female Nickname: Koko etc. etc. Basically insert a \n before the new category that ends in a colon. Thanks for the replies in advance!
type: AnsweredQuestion

http://stackoverflow.com/comment/91747590
comment on: http://stackoverflow.com/q/52401802
score: 0
type: Comment
type: QuestionComment
has text: My bad, I didn't know, I'll check that!

http://stackoverflow.com/a/52324110
downvote count: 0
upvote count: 2
has body: Here is what I believe to be a pretty elegant solution: def bounce(n): for x in range(-n, n+1): print(abs(x)) Our loop goes from the negative of n to the positive of n, printing the absolute value.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52323676
answers question: http://stackoverflow.com/q/52323676
type: Answer
has comment: http://stackoverflow.com/comment/91626828
score: 2

graphics
tag name: graphics
tags question: http://stackoverflow.com/q/52364306
type: Tag
tags question: http://stackoverflow.com/q/52414478
tags question: http://stackoverflow.com/q/52291509
tags question: http://stackoverflow.com/q/52410962

http://stackoverflow.com/comment/91530007
type: AnswerComment
has text: The three needed dimensions are: Samples, timesteps & features. In this case we assume that you have a single feature (or signal) which is why it is 1. Seeing as you have random data, it's a bit hard to explain but if you used actual timeseries data it would be easier to understand.
comment on: http://stackoverflow.com/a/52289843
score: 0
type: Comment

http://stackoverflow.com/comment/91673810
type: QuestionComment
score: 1
has text: @skdadle Do **not** use `shell=True`. It changes how the command list is interpreted.
comment on: http://stackoverflow.com/q/52364601
type: Comment

http://stackoverflow.com/q/52346788
linked to: http://stackoverflow.com/q/18465326
has comment: http://stackoverflow.com/comment/91639341
has comment: http://stackoverflow.com/comment/91641997
has title: RecursionError: maximum recursion depth exceeded in Karatsuba multiplication
tagged with: python
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: algorithm
has comment: http://stackoverflow.com/comment/91642085
has comment: http://stackoverflow.com/comment/91639181
has body: I am implementing karatsuba multiplication.In my assignment, I have to calculate the multiplication of 2 64 digit numbers. but while implementing it I am getting the error- RecursionError: maximum recursion depth exceeded while calling a Python object So my question is is the error due to my laptops limitation or is karatsuba not applicable for such large numbers? My code is- def karatsuba(num1,num2): if (len(str(num1))==1 and len(str(num2))==1): return num1*num2 else: print(num1,num2) a,b=int(str(num1)[:len(str(num1))//2]),int(str(num1)[len(str(num1))//2:]) c,d=int(str(num2)[:len(str(num2))//2]),int(str(num2)[len(str(num2))//2:]) #print(a,b,c,d) res1=karatsuba(a,c) res2=karatsuba(b,d) res3=karatsuba(a+b,c+d) res4=res3-res2-res1 #print(res1,res2,res4) n=max(len(str(num1)),len(str(num2))) #print(n) final_result=math.pow(10,n)*res1+math.pow(10,n/2)*res4+res2 return final_result edit-The code works for small numbers but for large numbers it gives the error- ValueError: invalid literal for int() with base 10: ''
downvote count: 0
has comment: http://stackoverflow.com/comment/91643282
favorite count: 0

http://stackoverflow.com/comment/91536182
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52291385
has text: Thank you very much for your answer. It works perfectly! Just one question, why was my question downvoted? Is it too trivial or did I miss some standards?

http://stackoverflow.com/q/52292879
tagged with: python
downvote count: 0
type: AnsweredQuestion
score: 1
has body: I am new to python. I need to get the Usage details using python sdk. I am able to do the same using the usage detail API. But unable to do so using the sdk. I am trying to use the azure.mgmt.consumption.operations.UsageDetailsOperations class. The official docs for UsageDetailsOperations https://learn.microsoft.com/en-us/python/api/azure-mgmt-consumption/azure.mgmt.consumption.operations.usage_details_operations.usagedetailsoperations?view=azure-python#list-by-billing-period specifies four parameters to create the object (i.e.client:Client for service requests,config:Configuration of service client, serializer:An object model serializer,deserializer:An object model deserializer). Out of these parameters I only have the client. I need help understanding how to get the other three parameters or is there another way to create the UsageDetailsOperations object. Or is there any other approach to get the usage details. Thanks!
type: Question
has title: Azure Python SDK to get usage details - UsageDetailsOperations Class
upvote count: 1
has answer: http://stackoverflow.com/a/52301403
accepted answer: http://stackoverflow.com/a/52301403
answer count: 1
favorite count: 0
tagged with: sdk
tagged with: azure

http://stackoverflow.com/q/52408768
accepted answer: http://stackoverflow.com/a/52408796
has comment: http://stackoverflow.com/comment/91761545
has title: Django dynamic filter based on variable (str)
tagged with: filter
has comment: http://stackoverflow.com/comment/91761673
answer count: 1
downvote count: 0
favorite count: 0
has body: I am writing a function that can return table items based on a dynamically inserted model. So I need to refrain from using the model name in the function. Now I sometimes will have a many-to-many relationship with another model and want to select on that. Say I have a projects = ManyToMany(Projects) field in my Files model. Now I can use: filter(projects__in=[1]) to select for files related to projects with id 1, but I need the projects part of this filter to be dynamic, so I can use something like: a_field = 'projects' filter(a_field+'__in'=[1]) which obviously doesn't work. How should I do this?
tagged with: django
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/4720079
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91761561
has answer: http://stackoverflow.com/a/52408796
duplicate of: http://stackoverflow.com/q/4720079
score: 1
type: Question

http://stackoverflow.com/q/52323636
has comment: http://stackoverflow.com/comment/91595893
has title: Python3 - how to deal with different strings elements (quotes, slash and such) between Windows and other OS
score: 0
has body: I am passing as parameter a string; to a Python3 function. This string is composed by different variables; and in few cases, I need to have the quotes in the string, so I did concatenate various strings to make it work. This is the string I use in my code, to call an application called conn.app, which use a file called lac.tsd to perform various operations. The whole code logic is not relevant for the purpose of this question; since the root cause of the errors is the fact that path strings and quoted strings behave differently between OS (like Windows and Unix-like systems for example) execute_string = '-b -m path="/Users/user/lac.tsd" -a app="/build/deploy/conn.app" -o output=/Users/user/out/' This works without problems on OSX and Linux; but when I run this on Windows machines, I get an error OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '"' After digging a bit in the differences between OS, it is clear to see that my path for the tsd file is pointing at /Users/.. which is a pure unix construct for the file system; so that has been replaced when I run the code on Windows. Although, there is still the problem with conn.app, which on windows is conn.exe; the location is the same, so I did fix that too. Last but not least, 2 issues tied to the OS itself: the / is \ in Windows, so that has to change; and same goes for quotes and double quotes. Does Python have any construct that help programmers to handle cases like mine, where you build a string of parameters to pass to a function, and have in it single and double quotes, paths and such? To expand on the original point: how do you handle this between OS? Beside a simple RE to replace a character with another; is there any construct used in Python that allow code to operate independently from the OS used, when dealing with paths, quoted strings and multiple nested quoted strings?
has comment: http://stackoverflow.com/comment/91596564
has comment: http://stackoverflow.com/comment/91595908
has comment: http://stackoverflow.com/comment/91596607
has comment: http://stackoverflow.com/comment/91596973
tagged with: python
has answer: http://stackoverflow.com/a/52324971
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91596813
type: Question
accepted answer: http://stackoverflow.com/a/52324971
answer count: 1

java
tags question: http://stackoverflow.com/q/52287664
tags question: http://stackoverflow.com/q/52337479
tags question: http://stackoverflow.com/q/52394799
tags question: http://stackoverflow.com/q/52403334
tags question: http://stackoverflow.com/q/52370910
tags question: http://stackoverflow.com/q/52377295
tags question: http://stackoverflow.com/q/52279041
tags question: http://stackoverflow.com/q/52299314
tags question: http://stackoverflow.com/q/52347984
tags question: http://stackoverflow.com/q/52272903
tags question: http://stackoverflow.com/q/52380351
tags question: http://stackoverflow.com/q/52381475
tags question: http://stackoverflow.com/q/52345913
tags question: http://stackoverflow.com/q/52349926
tags question: http://stackoverflow.com/q/52396862
tags question: http://stackoverflow.com/q/52276360
tag name: java
tags question: http://stackoverflow.com/q/52317109
tags question: http://stackoverflow.com/q/52310756
tags question: http://stackoverflow.com/q/52421822
type: Tag
tags question: http://stackoverflow.com/q/52400010
tags question: http://stackoverflow.com/q/52304492

http://stackoverflow.com/q/52370630
has comment: http://stackoverflow.com/comment/91686171
has comment: http://stackoverflow.com/comment/91685867
has body: I want to use a function which takes as input a tensor and Returns the index with the largest value across axes of a tensor. I know there exists a function tf.argmax() that does exactly the same, but how do I implement it on my own (this may be necessary incase of implementing some custom function)? Let us suppose for now the function takes as input only 1D tensor. So, the function needs to be of following signature: argmax( input, #input is a 1D tensor name=None ) I tried implementing it this way: def argmax(input, name=None): maxValue=0 maxIndex=0 for i in range(input.get_shape()[0]): if input[i]&gt;maxValue: maxValue=input[i] maxIndex=i return maxIndex However this does not work since during the construction phase, the values are not yet intialized and hence I cannot compare two values as I did in the above code. So, is there a way where we can write out custom functions like tf.argmax, tf.equal, etc?
favorite count: 0
has title: How to implement tf.argmax on our own?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52370927
tagged with: machine-learning
tagged with: python
score: 2
downvote count: 0
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/91686079
has comment: http://stackoverflow.com/comment/91686252
upvote count: 2
answer count: 1

http://stackoverflow.com/q/52419935
has body: I'm trying to use a python script with NodeJS. the code below works, but I need a way to do a 'pip install pandas' on 'npm install' nodeJS router.get('/', (req, res) =&gt; { const filePath = 'python/testing2.py' const spawn = require("child_process").spawn; const pythonProcess = spawn('python3',[filePath, '-l']); util.log('readingin') pythonProcess.stdout.on('data', (data) =&gt; { const textChunk = data.toString('utf8');// buffer to string util.log(textChunk); res.json({'working': true, 'data': textChunk}) }); }); python: import sys from pandas import read_csv from pandas import datetime def parser(x): return datetime.strptime('190'+x, '%Y-%m') print("Output from Python") series = read_csv('shampoo-sales.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser) print (series) sys.stdout.flush()
has title: import python packages for script called with nodejs
type: Question
has answer: http://stackoverflow.com/a/52420336
score: 3
tagged with: npm
upvote count: 3
tagged with: pip
tagged with: python
answer count: 1
tagged with: node.js
accepted answer: http://stackoverflow.com/a/52420336
type: AnsweredQuestion
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/91616569
score: 0
type: Comment
has text: No rush - thank you so much.
comment on: http://stackoverflow.com/a/52323222
type: AnswerComment

architecture
tags question: http://stackoverflow.com/q/52368747
type: Tag
tag name: architecture

http://stackoverflow.com/a/59891721
type: Answer
answers question: http://stackoverflow.com/q/52293709
has body: It is not possible to change the order of def button in ANSA while coding in Script editor. You can create a GUI instead, using the Designer Window in ANSA .
score: 0

http://stackoverflow.com/comment/91798670
comment on: http://stackoverflow.com/q/52421041
has text: ok I get it! thanks so much
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91610910
has text: I have been trying to create a custom class along the lines of the post mentioned above, and also tried to copy and rewrite the `LabelEncoder` without success: I kept getting the error you mentioned. I am now thinking: what if we give the variables to the pipeline in reverse order, thus `(y, X)`, and add a class between the encoder and the classifier whose sole purpose is to return the two arrays in reverse order, thus swapping them? I'll try to implement it.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52317506
type: AnswerComment

http://stackoverflow.com/comment/122576964
comment on: http://stackoverflow.com/a/67389309
type: AnswerComment
type: Comment
has text: Should I bother saving cookies (e.g. via pickle module) or does loading a profile imply saving them under the hood?
score: 1

http://stackoverflow.com/q/52301447
accepted answer: http://stackoverflow.com/a/52301658
has title: Render Jinja2 Template to string with layout
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91550884
has answer: http://stackoverflow.com/a/52301658
tagged with: python
score: 2
upvote count: 2
has body: Is it possible to return jinja2 template to string with layout also from string ? I know it's possible like this : from jinja2 import Template html = "{{var}}" t = Template(html) print t.render(var="X") but I need to use jinja template extending like this layout = "HEY {%block content%}{%endblock%}" html = "{%block content%}{{var1}}{%endblock%}" t = Template(html, layout=layout) Of course layout=layout doesn't work - this is what I'm looking for thanks
tagged with: jinja2
type: Question
type: AnsweredQuestion

http://stackoverflow.com/a/52340495
answers question: http://stackoverflow.com/q/52301798
upvote count: 1
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91640552
has body: I don't do ios dev, but i'm pretty sure you can't write to arbitrarly locations in it. I think you can use the App.user_data_dir property to get a path you can write to in a persistent way.

http://stackoverflow.com/q/52307209
type: Question
accepted answer: http://stackoverflow.com/a/52307498
score: 0
tagged with: http://stackoverflow.com/tag/csv
has title: How could I convert a simple XML to CSV using Python?
answer count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
upvote count: 2
downvote count: 2
has body: This is my XML file test.xml: &lt;nodes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/nodes_file.xsd"&gt; &lt;node id="0" x="0.0" y="0.0" type="traffic_light"/&gt; &lt;node id="1" x="0.0" y="500.0" type="priority"/&gt; &lt;node id="2" x="500.0" y="0.0" type="priority"/&gt; &lt;node id="3" x="0.0" y="-500.0" type="priority"/&gt; &lt;node id="4" x="-500.0" y="0.0" type="priority"/&gt; &lt;/nodes&gt; I want to convert it to a CSV file which contains the following columns: id, x, y, type. So it would be something like this: id,x,y,type 0,0.0,0.0,traffic_light 1,0.0,500.0,priority 2,500.0,0.0,priority 3,0.0,-500.0,priority 4,-500.0,0.0,priority How could I do it via Python? Thanks for your attention!
tagged with: python
has answer: http://stackoverflow.com/a/52307498
type: AnsweredQuestion

http://stackoverflow.com/q/52368556
has body: I'm having two strings string1 = "apple banna kiwi mango" string2 = "aple banana mango lemon" I want the resultant of addition of these two strings (not concatenation) i.e. result should look like result = "apple banana kiwi mango lemon" My current approach is rather simple. Tokenize the multiline string (the above strings are after tokenization), remove any noises (special/ newline characters/ empty strings) The next step is to identify the cosine similarity of the strings, if it is above 0.9, then I add one of the string to final result Now, here is the problem. It doesn't cover the part where one string contains one half of a word and other contains the other half (or correct word in some cases) of word. I have also added this function in my script. But again the problem remains. Any help on how to move forward with this is appreciated. def text_to_vector(text): words = WORD.findall(text) return Counter(words) def get_cosine(vec1, vec2): intersection = set(vec1.keys()) &amp; set(vec2.keys()) numerator = sum([vec1[x] * vec2[x] for x in intersection]) sum1 = sum([vec1[x]**2 for x in vec1.keys()]) sum2 = sum([vec2[x]**2 for x in vec2.keys()]) denominator = math.sqrt(sum1) * math.sqrt(sum2) if not denominator: return 0.0 else: return float(numerator) / denominator def merge_string(string1, string2): i = 0 while not string2.startswith(string1[i:]): i += 1 sFinal = string1[:i] + string2 return sFinal for item in c: for j in d: vec1 = text_to_vector(item) vec2 = text_to_vector(j) r = get_cosine(vec1, vec2) if r &gt; 0.5: if r &gt; 0.85: final.append(item) break else: sFinal = merge_string(item, j) #print("1.", len(sFinal), len(item), len(j)) if len(sFinal) &gt;= len(item) + len(j) -8: sFinal = merge_string(j, item) final.append(sFinal) #print("2.", len(sFinal), len(item), len(j)) temp.append([item, j]) break
has answer: http://stackoverflow.com/a/52368737
has title: Merge Similar Strings Python
answer count: 2
has comment: http://stackoverflow.com/comment/91681519
downvote count: 0
possible better answer: http://stackoverflow.com/a/52368737
tagged with: string
linked to: http://stackoverflow.com/q/46860908
favorite count: 0
tagged with: python
tagged with: regex
tagged with: nlp
tagged with: text
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/52369057
upvote count: 2
has comment: http://stackoverflow.com/comment/91681479
has comment: http://stackoverflow.com/comment/91681505
accepted answer: http://stackoverflow.com/a/52369057
type: Question
has comment: http://stackoverflow.com/comment/91682066
has comment: http://stackoverflow.com/comment/91681415

http://stackoverflow.com/q/52359467
accepted answer: http://stackoverflow.com/a/52359486
type: Question
has title: Comparing every line in a list with the previous one (multiple numbers per line) - python
answer count: 1
has answer: http://stackoverflow.com/a/52359486
has body: I have a list like so : (478.9013929574081, 397.2738906303129, 448.89480301797414, 542.7951217324505) (472.90651700176176, 424.78297261394266, 502.43464632003395, 603.6891367440179) (468.10938689187105, 427.371498928372, 511.24005916622326, 614.6921165073483) (461.6597495547769, 421.4376873975313, 507.23734519352905, 611.8902878449529) (425.487279262123, 402.292710366325, 507.77891332142167, 621.1597417845782) (419.40784031782096, 398.2749509071074, 506.50067770937756, 621.1464694579362) (413.0082657866075, 397.6126602713513, 510.7013095813061, 627.1330222592819) (413.0683323863853, 398.88024170228, 512.6260305724528, 629.2101773020437) (422.5678390801497, 406.35400653231824, 516.6077609026671, 631.4456260240206) (415.5577803083175, 401.4576799299969, 514.6341115538066, 630.8472626355573) (418.55910283476703, 404.5636199237953, 517.0606565634685, 632.8283515818844) (434.41278792007824, 420.3742027152652, 529.0694380783063, 642.42857214518) (415.3420769027216, 404.21410273005847, 519.1040751582156, 635.7586341103566) (443.0505653390292, 432.6358785944982, 541.5291344399056, 654.1970677458233) (465.30516533741354, 431.5888053340561, 520.7964063717009, 625.9943265634903) (419.0982438430095, 388.7972967913932, 491.81636612895943, 605.2795535885007) (427.7796057482705, 392.0655443853052, 489.5256797085785, 600.7623416078488) (454.50745633403204, 411.26272364904656, 496.8873392060136, 602.2765376994458) (445.03208123588115, 402.5587576107865, 491.1756847902183, 598.375762651814) (470.62598009859505, 431.7971898284693, 516.3417600231103, 619.7167200776199) (467.00822669571744, 428.97165850610526, 514.9142489788748, 619.044977203982) (429.377607418294, 400.45615209690385, 501.56268775922575, 613.4860469091849) (434.0340968876508, 392.2060647938512, 484.2164776843913, 593.4859705680318) (428.7396884234395, 385.71715081057516, 478.4743675782727, 588.5386312124532) (437.47633322723084, 395.40554135462384, 486.3183547162734, 594.9332249370034) (460.586968864012, 417.39712012343…
score: 0
tagged with: python
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/q/52390397
tagged with: neural-network
downvote count: 0
score: 1
tagged with: keras
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/52391055
tagged with: python
has answer: http://stackoverflow.com/a/52391055
has body: I have been trying with simple mnist example. Sorry if the question is the very basic one. from keras.datasets import mnist from keras.layers import Input, Conv2D, Dense from keras.models import Sequential from keras.utils import np_utils def myModel(): model= Sequential() layer1 = Dense(1024, input_shape=(784,), activation='relu') layer2 = Dense(512, activation='relu') layer3 = Dense(10, activation='softmax') model.add (layer1) model.add (layer2) model.add(layer3) model.compile(loss='categorical_crossentropy', optimizer='adam') return model if __name__ == '__main__': print "Inside the main function " model = myModel() (trainX, trainY), (testX, testY) = mnist.load_data() print ("TrainX shape is ", trainX.shape) trainX = trainX.reshape(trainX.shape[0], trainX.shape[1] * trainX.shape[2]) trainY = np_utils.to_categorical(trainY, 10) model.fit(trainX, trainY, batch_size=200, epochs=1) print ("Let's predict now..") print ("Shae of x and shape of 100" , trainX.shape, trainX[10].shape) result = model.predict(trainX[100].reshape(1,784 )) print result import matplotlib.pyplot as plt plt.subplot(2,2,1) plt.imshow(trainX[1100].reshape(28,28)) plt.show() The output value of the last layer is [[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]] How do i have to interpret this result?. Is this not a probability distribution for the result?. if not how do i get the same?
accepted answer: http://stackoverflow.com/a/52390994
answer count: 2
tagged with: machine-learning
upvote count: 1
tagged with: mnist
has title: Why does softmax provide always a probability of 1.0?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52390994

http://stackoverflow.com/comment/91700028
type: QuestionComment
comment on: http://stackoverflow.com/q/52377699
has text: Please format your code properly and show a full example.
score: 0
type: Comment

http://stackoverflow.com/comment/91606758
score: 0
type: Comment
type: QuestionComment
has text: You can't use `extras` *in the `requirements.txt` file*, no. You can define additional files, perhaps, but I'd first like to see how your `setup.py` file is set up.
comment on: http://stackoverflow.com/q/52328999

http://stackoverflow.com/comment/91518503
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52284965
has text: It's getting the variable as alert(numberVariable); displays 1 in a pop up box. The issue is that this: data: { id: numberVariable } isn't displaying id: 1 when the javascript is run.

http://stackoverflow.com/q/52414505
accepted answer: http://stackoverflow.com/a/52414617
downvote count: 1
has comment: http://stackoverflow.com/comment/91772938
has comment: http://stackoverflow.com/comment/91772894
answer count: 5
has comment: http://stackoverflow.com/comment/91773113
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/52414547
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91773223
favorite count: 0
has answer: http://stackoverflow.com/a/52414617
type: Question
has title: Python's list comprehension: Modify list elements if a certain value occurs
possible better answer: http://stackoverflow.com/a/52414754
has answer: http://stackoverflow.com/a/52414812
has body: How can I do the following in Python's list comprehension? nums = [1,1,0,1,1] oFlag = 1 res = [] for x in nums: if x == 0: oFlag = 0 res.append(oFlag) print(res) # Output: [1,1,0,0,0] Essentially in this example, zero out the rest of the list once a 0 occurs.
tagged with: python
has comment: http://stackoverflow.com/comment/91772944
has answer: http://stackoverflow.com/a/52414754
score: 10
has comment: http://stackoverflow.com/comment/91773021
upvote count: 11
has answer: http://stackoverflow.com/a/52414874
has comment: http://stackoverflow.com/comment/91773447

data-cleaning
tags question: http://stackoverflow.com/q/52415351
tags question: http://stackoverflow.com/q/52409689
type: Tag
tags question: http://stackoverflow.com/q/52333531
tag name: data-cleaning

http://stackoverflow.com/q/52415034
has comment: http://stackoverflow.com/comment/91784185
answer count: 1
has title: python take single argument input which can be two different types
favorite count: 0
has comment: http://stackoverflow.com/comment/91773922
tagged with: python
accepted answer: http://stackoverflow.com/a/52420118
type: AnsweredQuestion
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91774003
upvote count: 0
has body: I am in a situation where I am accepting a user input, that can either be True or False or a string. I know i can just take input as string then parse it to boolean if its either true or false, but is there a better way to parse input as either string or boolean? parser.add_argument('--s', type=int, default=False) thank you.
score: -1
has answer: http://stackoverflow.com/a/52420118

http://stackoverflow.com/comment/91693352
type: Comment
type: QuestionComment
has text: @ShadowRanger thanks a lot. I think it's enough for this problem. Next time I will formulate my questions according to your example
comment on: http://stackoverflow.com/q/52373652
score: 0

http://stackoverflow.com/q/52408698
linked to: http://stackoverflow.com/q/36607952
downvote count: 0
possible better answer: http://stackoverflow.com/a/52411202
has title: Import Python module into AWS Lambda
type: Question
score: 5
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/91784901
answer count: 2
has body: I have followed all the steps in the documentation: https://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html create a directory. Save all of your Python source files (the .py files) at the root level of this directory. Install any libraries using pip at the root level of the directory. Zip the content of the project-dir directory) But after I uploaded the zip-file to lambda function, I got the error message when I test the script my code: import psycopg2 #my code... the error: Unable to import module 'myfilemane': No module named 'psycopg2._psycopg' I don't know where is the suffix '_psycopg' from... Any help regarding this?
has answer: http://stackoverflow.com/a/52410516
accepted answer: http://stackoverflow.com/a/52410516
favorite count: 0
tagged with: aws-lambda
tagged with: postgresql
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/52411202
type: AnsweredQuestion

http://stackoverflow.com/q/52341463
tagged with: pandas
has title: How to get a ranking of frequency of elements in a row?
downvote count: 0
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/52342214
tagged with: python
answer count: 4
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52341818
accepted answer: http://stackoverflow.com/a/52342214
type: Question
possible better answer: http://stackoverflow.com/a/52341561
has answer: http://stackoverflow.com/a/52341561
tagged with: dataframe
has body: I have a DataFrame named a. I want to get the top two most frequent elements in each row. Input: import pandas as pd a=pd.DataFrame({'A1':['food','movie','sport'],'A2':['game','traffic','health'], 'A3':['food','health','education'],'A4':['game','travel','other'], 'A5':['social','other','sport']}) Output: A1 A2 A3 A4 A5 0 food game food game social 1 movie traffic health travel other 2 sport health education other sport Expected: top1 top2 0 food game 1 health movie 2 sport education As you see, maybe some elements in a row appear at the same frequency.For such elements, I just select one of them for ranking, for example, all of elements in row 1 appear once, so I just randomly select two of them for ranking. Hopefully for help and thanks!
has answer: http://stackoverflow.com/a/52342689

http://stackoverflow.com/comment/91675241
comment on: http://stackoverflow.com/a/52352717
type: Comment
has text: @ayushgupta I did literally what you suggested here. all the code above is the same, I've just replaced the httpresponse with the rest_framework response
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91624453
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52337370
has text: you need to read excel again and again after some duration of time by some scheduler like windows task scheduler or cron job in linux. And compare the max_rows of previous read excel to newest read.

http://stackoverflow.com/a/52328092
type: Answer
has comment: http://stackoverflow.com/comment/91614136
answers question: http://stackoverflow.com/q/52327740
has body: If I understood correctly, you need to use the difflib library. I might be wrong. But let me try suggesting anyway. Right now I am also trying to figure out how to compare two text files, but for all I know, comparing a line of text could be done using the following: See Differ(), but I haven't quite figured how to properly use that one yet. It compares lines and displays: removed lines, new lines and modified lines. Could be exported into a separate file. I'd probably try using difflib.Differ() in your case. EDIT: But looking at your jsons to compare, there's a lot of different lines, so you'll receive a lot of unneeded lines.
score: 0

http://stackoverflow.com/comment/91763068
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52409681
has text: Ok, thanks. So in the first example, let's say all processes take roughly the same time to execute. The second loop will wait until the first process has finished, and then very quickly loop through all other 9 processes, almost instantaneously?
type: AnswerComment

http://stackoverflow.com/comment/91615630
score: 1
has text: It's clear that `list.extend()` is now used to restore the pickled data, before any other attributes are set. I'm looking into *why* that is and what a good workaround would be. Worst-case: detect that `options` is not yet set in `append` or `extend` and store that data for `__init__` to pick up later on.
comment on: http://stackoverflow.com/q/52333864
type: Comment
type: QuestionComment

http://stackoverflow.com/a/62323213
score: 18
has comment: http://stackoverflow.com/comment/120522860
upvote count: 18
has body: Use Conda instead of pip. It works perfectly conda install PyAudio
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52283840

http://stackoverflow.com/comment/91742752
score: 0
type: Comment
has text: this is not working. If I use window_size = 3 then it will get [('I', 'have', 'a'), ('I', 'have', 'pen'), ('I', 'have', 'to'), ('I', 'have', 'use'), ('I', 'a', 'pen'), ('I', 'a', 'to'), ('I', 'a', 'use'), ('I', 'pen', 'to'), ('I', 'pen', 'use'), ('I', 'to', 'use'), ('have', 'a', 'pen'), ('have', 'a', 'to'), ('have', 'a', 'use'), ('have', 'pen', 'to'), ('have', 'pen', 'use'), ('have', 'to', 'use'), ('a', 'pen', 'to'), ('a', 'pen', 'use'), ('a', 'to', 'use'), ('pen', 'to', 'use')].... this is too much different from expected output of skip-gram
type: AnswerComment
comment on: http://stackoverflow.com/a/52399263

http://stackoverflow.com/a/52418870
has comment: http://stackoverflow.com/comment/91802679
answers question: http://stackoverflow.com/q/52417833
downvote count: 0
score: 1
has body: You should create a ColumnDataSource object from your data and use it when creating the glyphs in your figures. As long as the figures are sharing the same datasource, they will have the same tool effects. When using a ColumnDataSource, you need to specify the data using the column names in the datasource rather than directly passing the arrays themselves. For example: from bokeh.io import output_file, show from bokeh.layouts import column from bokeh.plotting import figure from bokeh.models import ColumnDataSource from bokeh.models import PanTool,ResetTool,HoverTool,WheelZoomTool,SaveTool,BoxZoomTool output_file("layout.html") x = list(range(11)) y0 = x y1 = [10 - i for i in x] y2 = [abs(i - 5) for i in x] #tools='hover,xpan,xwheel_zoom,box_zoom,save,reset' tools=[HoverTool(),BoxZoomTool(dimensions='width'), PanTool(dimensions='width'), SaveTool(), ResetTool()] datasource = ColumnDataSource({'x': x, 'y0': y0, 'y1': y1, 'y2': y2}) # create a new plot s1 = figure(plot_width=250, plot_height=250, title=None,tools=tools) s1.circle('x', 'y0', size=10, color="navy", alpha=0.5, source=datasource) # create another one s2 = figure(plot_width=250, plot_height=250, title=None,tools=tools) s2.triangle('x', 'y1', size=10, color="firebrick", alpha=0.5, source=datasource) # create and another s3 = figure(plot_width=250, plot_height=250, title=None,tools=tools) s3.square('x', 'y2', size=10, color="olive", alpha=0.5, source=datasource) # put the results in a column and show show(column(s1, s2, s3))
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91816397

http://stackoverflow.com/comment/91583742
comment on: http://stackoverflow.com/a/52302774
type: AnswerComment
has text: @emax, even for the dummy dataset, grouping over year and month (my last solution) is taking 4.6 ms vis-a-vis 8.66 ms with my original solution using to_period
score: 0
type: Comment

vtk
tags question: http://stackoverflow.com/q/52413804
type: Tag
tags question: http://stackoverflow.com/q/52347112
tag name: vtk

http://stackoverflow.com/comment/91584064
score: 0
comment on: http://stackoverflow.com/q/52318351
type: QuestionComment
type: Comment
has text: What have you tried? startPattern.*endPattern is the general format that you want.

http://stackoverflow.com/a/52408438
has comment: http://stackoverflow.com/comment/91761219
has comment: http://stackoverflow.com/comment/91761490
answers question: http://stackoverflow.com/q/52407474
score: 15
has comment: http://stackoverflow.com/comment/91761602
type: Answer
upvote count: 15
has comment: http://stackoverflow.com/comment/91762701
downvote count: 0
has comment: http://stackoverflow.com/comment/91762371
has body: The simplest solution would be creating a hash table for each line in the file - storing 16M hashes in your working memory shouldn't be a problem (depends on the hash size, tho) - then you can iterate over your file again and make sure that you write down only one occurrence of each hash. You don't even need to parse your CSV nor you need Pandas. import hashlib with open("input.csv", "r") as f_in, \ open("output.csv", "w") as f_out: seen = set() # a set to hold our 'visited' lines for line in f_in: # iterate over the input file line by line line_hash = hashlib.md5(line.encode()).digest() # hash the value if line_hash not in seen: # we're seeing this line for the first time seen.add(line_hash) # add it to the hash table f_out.write(line) # write the line to the output This uses MD5 as a hash so it would take about 16B + set overhead per line, but that's still far less than storing everything in the memory - you can expect ~500MB of memory usage for a 16M lines CSV file.
has comment: http://stackoverflow.com/comment/91761688
has comment: http://stackoverflow.com/comment/91761088
has comment: http://stackoverflow.com/comment/91761318

http://stackoverflow.com/q/52275703
has title: pickle.PicklingError: Can't pickle <function func at 0x02B3C1B0>: it's not found as __main__.func
has answer: http://stackoverflow.com/a/52275745
type: Question
has body: test.py and main.py is in the same folder, and I execute the main.py, the Interpreter report the following error. Python environment:python2.7.15 how to fix this issue? Google told me that this issue is fixed in python3.4, but I want to use this style in python 2.7, how to do it test.py from multiprocessing import Process, Queue def interaction(q): print '*'*50 q.put('-'*50) q = Queue() p = Process(target=interaction, args=(q,)) p.start() p.join() print q.get() main.py if __name__ == '__main__': execfile('test.py') Error: Traceback (most recent call last): File "C:\sync360\code\python\oobe_test\multiprocessing_test\demorund\main.py", line 3, in &lt;module&gt; execfile('test.py') File "test.py", line 13, in &lt;module&gt; main() File "test.py", line 10, in main p.start() File "C:\Python27\lib\multiprocessing\process.py", line 130, in start self._popen = Popen(self) File "C:\Python27\lib\multiprocessing\forking.py", line 277, in __init__ dump(process_obj, to_child, HIGHEST_PROTOCOL) File "C:\Python27\lib\multiprocessing\forking.py", line 199, in dump ForkingPickler(file, protocol).dump(obj) File "C:\Python27\lib\pickle.py", line 224, in dump self.save(obj) File "C:\Python27\lib\pickle.py", line 331, in save self.save_reduce(obj=obj, *rv) File "C:\Python27\lib\pickle.py", line 425, in save_reduce save(state) File "C:\Python27\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python27\lib\pickle.py", line 655, in save_dict self._batch_setitems(obj.iteritems()) File "C:\Python27\lib\pickle.py", line 687, in _batch_setitems save(v) File "C:\Python27\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python27\lib\pickle.py", line 754, in save_global (obj, module, name)) pickle.PicklingError: Can't pickle &lt;function func at 0x02B3C1B0&gt;: it's not found as __main__.func Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Python27\lib\multi…
tagged with: python-multiprocessing
tagged with: multiprocessing
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91498967
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91519581
tagged with: pickle
tagged with: python
linked to: http://stackoverflow.com/q/8804830

http://stackoverflow.com/a/52366977
accepted answer of: http://stackoverflow.com/q/52366922
type: Answer
answers question: http://stackoverflow.com/q/52366922
score: 2
downvote count: 0
has body: Just use another for loop looping over the sublists in your list comprehension. Here for j in x[::-1] will loop over the elements of each sublists and 1-j will give you what you want. A = [[1,1,0],[1,0,1],[0,0,0]] A = [[1-j for j in x[::-1]] for x in A] print (A) Output [[1, 0, 0], [0, 1, 0], [1, 1, 1]]
upvote count: 2
has comment: http://stackoverflow.com/comment/91678519
type: AcceptedAnswer

http://stackoverflow.com/comment/91725453
comment on: http://stackoverflow.com/q/52390253
score: 2
has text: df.val.value_counts().reset_index()
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52319772
upvote count: 2
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/52319816
has title: Python Pandas Cumulative Multiplication
score: 2
downvote count: 0
has body: I created a small dataframe and I want to multiply 0.5 to the previous row and so on. In: 1 2 3 4 Out: 1 0.5 0.25 0.125 I tried the following but does not work the right way. It is not cumulative and let's say perpetual. x = pd.DataFrame([1, 2, 3, 4]) y = np.zeros(x.shape) y[0] = 1 yd = pd.DataFrame(y) k = yd.shift(1) * 0.5 print (k) Any idea? Thank you 2nd more complexed question based on previous issue. data['y'] = np.where((data['a']&lt;50) &amp; (data['b']&gt;0), data['initial'], pd.Series(0.99, data['y'].index).cumprod() / 0.99) I tried this code but does not work. If the premises are true then call the 'initial' otherwise proceed to the cumulative multiplication.
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/52319816
tagged with: pandas
type: AnsweredQuestion
favorite count: 0
type: Question

http://stackoverflow.com/comment/91536726
type: QuestionComment
comment on: http://stackoverflow.com/q/52294179
score: 0
type: Comment
has text: @tda did you even look at the output he provided? That is clearly not what he wants.

http://stackoverflow.com/q/52276973
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/91502077
has comment: http://stackoverflow.com/comment/91501855
has comment: http://stackoverflow.com/comment/91501777
has answer: http://stackoverflow.com/a/52277151
has comment: http://stackoverflow.com/comment/91502023
tagged with: pandas
downvote count: 0
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91531952
favorite count: 0
type: Question
has title: How to read columns of .txt data with pandas and feed to TF
tagged with: python
has body: I have a file birth_life_data.txt with the format as: Country fertiliy_rate Life_span India 5.7 52 USA 10.2 70 ... ... I want to store the fertiliy_rate data in the variable X, and life_span similarly in Y as 1-d arrays, to fed as training data in my TF graph. How do i use pandas to parse this data and store it in the form of a python array?
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/91636224
type: AnswerComment
score: 0
type: Comment
has text: So do you need a dynamic log level (`CRITICAL`)? If so, how is it determined? You can then input whichever message you want into the `log()` call. If the message is built in multiple steps, you may have to save the message in a string first and pass that one to `log()` when it's complete.
comment on: http://stackoverflow.com/a/52344991

http://stackoverflow.com/comment/91675377
comment on: http://stackoverflow.com/q/52357812
type: Comment
has text: @today: I added clarification.
score: 0
type: QuestionComment

http://stackoverflow.com/q/52304067
has comment: http://stackoverflow.com/comment/91555820
has body: I am writing a code where I calculate an exponential distribution from data points. When running the code, the exponential resulted in arrays of zero. To avoid overflow, I took the log of the exponential. After taking the log, these are the values I get: LL = [-2.206e+007 -5.209e+037 -1.525e+023 -2.761e+075 -5.577e+015 -4.774e+021 -3.420e+030 -8.149e+035 -1.320e+023 -8.438e+065] I then subtract the Maximum value from the array to further help avoid overflow. However, when I take the exponent again afterwards all of my values are zero except for the maximum value which is equal to 1. I think it is because the values are so large that subtracting the maximum value doesn't make a difference. Is there a way to further avoid overflow in my calculations after taking the log and subtracting the maximum logged value before taking the exponent again?
favorite count: 0
tagged with: overflow
answer count: 0
has comment: http://stackoverflow.com/comment/91555767
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Avoid Overflow from Exponential With Very large negative numbers python
score: 1
type: Question
tagged with: exponent
has comment: http://stackoverflow.com/comment/91555707
downvote count: 0

global
type: Tag
tags question: http://stackoverflow.com/q/52289877
tag name: global
tags question: http://stackoverflow.com/q/52310792
tags question: http://stackoverflow.com/q/52274533

http://stackoverflow.com/q/52308164
upvote count: 4
possible better answer: http://stackoverflow.com/a/52318553
has answer: http://stackoverflow.com/a/52318553
type: AnsweredQuestion
tagged with: user-interface
tagged with: wxpython
downvote count: 0
has title: How to a thread a wxpython progress bar GUI?
has answer: http://stackoverflow.com/a/52309299
favorite count: 0
type: Question
has body: I am trying to figure out how to add a progress bar to a GUI Installer I am making. The problem is actually making the progress bar work. I have it implemented but it freezes the entire program half way though. # Import Libraries import requests, os, sys, zipfile, shutil, subprocess, wx, urllib, time from threading import * # Define variables url = "Enter any dropbox link .zip file here" r = requests.get(url, stream = True) # Button definitions ID_START = wx.NewId() # Define notification event for thread completion EVT_RESULT_ID = wx.NewId() # Checks for old files def Check(): if os.path.exists("Folder"): print('\n\nRemoving old files...') subprocess.check_call(('attrib -R ' + 'Folder' + '\\* /S').split()) shutil.rmtree('Folder') print('\nRemoved old files.') else: pass # Downloads new file def Download(): print('\n\nDownloading:') urllib.request.urlretrieve(url, 'temp.zip') print('\nDownload Complete.') # Extracts new file def Extract(): print('\n\nExtracting...') zip_ref = zipfile.ZipFile("temp.zip", 'r') zip_ref.extractall("Folder") zip_ref.close() print('\nExtraction Complete') # Deletes the .zip file but leave the folder def Clean(): print('\n\nCleaning up...') os.remove("temp.zip") print('\nDone!') # Thread class that executes processing class WorkerThread(Thread): """Worker Thread Class.""" def __init__(self, notify_window): """Init Worker Thread Class.""" Thread.__init__(self) self._notify_window = notify_window # This starts the thread running on creation. self.start() # This is what runs on a separate thread when you click the download button def run(self): """Run Worker Thread.""" # This is the code executing in the new thread. Check() Download() Extract() Clean() # GUI Frame class that spins off the worker thread class MainFrame(wx.Frame): """Class MainFrame.""" def __init__(self, parent, id): """Create the MainFrame.""" wx.Frame.__init__(self, parent, id, 'RFMP GUInstaller', style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER) self.SetSize(400, 350) wx.Butt…
tagged with: python
tagged with: python-3.x
score: 4
tagged with: multithreading
accepted answer: http://stackoverflow.com/a/52309299
answer count: 2

http://stackoverflow.com/a/52283490
has comment: http://stackoverflow.com/comment/91561642
has comment: http://stackoverflow.com/comment/91532631
upvote count: 11
accepted answer of: http://stackoverflow.com/q/52277083
answers question: http://stackoverflow.com/q/52277083
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/110325426
has comment: http://stackoverflow.com/comment/91518903
has body: Saving torch.save({'state_dict': model.state_dict()}, 'checkpoint.pth.tar') Loading model = describe_model() checkpoint = torch.load('checkpoint.pth.tar') model.load_state_dict(checkpoint['state_dict'])
has comment: http://stackoverflow.com/comment/91568197
type: Answer
score: 11
downvote count: 0
has comment: http://stackoverflow.com/comment/95406937

http://stackoverflow.com/q/52415096
answer count: 2
tagged with: azure
has answer: http://stackoverflow.com/a/68371125
accepted answer: http://stackoverflow.com/a/52417826
has comment: http://stackoverflow.com/comment/91774027
has comment: http://stackoverflow.com/comment/91774051
tagged with: python
has answer: http://stackoverflow.com/a/52417826
has title: Maximum Recursion Depth Exceeded: Python Azure ServicePrincipalCredentials
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91774077
possible better answer: http://stackoverflow.com/a/68371125
type: Question
has comment: http://stackoverflow.com/comment/91774159
has body: I am calling a new object to manage an Azure Resource and using the Azure python packages. While calling it, i get a maximum depth exceeded error however if I step through the code in a python shell I don't get this issue. Below is the init method class WindowsDeployer(object): def __init__(self, params): try: print("executes class init") self.subscription_id = '{SUBSCRIPTION-ID}' self.vmName = params["vmName"] self.location = params["location"] self.resource_group = "{}-rg".format(self.vmName) print("sets variables") # Error is in the below snippet, while calling ServicePrincipalCredentials self.credentials = ServicePrincipalCredentials( client_id='{CLIENT-ID}', secret='{SECRET}', tenant='{TENANT-ID}' ) # Does not reach here... print("creates a credential") self.client = ResourceManagementClient(self.credentials, self.subscription_id) Instead, it exits with the following message: maximum recursion depth exceeded I have tried to increase the recursion limit to 10000 and that has not solved the issue. Pip freeze: azure==4.0.0 azure-common==1.1.4 azure-mgmt==4.0.0 Traceback: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise raise value File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/fla…
tagged with: flask
tagged with: class
has comment: http://stackoverflow.com/comment/91774122
score: 0

http://stackoverflow.com/q/52409827
type: Question
tagged with: encoding
downvote count: 0
has comment: http://stackoverflow.com/comment/91764183
has comment: http://stackoverflow.com/comment/91763747
answer count: 1
has body: This is driving me nuts. I have a main python 3 (3.5.2) driver/program that I use subprocess and popen with to spawn additional python 3 processes that I communicate with using rpyc. This has been working well, especially in python 2. I've successfully converted to python 3 and have verified that all of these processes spawn successfully if run from a terminal. To launch them from my driver, it looks like this. cmd_one = "/path/to/.virtualenv/venv_one/bin/python file_a.py" cmd_two = "/path/to/.virtualenv/venv_two/bin/python file_b.py" s_one = subprocess.Popen(cmd_one.split(), stdout=logfile, stderr=logfile) s_two = subprocess.Popen(cmd_two.split(), stdtou=logfile, stderr=logfile) This worked great in Python 2.7. As I upgrade to Python 3, however, I'm seeing something weird with default encoding that I can't figure. For cmd_one, it works great-- if I do a import locale print(locale.getpreferredencoding()) it returns UTF-8 like I'd expect. However, for cmd_two, I am getting ANSI_X3.4-1968 for seemingly no reason, and it's throwing a boatload of unicodedecode errors as a result. Like I said, when spawned in the terminal both cmd_one and cmd_two work great and use the proper default encoding. I've searched extensively but this seems to be a special case. I don't want to force the default encoding because I feel like that is masking some other issue. Is there something in the file_b.py and its constituents that is somehow setting the encoding to ANSII when it doesn't see that it's run in the terminal? file_b.py is part of a large Tensorflow project, and there are about 8 files it draw upon but I've looked in all of them but can't find anything. This is on ubuntu 16.04 and the default python 3 is 3.5.2, and as far as I know, there's no way to pass encoding='utf-8' with Popen. Any suggestions on what the heck is going on? Thanks.
tagged with: utf-8
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52410768
tagged with: subprocess
type: UnansweredQuestion
has title: opening another python 3 process from subprocess.Popen is setting locale default encoding to ANSI_X3.4-1968 but only in certain instances
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91763451
score: 1
has comment: http://stackoverflow.com/comment/91763947
has comment: http://stackoverflow.com/comment/91764206

http://stackoverflow.com/a/52376058
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52375963
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/91698018
has body: With MIDI, there are 16 channels. Each channel can be on one program/patch at a given time. When you call program_change, you're changing the patch for that default channel. You should send program_change for another channel, and then send MIDI notes to that other channel as well.

http://stackoverflow.com/q/52376476
has comment: http://stackoverflow.com/comment/91713993
tagged with: python
tagged with: python-imaging-library
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/91724802
score: 4
has body: I'm using pillow and working with pretty large images (at least 10500 x 10500 px), which in turn uses up quite a lot of memory. I was wondering if there was a way to lower it and tried using a compressed image to load (which would be ~400kb instead of 420mb), instead of directly creating a new one.. but the memory usage is the same: Line # Mem usage Increment Line Contents ================================================ 151 35.969 MiB 0.742 MiB base = Image.open("C:/Users/Nick/Desktop/transparent.png") 152 456.992 MiB 421.023 MiB base.load() 155 877.641 MiB 420.648 MiB base_hallway = Image.new("RGBA", (map_width_px, map_height_px)) I also tried using a jpg or Image.new() with RGB only for the second image, but ditching the alpha channel didn't work either. Line # Mem usage Increment Line Contents ================================================ 151 36.309 MiB 0.766 MiB base = Image.open("C:/Users/Nick/Desktop/transparent.png") 152 457.359 MiB 421.051 MiB base.load() 156 457.367 MiB 0.008 MiB base_hallway = Image.open("C:/Users/Nick/Desktop/blackjpg.jpg") 157 878.312 MiB 420.945 MiB base_hallway.load() Mainly the operation being run on the base images is pasting other images on top of them in different positions. The rooms or hallways also have operations on them, but use almost no memory in comparison, such as picking the proper position to paste depending on the previous room or hallway, rotating if necessary, etc. But since it requires dozens or even hundreds of items pasted on top, I can't close the base images after every iteration (so only base OR base_hallway is open at any one time). I tried to open the base and base_hallway images only when needed, which requires a lot of save and close operations as well. That ended up increasing the time it takes for the code to run tenfold.. Simplified: room = Image.open(open_room) if next_tile == "room": base.paste(room, box=(rand_width_position, rand_height_position), mask=room) elif next_tile == "hallway" or next_tile…
has answer: http://stackoverflow.com/a/52390907
answer count: 1
downvote count: 0
has title: Optimizing memory usage with large images in Python (Pillow)
favorite count: 0
has comment: http://stackoverflow.com/comment/124133892
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91723837
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/51667881

http://stackoverflow.com/a/52397846
has body: First add (5, 5.5): 'D0', (15, 5.5): 'D1' to valueDict: valueDict = {(0, 0): 'P0', (20, 0): 'P1', (20, 11.36): 'P2', (0, 11.36): 'P3', (5, 5.5): 'D0', (15, 5.5): 'D1'} And change the 11.6 for 11.36 in values: values = [[0, 0, 20, 0, 15, 5.5, 5, 5.5], [20, 0, 20, 11.36, 15, 5.5], [20, 11.36, 0, 11.36, 5, 5.5, 15, 5.5], [0, 11.36, 0, 0, 5, 5.5]] First we go through it and we turn it into tuples: tuples_values = [] for v in values: tuples_values.append([(v[i], v[i+1]) for i in range(0, len(v), 2)]) Then we go through it and replace it with the values of the dict: out = [] for v in tuples_values: out.append([valueDict[tuple_value] for tuple_value in v]) out: [['P0', 'P1', 'D1', 'D0'], ['P1', 'P2', 'D1'], ['P2', 'P3', 'D0', 'D1'], ['P3', 'P0', 'D0']]
downvote count: 0
answers question: http://stackoverflow.com/q/52397709
score: 2
type: Answer
upvote count: 2

http://stackoverflow.com/a/52313235
answers question: http://stackoverflow.com/q/52310791
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91578617
has body: while not False: print('rainy rainy rain rain') key = keypress() if key == "e": #e: exit exit() if key == "w": # w: wait waiting = True while waiting == True: print("waiting waiting waiting") if keypress() == "w": waiting = False ...this little change, solved the problem. I think calling the keypress() [and therefore also the msvcrt.getch() function] takes 'a lot' of time what prevents another keyboard hit from beeing recognized. But why? Shouldn't the hit of key beeing buffered!? And therefore the elapsed time shouldn't matter!?

http://stackoverflow.com/comment/91610285
score: 0
comment on: http://stackoverflow.com/a/52331743
type: Comment
type: AnswerComment
has text: Oops, sorry, had the wrong `values`. This does indeed work - nice!

http://stackoverflow.com/q/52356414
has body: I have the following inheritance structure of my Django models: Transaction SimpleTransaction SubscriptionTransaction Item SimpleItem SubscriptionItem The model SimpleTransaction refers to the model SimpleItem and the class SubscriptionTransaction refers to the model SubscriptionItem. The most obvious way to do this is to define item field in Transaction: class Transaction(models.Model): # ... item = models.ForeignKey('Item') # ... But I would like t.item to refer to SimpleItem or SubscriptionItem (not the base class Item as in the above code) dependently on whether t is SimpleTransaction or SubscriptionTransaction. What are the ways to do this in Django? Or maybe referring to a derived class (SimpleItem or SubscriptionItem) instead of Item may somehow impact performance badly, as it would request to read SimpleItem or SubscriptionItem even when just Item fields are needed? and so better to refer to the base class and not to invent a question like this? However having references to a particular Item-derived class (not just Item base class) from either SimpleTransaction or SubscriptionTransaction benefits referential integrity. So should I do this to improve the DB "stability"?
tagged with: python
has title: Polymorphic (derived model referred) model inheritance in Django
type: AnsweredQuestion
type: Question
tagged with: django-models
has answer: http://stackoverflow.com/a/52357004
accepted answer: http://stackoverflow.com/a/52357004
score: 0
answer count: 1
tagged with: django

http://stackoverflow.com/q/52279355
type: Question
has comment: http://stackoverflow.com/comment/91541251
has title: Trying to split a Keras input layer, processing both sub-tensors differently and connecting them latter into a LSTM layer
tagged with: neural-network
tagged with: deep-learning
downvote count: 0
tagged with: keras
linked to: http://stackoverflow.com/q/71886992
favorite count: 0
has comment: http://stackoverflow.com/comment/127727808
has comment: http://stackoverflow.com/comment/91510968
type: UnansweredQuestion
tagged with: python
has body: So, one input of my neural network in Keras is an array of 10 elements. The question is, the first 9 elements are numbers, while the last one is a matrix that will be concatenated. What I'm trying to do is: Receive the input Split the input, separating [0:8] and [9] entries Sending [9] entry into a series of convolution layers Ending it into a LSTM layer, which will receive the [0:8] entries directly and also the outputs of the convolution layers I understand that will have to use an input layer: shape = (10,) input = Input(shape=shape , name='input', dtype='float32') I also already have the convolution layers: conv = Convolution1D(nb_filter=nb_filter, filter_length=filter_kernels[0], border_mode='valid', activation='relu', input_shape=(maxlen, vocab_size), kernel_initializer=initializer)(text_input) conv = MaxPooling1D(pool_length=3)(conv) conv1 = Convolution1D(nb_filter=nb_filter, filter_length=filter_kernels[1], border_mode='valid', activation='relu', kernel_initializer=initializer)(conv) conv1 = MaxPooling1D(pool_length=3)(conv1) conv2 = Convolution1D(nb_filter=nb_filter, filter_length=filter_kernels[2], border_mode='valid', activation='relu', kernel_initializer=initializer)(conv1) conv3 = Convolution1D(nb_filter=nb_filter, filter_length=filter_kernels[3], border_mode='valid', activation='relu', kernel_initializer=initializer)(conv2) conv4 = Convolution1D(nb_filter=nb_filter, filter_length=filter_kernels[4], border_mode='valid', activation='relu', kernel_initializer=initializer)(conv3) conv5 = Convolution1D(nb_filter=nb_filter, filter_length=filter_kernels[5], border_mode='valid', activation='relu', kernel_initializer=initializer)(conv4) conv5 = MaxPooling1D(pool_length=3)(conv5) conv5 = Flatten()(conv5) conv5 = Dropout(0.5)(Dense(dense_outputs, activation='relu', kernel_initializer=initializer)(conv5)) I also know that I will have to concatenate them latter and feed into a LSTM layer: concat_lstm2 = Concatenate()([first, second]) Dropout(0.5)(LSTM(lstm_size, re…
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/91540827
upvote count: 1

http://stackoverflow.com/q/52312950
downvote count: 1
type: AnsweredQuestion
tagged with: list
score: -1
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/52313382
answer count: 2
accepted answer: http://stackoverflow.com/a/52313149
has comment: http://stackoverflow.com/comment/91574093
has answer: http://stackoverflow.com/a/52313382
upvote count: 0
favorite count: 0
has title: Replicate a numpy list m times
has comment: http://stackoverflow.com/comment/91573018
has comment: http://stackoverflow.com/comment/91572950
has comment: http://stackoverflow.com/comment/102990194
has body: I am trying to pair two different databases of images that I have in python (lets say database A and database B, they are stored in list of numpy arrays). For the database A I have x images (for example 6) and for database B y images (for example 78). Each image from database A is correspond to 78/6 = 13 images from database B and the order is the same. Thus, A B -------------- 1 [1, 13] 2 [14, 26] 3 [27, 39] 4 [38, 52] 5 [51, 65] 6 [66, 78] What I want to do is to replicate each image from database A 13 times in order to have the same number of images with database B. The problem is that those amount of numbers are not fixed (x and y). Therefore, len1 = len(database_A) len2 = len(database_B) m = round(len2/len1) How can I return a replicate m times the elements of the database list A (m times the image 1 then m times the image 2 etc.). EDIT: Sometimes the division produces some module. How can I handle that module. There is the case i have for database A 6 images while for database B 68 and that produce mod = 2. I need in that case to store only 66 images from both databases.
has answer: http://stackoverflow.com/a/52313149
tagged with: python

http://stackoverflow.com/comment/91646211
has text: Please include the complete error message. It is impossible to tell which statement generated it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52350448
score: 1

http://stackoverflow.com/q/52342543
type: Question
has answer: http://stackoverflow.com/a/52342703
has body: I want to extract value of window.FEED__INITIAL__STATE Piece of code How can I do it?
score: 0
answer count: 2
tagged with: beautifulsoup
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91631634
type: UnansweredQuestion
tagged with: python
has title: Extract content of in Python with BeautifulSoup
has answer: http://stackoverflow.com/a/52344119

http://stackoverflow.com/comment/91599123
has text: I am able to get the image url in `scrapy shell` using `response.xpath('.//div[@class="offer-image-box"]/img/@src').extract_first()`. Which is `'//sc01.alicdn.com/kf/HTB1jvmMXmtYBeNjSspkq6zU8VXa3/Closed-Cell-Expanded-Perlite-Bulk-Expanded-Perlite.jpg_300x300.jpg'` .
comment on: http://stackoverflow.com/q/52325790
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52337888
tagged with: selenium-webdriver
score: 2
possible better answer: http://stackoverflow.com/a/52339239
tagged with: selenium
has body: My issue is that I need all the data within the grid containing subdomains from the website https://applipedia.paloaltonetworks.com - (data containing NAME , CATEGORY, SUBCATEGORY, RISK, TECHNOLOGY). What I require is [Example: In line number 5: 2ch has 2 subdomains |_2ch-base and 2ch-posting. Like this I only want to get the list of all apps having subdomains] Right not whenever I have tried adding anything in the line: table =wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'tbody#bodyScrollingTable tr'))) I am getting a timeout error. Below is the script I have as of now which fetches all the data from the grid but I need only the apps and it's containing subdomains.[Example 2ch, 2ch-base, 2ch-posting]. I have found out a pattern through inspect element which is all apps that doesn't have subdomains have ( ) or we can go by the () field which is common for all apps having subdomains. Any help on solving this problem will be much appreciated. from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome(executable_path = r'/Users/am/Downloads/chromedriver') driver.maximize_window() driver.get("https://applipedia.paloaltonetworks.com/") wait = WebDriverWait(driver,30) table =wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'tbody#bodyScrollingTable tr'))) for tab in table: print(tab.text)
tagged with: webdriver
has answer: http://stackoverflow.com/a/52339239
type: AnsweredQuestion
has title: Scraping javascript data within a grid of a webpage using selenium and python
accepted answer: http://stackoverflow.com/a/52338398
type: Question
upvote count: 2
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52338398
tagged with: webdriverwait
tagged with: python

http://stackoverflow.com/comment/91678236
type: QuestionComment
score: 0
has text: again, I don't know sympy, but I suppose you should assign the result of `g.subs(a,a)` to another variable.
comment on: http://stackoverflow.com/q/52366855
type: Comment

http://stackoverflow.com/comment/91561131
comment on: http://stackoverflow.com/a/52283180
type: AnswerComment
has text: Thank It is solved.While exporting the paramter should be encoded_image_tensor.I changed its working perfectly thanks
type: Comment
score: 1

http://stackoverflow.com/comment/91547852
has text: Yeah, I'll edit my response to show some cleaner code
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52300075
type: Comment

http://stackoverflow.com/a/52337018
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91621324
accepted answer of: http://stackoverflow.com/q/52336707
type: Answer
has comment: http://stackoverflow.com/comment/91621452
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91621382
has comment: http://stackoverflow.com/comment/91621384
has body: Now reading the comments, I think I understand your problem. This piece of code: cookiemon = User(username='cookiemon', email_address='wellhithere@gmail.com', phone='416-555-1212', password='password' ) session.add(cookiemon) session.commit() Creates a new user and stores it in the database. You can't run it twice, because it is already stored in the database. You can only execute that once, or you get the error. Now later, if you want to use the same user, you can't create it again. If you still have the same cookiemon variable in memory, you can just use it, but if you don't, you have to fetch the existing user from the database instead of creating a new one: cookiemon = session.query(User).filter(User.username=='cookiemon').one() You could combine both in a single execution: # try to get the user from the databae cookiemon = session.query(User).filter(User.username=='cookiemon').first() if cookiemon is None: # not found, create new one: cookiemon = User( username='cookiemon', email_address='wellhithere@gmail.com', phone='416-555-1212', password='password' ) session.add(cookiemon) session.commit()
answers question: http://stackoverflow.com/q/52336707

http://stackoverflow.com/comment/91797041
score: 0
has text: @EugeneYarmash If it helps, I am using Anaconda
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52426694

http://stackoverflow.com/q/52389622
linked to: http://stackoverflow.com/q/52387273
has comment: http://stackoverflow.com/comment/91724426
tagged with: pandas
has comment: http://stackoverflow.com/comment/91724743
upvote count: 0
answer count: 1
favorite count: 0
has body: I am trying to figure out since hours now how to handle the case that a value occurs only once in a column of my data frame. In this case i want to do any action. Example: df = pd.DataFrame([(1,1,1,2,3,3],columns=['id'] for i, g in df.groupby('id'): df_counter=df.loc[df['id'] == i] if(df_counter.count()&lt;=1): #...do sth else: #anything else So in case i = 2, I want to do sth. as it only occurs once in the column id. Otherwise I do sth else. My approach does not work. Any idea of how to do it?
has comment: http://stackoverflow.com/comment/91724384
score: -3
tagged with: count
tagged with: python
has comment: http://stackoverflow.com/comment/91724684
has title: Do sth. if occurrence of value in a column equals 1 in a panda data frame
type: AnsweredQuestion
downvote count: 3
tagged with: loops
has answer: http://stackoverflow.com/a/52390361
type: Question
accepted answer: http://stackoverflow.com/a/52390361

http://stackoverflow.com/q/52384648
has comment: http://stackoverflow.com/comment/91713326
favorite count: 0
has comment: http://stackoverflow.com/comment/91713351
answer count: 5
has title: Python - For Loop - Print only if the above line is equal
tagged with: python
has answer: http://stackoverflow.com/a/52384776
type: AnsweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/52384766
has answer: http://stackoverflow.com/a/52384709
type: Question
tagged with: for-loop
upvote count: 0
score: -2
linked to: http://stackoverflow.com/q/38708692
has body: I've the following code: characters = ['a', 'b', 'b', 'c','d', 'b'] for i in characters: if i[0] == i[-1]: print(i) Basically I only want to extract the characters that are equal from the line above. For example, in my case I only want to extract the b from 1 and 2 position. How can I do that? Thanks!
has comment: http://stackoverflow.com/comment/91713361
has answer: http://stackoverflow.com/a/52384963
accepted answer: http://stackoverflow.com/a/52384709
possible better answer: http://stackoverflow.com/a/52384760
has answer: http://stackoverflow.com/a/52384760

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

http://stackoverflow.com/a/52813234
has body: Not an ideal solution, but you could try using MPXJ. MPXJ itself is a Java library, but assuming you can launch a separate process from your Python code you can get it to convert the XER file to JSON which should be easier to consume (this is the approach used by the MPXJ Ruby gem, it's just wrapping the Java code performing the conversion, then reading the resulting JSON). You should also find the structure of the schedule data in the JSON generated by MPXJ easier to work with than the contents of the XER file, although you won't have access to every attribute in the original XER file. The ruby version of this process can be found here. To summarise, the command line will look something like this: java -cp &lt;classpath&gt; net.sf.mpxj.sample.MpxjConvert your-file.xer your-file.json You'll just need to set supply the &lt;classpath&gt; to tell the JVM where MPXJ JAR and its dependencies are.
score: 0
answers question: http://stackoverflow.com/q/52381302
type: Answer

http://stackoverflow.com/a/52386892
score: 3
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91718249
type: Answer
has comment: http://stackoverflow.com/comment/91718378
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52386747
has body: Does checking whether there are any axes in the figure with fig.get_axes() work for your purposes? fig = plt.figure() if fig.get_axes(): # Do stuff when the figure isn't empty.
answers question: http://stackoverflow.com/q/52386747

http://stackoverflow.com/q/52359147
has comment: http://stackoverflow.com/comment/130668274
tagged with: python
has answer: http://stackoverflow.com/a/52359482
downvote count: 0
has body: I'm having trouble specifying constraints using basinhopping with method='COBYLA'. Here is a test case where things go wrong. Essentially, the constraints are ignored and there are function trials outside the specified range. I specify a simple quadratic with minimum at [0,0], searching for -3&lt;x[0], but as you can see from the output, there are lots of searches outside that range (I increased the stepsize to make it obvious) import numpy as np from scipy.optimize import basinhopping def f(x): if x[0]&lt;-3 : print('outside range ',x[0]) return x[0]**2+x[1]**2 cons = [{'type':'ineq','fun': lambda x: x[0]+3}] kwargs = {'method':'COBYLA','constraints':cons} ret=basinhopping(f, [5,1],T=1,stepsize=1000,niter=1,minimizer_kwargs=kwargs) print(ret) runfile('py/cobyla_test', wdir='/py', post_mortem=True) outside range -446.14581341127945 outside range -445.14581341127945 outside range -445.14581341127945 outside range -444.14581341127945 [etc... lots of output deleted] [-4.81217825e-05 -5.23242054e-05] 5.0535284302996725e-09
tagged with: scipy
type: Question
score: 3
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/91689777
tagged with: minimization
has title: Constraints seem to be ignored using basinhopping with COBYLA method
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52298926
tagged with: memory-management
type: Question
score: 0
tagged with: python
has title: How to perform operations synchronously for memory management?
has comment: http://stackoverflow.com/comment/91545946
has comment: http://stackoverflow.com/comment/91545751
tagged with: memory
has body: I have an application that keeps on crashing due to what I believe is too much data in a list. I am calling xml data from an api and appending the data into a list. I have to make roughly ~300K api calls which I think is causing my application to crash because when I am appending into the list, there is too much data. Below is code to call api and save results into list. lst1 is a list of ids that I pass into the api. I have to take into account that if the http request times out or I can build a mechanism to clear the appended list of data, that I can restart the requests from the ID I left off at from lst1 which is passed into the api url. import requests import pandas as pd import xml.etree.ElementTree as ET from bs4 import BeautifulSoup import time from concurrent import futures lst1=[1,2,3] lst =[] for i in lst1: url = 'urlId={}'.format(i) while True: try: xml_data1 = requests.get(url).text print(xml_data1) break except requests.exceptions.RequestException as e: print(e) lst.append(xml_data1) I am thinking that if I can apply my below function to unpack the xml into a dataframe and perform the needed dataframe manipulation, while clearing the list of appended data lst that it could free memory. IF this is not the case, I am open to any suggestions to allowing code or application to not crash with what I believe is too much xml data in the list: def create_dataframe(xml): soup = BeautifulSoup(xml, "xml") # Get Attributes from all nodes attrs = [] for elm in soup(): # soup() is equivalent to soup.find_all() attrs.append(elm.attrs) # Since you want the data in a dataframe, it makes sense for each field to be a new row consisting of all the other node attributes fields_attribute_list = [x for x in attrs if 'Id' in x.keys()] other_attribute_list = [x for x in attrs if 'Id' not in x.keys() and x != {}] # Make a single dictionary with the attributes of all nodes except for the `Field` nodes. attribute_dict = {} for d in other_attribute_list: for k, v in d.items(): att…
has comment: http://stackoverflow.com/comment/91554040
has comment: http://stackoverflow.com/comment/91554382
tagged with: list-manipulation
answer count: 0
type: UnansweredQuestion
tagged with: python-3.x

http://stackoverflow.com/q/52298580
has answer: http://stackoverflow.com/a/52298684
tagged with: python
tagged with: lcm
has title: How to loop over modulus?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52298617
has comment: http://stackoverflow.com/comment/91545053
type: Question
score: 0
has answer: http://stackoverflow.com/a/52298814
has body: newbie here. I've been trying to find the least common multiple of the numbers 1 thru 10. My code so far def smallest_multiple(): a = 0 while True: a += 1 if a%1 == 0 and a%2 == 0 and a%3 == 0 and a%4 == 0 and a%5 == 0 and a%6 == 0 and a%7 == 0 and a%8 == 0 and a%9 == 0 and a%10 == 0: return a print(smallest_multiple()) My result is 2520, which seems to be correct. It is the smallest number that is divisible by the numbers 1 thru 10 without remainder. But is there a way to make the 5 line shorter (not that much modulus) by iterating over them? I've tried something like this def smallest_multiple(): a = 0 while True: a += 1 for i in range(1, 11): if a % i == 0: return a print(smallest_multiple()) But that returns just 1, not 2520. Is there a way to make if a%1 == 0 and a%2 == 0 and a%3 == 0 and a%4 == 0 and a%5 == 0 and a%6 == 0 and a%7 == 0 and a%8 == 0 and a%9 == 0 and a%10 == 0: shorter?
answer count: 3

http://stackoverflow.com/a/52387564
answers question: http://stackoverflow.com/q/52387297
upvote count: 3
has comment: http://stackoverflow.com/comment/91719878
has body: You've used PyModule_HEAD_INIT in your myModule definition, but that's not an identifier declared by CPython. You're probably thinking of PyModuleDef_HEAD_INIT (note the Def). As for whether you should develop under Linux instead: So far, the problems you've experienced have not been the fault of your tools. It seems unlikely that switching over would help in that respect.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91719920
has comment: http://stackoverflow.com/comment/91723759
type: Answer
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/91720189
accepted answer of: http://stackoverflow.com/q/52387297
has comment: http://stackoverflow.com/comment/91720128

http://stackoverflow.com/q/52356569
tagged with: python
score: 4
accepted answer: http://stackoverflow.com/a/52356810
upvote count: 4
has answer: http://stackoverflow.com/a/52356791
has body: I have a Python program that maintains a list of contacts and I want it to support following options through the command line: --show , takes a string argument --list , takes no argument --add , takes a string argument --number , takes an int argument --email , takes a string argument What I need is: prog [--show xyz | --list | --add xyz --number 123 --email abcd@xyz.com ] I tried to implement it using subparsers as follows: parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() subparser1 = subparsers.add_parser('1') subparser1.add_argument('--show', type=str, help="Shows the contact based on the given name provided as argument") subparser1.add_argument('--list', action='store_true', help= "Prints all the contacts") subparser2 = subparsers.add_parser('2') subparser2.add_argument('--add', type=str, help="Adds a new contact by this name",required=True) subparser2.add_argument('--number', type=int, help="The Phone Number for the new contact",required=True) subparser2.add_argument('--email', type=str, help="Email address for the new contact",required=True) The problem is that I don't to want to provide the number/name of the subparser I wanna use through the command-line. E.g: prog.py 1 --list prog.py 2 --add xyz --number 1234 --email abc@xyz.com I tried to make it work with mutually_exclusive_group but couldn't. Is there a way around this usage?
possible better answer: http://stackoverflow.com/a/52356712
downvote count: 0
has title: Argument Parser Python conditional requirement
has answer: http://stackoverflow.com/a/52356712
has comment: http://stackoverflow.com/comment/91657713
type: Question
tagged with: argparse
type: AnsweredQuestion
favorite count: 0
has answer: http://stackoverflow.com/a/52356810
answer count: 3

http://stackoverflow.com/comment/91802674
has text: Terminal is not a Python console, it is the OS terminal (looks like `cmd.exe` in your case).
type: Comment
comment on: http://stackoverflow.com/q/52429508
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91619135
comment on: http://stackoverflow.com/q/52335920
has text: @Zrax how exactly can I force it to?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91784752
type: QuestionComment
type: Comment
has text: What is the actual error, when you place a value after the 0?
score: 0
comment on: http://stackoverflow.com/q/52420831

http://stackoverflow.com/comment/91605531
type: QuestionComment
comment on: http://stackoverflow.com/q/52329341
has text: @MartijnPieters I am reading a file which has strings and they are separated by tabs. After reading the file, I split it using tab and then store as a list and thus I guess it has both single and double quotes. Is this correct way of doing.?
score: 0
type: Comment

http://stackoverflow.com/comment/91592361
has text: Glad I could help!
type: Comment
comment on: http://stackoverflow.com/a/52321058
type: AnswerComment
score: 0

http://stackoverflow.com/a/52383068
type: Answer
has comment: http://stackoverflow.com/comment/91710330
has body: you can use this script if your file is a text filename='file.text' with open(filename) as f: data = f.readlines() x=[data[0][0],data[1][0]] y=[data[0][1:],data[1][1:]]
score: 0
answers question: http://stackoverflow.com/q/52382780

http://stackoverflow.com/comment/91723443
comment on: http://stackoverflow.com/q/52388882
type: Comment
score: 0
has text: @VineethSai How do you uncover this DAG of installations? "Using setup.py": Do you mean unpack manually and run the "setup.py" that is part of the package?
type: QuestionComment

http://stackoverflow.com/comment/91627500
score: 0
comment on: http://stackoverflow.com/q/52340023
has text: numpy only supports fixed size integer up to 64 bits. I don't know if this is enough here.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52383832
type: AnsweredQuestion
tagged with: python-3.x
has title: Using axes_grid1 without manipulating subplots
linked to: http://stackoverflow.com/q/13784201
type: Question
accepted answer: http://stackoverflow.com/a/52387054
tagged with: matplotlib
score: 0
has answer: http://stackoverflow.com/a/52387054
tagged with: subplot
has body: I'd like to draw a colorbar beside one of my subplots using axes_grid1. The problem is, that the call of make_axes_locatable manipulates my subplot so that it doesn't have the same size of the other plots anymore. Here is a minimal working example of my issue. from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np import matplotlib import matplotlib.pyplot as plt fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(15,5)) _ax = ax[0,:].flatten('C') values_x = np.linspace(0, 2 * np.pi, 100) values_y = np.sin(values_x) vmax = np.amax(values_x) vmin = np.amin(values_x) s = 1 ticks_rotation = 10 ticks_num = 5 _ax = ax[0,:].flatten('C') plot_w = _ax[0].scatter(values_x, values_y, c=values_x, cmap='rainbow', vmin=vmin, vmax=vmax, s=s) plot_v = _ax[1].scatter(values_x, values_y, c=values_x, cmap='rainbow', vmin=vmin, vmax=vmax, s=s) _ax = ax[1,:].flatten('C') plot_w = _ax[0].scatter(values_x, values_y, c=values_x, cmap='rainbow', vmin=vmin, vmax=vmax, s=s) plot_v = _ax[1].scatter(values_x, values_y, c=values_x, cmap='rainbow', vmin=vmin, vmax=vmax, s=s) divider = make_axes_locatable(_ax[1]) cax = divider.append_axes('right', size='5%', pad=0.05) v_delta = (vmax - vmin)*0.1 ticks = np.linspace(vmin+v_delta,vmax-v_delta,ticks_num) cbar = fig.colorbar(plot_v, cax=cax, orientation='vertical', ticks=ticks) cbar.ax.set_yticklabels(np.around(ticks,decimals=1), rotation=ticks_rotation,rotation_mode='default') plt.show() What I want is actually all subplots of the same size with a nice color beside it. Any suggestions? Edit: I really just want to have the colorbar besides the lower right subplot, and not like this.
has comment: http://stackoverflow.com/comment/91711901
answer count: 1
duplicate of: http://stackoverflow.com/q/13784201
has comment: http://stackoverflow.com/comment/91712731
tagged with: python

http://stackoverflow.com/comment/91540625
score: 0
type: AnswerComment
type: Comment
has text: you could implement switch case, add validation for num1 and num2 etc. https://jaxenter.com/implement-switch-case-statement-python-138315.html
comment on: http://stackoverflow.com/a/52293430

http://stackoverflow.com/comment/91593931
type: Comment
has text: Search for NMS.
type: QuestionComment
comment on: http://stackoverflow.com/q/52318311
score: 0

http://stackoverflow.com/q/52382111
favorite count: 0
has comment: http://stackoverflow.com/comment/91708651
tagged with: python-3.x
tagged with: django-2.0
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Django: product variants for ecommerce
has comment: http://stackoverflow.com/comment/91708718
score: 1
upvote count: 1
type: Question
has body: I'm trying to build an ecommerce and to configure product variants and attributes. In my product variant models, I'd like to access all of the selected attributes from the related product and add a value for each product. For example, if I create a new product and chosose two attributes for the variants: color and size, I'd like to be able to create dynamically a field for each of them when creating a variant for this product. Here's what I have in my models.py file: class Product(models.Model) : name = models.CharField(max_length=120) price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='products') allow_variants = models.BooleanField(default=True) product_attributes = models.ManyToManyField("attribute") def __str__(self) : return self.name class Meta : ordering = ("name",) class Attribute(models.Model) : name = models.CharField(max_length=120) def __str__(self) : return self.name def get_all_attr_variants(self) : variants = AttributeVariant.objects.filter(attribute__name=self.name) return variants class AttributeVariant(models.Model) : name = models.CharField(max_length=120) attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) def __str__(self) : return self.name class Meta : ordering = ('name',) class ProductVariant(models.Model) : Please help me if you have any idea of how I could do it. Thanks!
tagged with: django-models
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52382247

http://stackoverflow.com/a/52422445
downvote count: 0
answers question: http://stackoverflow.com/q/52422265
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/91788078
has body: You just need to add the argument to df_pivot.rename(columns = {"CDS_STATUS":"CDS"}) that is df_pivot.rename(columns = {"CDS_STATUS":"CDS"},inplace=True)
score: 2

http://stackoverflow.com/q/52306563
tagged with: http://stackoverflow.com/tag/html
has body: My html page has a button and when I click that button I need to execute a python file. I don't need to show the python file content in browser, I only need to execute the python file by clicking the html button. When executing the python file, it will generate a json file which I need. This is my code and it's opening the python file but not showing any output. &lt;html&gt; &lt;body&gt; &lt;h1&gt; DEVELOPMENT &lt;/h1&gt; &lt;form action="phpfile.php" method="post"&gt; &lt;input type="submit" name="someAction" value="GO" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; &lt;?php $result_last_line = system("python C:/xampp/htdocs/NEW/pythonfile/identifyrooms.py"); header('Location: view.html'); exit; ?&gt; When I run my python file using editor the output console is as below. Can anyone find the error?. Thanks
tagged with: python
has title: How to execute Python scripts from HTML button
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: php
type: Question
has comment: http://stackoverflow.com/comment/91564129
has comment: http://stackoverflow.com/comment/91564549
has comment: http://stackoverflow.com/comment/91566211
score: 0
has comment: http://stackoverflow.com/comment/91564578

http://stackoverflow.com/comment/91650784
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52352847
has text: Possible duplicate of [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value)
score: 0

http://stackoverflow.com/q/52319939
type: Question
tagged with: sympy
downvote count: 0
has title: Python Sympy module NoConvergence: convergence to root failed; try n < 15 or maxsteps > 50
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52321461
score: 1
favorite count: 0
upvote count: 1
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/588004
has body: I encountered a problem when I using Sympy to solve problems Here is my code: from math import pi, hypot from sympy import solve, solveset, sqrt, Symbol one_x=-0.08 one_y=1.28 second_x=0 second_y=0 second_r=7 one_r=7.3 slopes=-16.0000000000 (maybe more trailing 0s) intercepts=0.0 x=Symbol('x') solveset(sqrt((x-second_x)**2+(slope*x+intercept-second_y)**2)+second_r-one_r-sqrt((x-one_x)**2+(slope*x+intercept-one_y)**2),x) That's only part of my code but it raises a lot of errors but instead, I replaced all of the variables with its value like x=Symbol('x') solveset(sqrt((x)**2+((-16)*x)**2)+7-7.3-sqrt((x+0.08)**2+((-16)*x-1.28)**2),x) It works nicely and i can get an output {-0.0493567429232771} I think It's because of the type of slopes(-16 compared with -16.000000), I really wanna know why an equation with float number cannot be calculated, and how I can fix it (cause I need it to be more precise so I cannot just ignore the number after the dot ) Thanks so much!
has answer: http://stackoverflow.com/a/52321461

http://stackoverflow.com/q/52372746
answer count: 3
has answer: http://stackoverflow.com/a/52372822
tagged with: string
linked to: http://stackoverflow.com/q/509211
favorite count: 0
linked to: http://stackoverflow.com/q/1876191
has body: Let´s say I have a one-word string ("Hello") and I wanted to swap the first and last letter so I´d do this: s="Hello" l=list(s) l[0],l[len(l)-1]=l[len(l)-1],l[0] print("".join(l)) But, what if I had to swap the first and last letter in every word of the string:"Hello World" , so that I would get "oellH dorlW". I was thinking using nested lists but it seems overcomplicated.
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/52372818
type: AnsweredQuestion
tagged with: list
score: 1
downvote count: 1
type: Question
has title: Swaping letters in a 2+ word string
has comment: http://stackoverflow.com/comment/91690782
has answer: http://stackoverflow.com/a/52372927
has answer: http://stackoverflow.com/a/52372818
possible better answer: http://stackoverflow.com/a/52372822

http://stackoverflow.com/q/52302196
tagged with: python-3.x
has title: How to solve ValueError: could not convert string to float in python
has answer: http://stackoverflow.com/a/52302276
tagged with: python
has comment: http://stackoverflow.com/comment/91552515
type: AnsweredQuestion
upvote count: 0
type: Question
has body: I have text file of dataset which look like this. 2.8858451e-001 -2.0294171e-002 -1.3290514e-001 -9.9527860e-001 -9.8311061e-001 When I had read this file and fit classifier on this data I get this error. ValueError: could not convert string to float: ' 2.3177399e-001 4.9371571e-003 I'm using the following code: tra_x, tra_y, tes_x, tes_y = np.array([]), np.array([]), np.array([]),np.array([]) file = open('train\X_train.txt', encoding='utf-8') tra_x = file.readlines() tra_x = [float(x).split(" ") for x in tra_x] file = open('train\y_train.txt', encoding='utf-8') tra_y = file.readlines() file = open('test\X_test.txt', encoding='utf-8') tes_x = file.readlines() file = open('test\y_test.txt', encoding='utf-8') tes_y = file.readlines()
score: -1
accepted answer: http://stackoverflow.com/a/52302276
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91552855
favorite count: 0

http://stackoverflow.com/comment/91552170
comment on: http://stackoverflow.com/q/52302017
has text: I think a more complete example would be helpful. Are you trying to generate a query for one specific product? A list of products?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91698556
type: QuestionComment
type: Comment
has text: This is a *backtracking* example, in *2D* (that I've studied in hi-school - such a problem was the very example). Note that *backtracking* finds **all** the possibilities (you can get your best from there), but it's like kind of *brute force*.
comment on: http://stackoverflow.com/q/52376886
score: 0

http://stackoverflow.com/comment/91752272
comment on: http://stackoverflow.com/q/52402622
score: 0
type: Comment
type: QuestionComment
has text: Actually, i want to get data from this web http://gls.fehd.gov.hk/fehd_lgs/jsp/search/searchMainPage.jsp?lang=en, i use fiddle to see it will call another URL when POST method call.

http://stackoverflow.com/comment/91620964
type: Comment
type: QuestionComment
has text: I'm trying to reproduce your problem, but your code is working fine here. Only thing I added is creating the 'chocolate chip' and 'peanut butter' `Cookie()` objects and adding them to the session. Can you provide the full error traceback, along with line numbers? Also please format it as code or it will be very hard to read.
comment on: http://stackoverflow.com/q/52336707
score: 0

http://stackoverflow.com/comment/116329203
type: QuestionComment
comment on: http://stackoverflow.com/q/52330887
score: 0
has text: Did you ever find a solution for this problem?
type: Comment

http://stackoverflow.com/q/52290426
tagged with: matplotlib
has answer: http://stackoverflow.com/a/52291663
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: In the following code I use axhline command to draw a horizontal line along x-axis. Now I want to draw a vertial line at the point where two lines have already crossed each other. I can not use axvline because I don't know the value of intersection. In case of axhline I draw that line at 50 percent probability value. x=[1, 1.5, 2, 5, 5.5, 6 ] y=[1, 1, 0.89189189, 0.01086957, 0.01190476, 0] fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x,y,marker='o') plt.axhline(0.5, color='r')
upvote count: 0
downvote count: 2
type: Question
has title: How to draw a vertical line at intersection point
score: -2

http://stackoverflow.com/a/52299852
has body: There is no string dtype in pandas. As noted in the docs: Note When working with heterogeneous data, the dtype of the resulting ndarray will be chosen to accommodate all of the data involved. For example, if strings are involved, the result will be of object dtype. If there are only floats and integers, the resulting array will be of float dtype. As far as replacing , for . in your whole dataframe, Use replace with regex = True: df = df.replace(',','.',regex=True) # or df.replace(',','.',regex=True, inplace = True) For example: If your dataframe df looks like: &gt;&gt;&gt; df col1 col2 0 x,x blah,blah 1 y,z hello,world 2 z.z ,.,.,. Then: df = df.replace(',','.',regex=True) &gt;&gt;&gt; df col1 col2 0 x.x blah.blah 1 y.z hello.world 2 z.z ......
type: Answer
answers question: http://stackoverflow.com/q/52299774
accepted answer of: http://stackoverflow.com/q/52299774
has comment: http://stackoverflow.com/comment/91547731
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4

http://stackoverflow.com/q/52426378
type: UnansweredQuestion
has body: I have a small .bat script which I run on a shared server. In it, I just call python and run a script: #!/bin/bash @echo off python SCRIPT.py In the python script, I am pulling data repeatedly from a website every minute or so. For some reason the API connection isn't great and every once in a while (maybe after an hour or two of data pulling), it throws an error like "connection timed out". To remedy this, I want to just loop back every time the python script breaks out; #!/bin/bash @echo off :loop python SCRIPT.py goto loop Given my lack of understanding of this stuff, I just want to know if this will actually work in re-running the python script only after the previous one error-ed out.
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91796189
score: 0
upvote count: 1
downvote count: 1
type: Question
has title: Auto Re-run Script in case of crash
tagged with: batch-file
has comment: http://stackoverflow.com/comment/91796387
favorite count: 0

ethereum
type: Tag
tags question: http://stackoverflow.com/q/52376823
tag name: ethereum
tags question: http://stackoverflow.com/q/52317640
tags question: http://stackoverflow.com/q/52272285

algorithm
tags question: http://stackoverflow.com/q/52429110
tag name: algorithm
tags question: http://stackoverflow.com/q/52390106
tags question: http://stackoverflow.com/q/52299947
tags question: http://stackoverflow.com/q/52288445
tags question: http://stackoverflow.com/q/52272402
tags question: http://stackoverflow.com/q/52406902
tags question: http://stackoverflow.com/q/52310610
tags question: http://stackoverflow.com/q/52315095
tags question: http://stackoverflow.com/q/52316725
tags question: http://stackoverflow.com/q/52323957
tags question: http://stackoverflow.com/q/52335731
tags question: http://stackoverflow.com/q/52362124
tags question: http://stackoverflow.com/q/52429260
tags question: http://stackoverflow.com/q/52277370
type: Tag
tags question: http://stackoverflow.com/q/52354777
tags question: http://stackoverflow.com/q/52346788
tags question: http://stackoverflow.com/q/52303451
tags question: http://stackoverflow.com/q/52346223
tags question: http://stackoverflow.com/q/52307347
tags question: http://stackoverflow.com/q/52274960
tags question: http://stackoverflow.com/q/52339274
tags question: http://stackoverflow.com/q/52356091
tags question: http://stackoverflow.com/q/52301197
tags question: http://stackoverflow.com/q/52284418
tags question: http://stackoverflow.com/q/52345330
tags question: http://stackoverflow.com/q/52312304
tags question: http://stackoverflow.com/q/52388992

http://stackoverflow.com/a/52275970
score: 4
has comment: http://stackoverflow.com/comment/91557810
has comment: http://stackoverflow.com/comment/91507400
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/91499722
answers question: http://stackoverflow.com/q/52275262
type: Answer
has body: You can groupby the sales rep and take the row-wise difference. Then merge the datasets back together. import pandas as pd df = pd.DataFrame({ 'Date': ['01-01-2018', '01-01-2018', '01-01-2018', '01-02-2018', '01-02-2018', '01-02-2018'], 'SalesRep': ['Jakob', 'Adomas', 'Thomas', 'Jakob', 'Adomas', 'Thomas',], 'itemA': [5, 10, 15, 50, 100, 150], 'itemB': [10, 20, 30, 30, 40, 65]}) df_diff = df.groupby('SalesRep').diff().fillna(0).astype(int) df.loc[:, ['itemA', 'itemB']] = df_diff.where(df_diff, df.loc[:, ['itemA', 'itemB']]) df # returns: Date SalesRep itemA itemB 0 01-01-2018 Jakob 5 10 1 01-01-2018 Adomas 10 20 2 01-01-2018 Thomas 15 30 3 01-02-2018 Jakob 45 20 4 01-02-2018 Adomas 90 20 5 01-02-2018 Thomas 135 35

http://stackoverflow.com/comment/91627232
type: QuestionComment
has text: @user2357112 thanks, should be fixed now.
comment on: http://stackoverflow.com/q/52340023
score: 0
type: Comment

http://stackoverflow.com/comment/91565677
type: AnswerComment
comment on: http://stackoverflow.com/a/52309182
type: Comment
score: 0
has text: @aditya Do you already know how to transmit data from a secondary thread? I think that with the example and the explanation it is no longer necessary to ask: *how to modify XXX of the GUI from another thread*.

http://stackoverflow.com/a/52289499
downvote count: 0
answers question: http://stackoverflow.com/q/52288873
type: Answer
upvote count: 2
has body: You should use a hash function such as binascii.crc32 to calculate a practically unique hash for each unique file content, and then use a dict of lists to group files by their hashes: from binascii import crc32 import os groups = {} for root, _, files in os.walk('File_Directory'): for file in files: if file.endswith('.json'): path = os.path.join(root, file) with open(path, 'rb') as f: groups.setdefault(crc32(f.read()), []).append(path) so that: print([l for l in groups.values() if len(l) &gt; 1]) will output all the duplicating files in grouped sub-lists.
score: 2

http://stackoverflow.com/q/52387433
type: Question
has comment: http://stackoverflow.com/comment/91719651
has body: I am trying to reproduce the following plot: I am working with a function of two variables: skin_depth(T,rho). So I decided to use the meshgrid and to plot using contourlines. The problem is it only works for a small range of T and rho. When I try to use the range for x and y axis like in the figure above, the following error message appears: MemoryError Traceback (most recent call last) in () 1 T = np.linspace(0.01,10000,10000) 2 rho = np.linspace(0.1,100000,1000000) ----> 3 X, Y = np.meshgrid(T,rho) C:\Users\paula\Anaconda2\lib\site-packages\numpy\lib\function_base.pyc in meshgrid(*xi, **kwargs) 4696 4697 if copy_: -> 4698 output = [x.copy() for x in output] 4699 4700 return output MemoryError: Does anyone know a way to avoid it? Below is my code. import numpy as np import matplotlib.pyplot as plt T = np.linspace(0.01,100,10000) rho = np.linspace(0.1,1000,10000) X, Y = np.meshgrid(T,rho) skin_depth = 500*(np.sqrt(Y*X)) levels=np.array([10,20,30,40,50,60,70,80,90,100,200,300,400,500,600,700,800]) fig = plt.figure(figsize=(10,10)) CS = plt.contour(X,Y,skin_depth, levels, colors='k') plt.clabel(CS, fontsize=9, inline=1, inlinespacing=1, fmt='%1.f') plt.grid(True,which="both",ls="-") plt.title('Skin Depth (m)') plt.xlabel('Period [T(s)] ') plt.ylabel('Resistivity [rho(ohm.m)]') plt.xscale('log') plt.yscale('log') plt.show()
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52387771
tagged with: python
tagged with: plot
has title: How to use a large meshgrid without memory error in python?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52387771
tagged with: matplotlib

http://stackoverflow.com/a/52415816
upvote count: 2
has body: You can pass a list to skiprows to skip only that row. From the docs: skiprows : list-like or integer or callable, default None Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file. Try: pd.read_csv('my.csv', skiprows=[1]) Beware that python starts counting from 0. So that column (in python) in 1
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52415754
downvote count: 0

http://stackoverflow.com/q/52428679
has answer: http://stackoverflow.com/a/52428851
favorite count: 0
tagged with: class
linked to: http://stackoverflow.com/q/40164900
tagged with: subclass
tagged with: python
has comment: http://stackoverflow.com/comment/91834540
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91832775
type: UnansweredQuestion
score: 6
upvote count: 7
downvote count: 1
has comment: http://stackoverflow.com/comment/91801578
has body: When inheriting from a class, the child class is accessible on the parent via the .__subclasses__() method. class BaseClass: pass class SubClass(BaseClass): pass BaseClass.__subclasses__() # [&lt;class '__main__.SubClass'&gt;] However, deleting the child class doesn't seem to remove it from the parent. del SubClass BaseClass.__subclasses__() # [&lt;class '__main__.SubClass'&gt;] Where does __subclasses__ get its information from? And can I manipulate it? Or Is there a proper way to remove a class and have its parent lose reference to it (e.g. BaseClass.remove_subclass(SubClass)?
has answer: http://stackoverflow.com/a/52442961
has comment: http://stackoverflow.com/comment/91801122
type: Question
has title: How to remove classes from __subclasses__?
answer count: 2

http://stackoverflow.com/q/52327186
score: 0
has body: I am creating a application using django My Code as follows: class Profile(models.Model): Name = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) E_mail = models.EmailField(max_length=70) Phone_no = models.BigIntegerField() Skills = models.TextField() Image = models.ImageField(upload_to='user_images') I want to autogenerate the user email in the user profile which the user had given at the time of signup. I am using the django autheticated models for signup and login and I am using class based views for my profile generation. Can anybody help me in this? Thank you
has comment: http://stackoverflow.com/comment/91809332
answer count: 1
has comment: http://stackoverflow.com/comment/91818756
tagged with: django-class-based-views
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: django-forms
has comment: http://stackoverflow.com/comment/91822258
has answer: http://stackoverflow.com/a/52441539
type: Question
has comment: http://stackoverflow.com/comment/91817906
has comment: http://stackoverflow.com/comment/91817878
tagged with: django-models
has title: Auto-generating user email when creating user profile?

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

http://stackoverflow.com/q/52413797
has comment: http://stackoverflow.com/comment/91771504
has comment: http://stackoverflow.com/comment/91771974
has comment: http://stackoverflow.com/comment/91771431
possible better answer: http://stackoverflow.com/a/52413837
upvote count: 2
linked to: http://stackoverflow.com/q/9085450
answer count: 3
tagged with: symbol-table
has answer: http://stackoverflow.com/a/52413837
favorite count: 0
has answer: http://stackoverflow.com/a/52413840
has body: Going through the python tutorial, in section 4.7.1, a mutable default argument is stored somewhere but I can't seem to find it using dir(), globals(), locals() or f.__dict__. I'm referring to this code: def f(a, L=[]): L.append(a) return L behaves as: &gt;&gt;&gt; print(f(1)) [1] &gt;&gt;&gt; print(f(2)) [1, 2] &gt;&gt;&gt; print(f(3)) [1, 2, 3] I would expect to see this in the namespace of the function, say when I do dir(f) but it is not there. I had a look at this but this is way more than I'm probably looking for.
tagged with: default-arguments
tagged with: python
has comment: http://stackoverflow.com/comment/91771548
tagged with: mutable
tagged with: function-declaration
type: AnsweredQuestion
score: 2
downvote count: 0
has title: Where does a mutable object argument of a function lives? Is there a symbol table? (Python tutorial 4.7.1)
has answer: http://stackoverflow.com/a/52413847
accepted answer: http://stackoverflow.com/a/52413847
type: Question

http://stackoverflow.com/q/52423254
answer count: 1
has title: Python logging: Can I pass arguments to a custom handler in json config file
tagged with: logging
has body: Ive read the docs, but did not find any mention of this. Is it possible to pass parameters to a custom logging.handler class inside a json configuration file? "handlers": { "custom_handler": { "class": "logging.CustomHandler", "args": ['a', 'b'] # &lt;------------------------ "level": "INFO", "formatter": "custom" } }, Where the handler class definition is : class CustomHandler(logging.Handler): def __init__(self, argA, argB): super().__init__() self.a = argA self.b = argB def emit(self, record): &lt;Some code&gt;
score: 4
accepted answer: http://stackoverflow.com/a/52434428
upvote count: 4
downvote count: 0
tagged with: python-3.6
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52434428
favorite count: 0
tagged with: python

http://stackoverflow.com/q/52278177
has answer: http://stackoverflow.com/a/52278752
upvote count: 5
score: 5
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52278752
tagged with: python
has title: Enum object not defined when imported - Python 3 through Jupyter Notebook
tagged with: jupyter-notebook
type: AnsweredQuestion
tagged with: python-3.x
type: Question
tagged with: enums
has body: I am using Python 3 through Jupyter Notebook I have two modules "color.py" and "painting.ipynb" in the same working directory. color.py from enum import Enum class Color(Enum): RED = 1 BLUE = 2 def painting(color): if color == Color.RED: print("The painting is red") elif color == Color.BLUE: print("The painting is blue") else: raise ValueError("The painting is not blue nor red!") painting.ipynb import color color.painting(Color.RED) When I try to run "painting.ipynb" in jupyter notebook, I have the following error. --------------------------------------------------------------------------- NameError Traceback (most recent call last) in () 1 import color 2 ----> 3 color.painting(Color.RED) NameError: name 'Color' is not defined I do not understand why I cannot access the color. Am I supposed to call the class ? It is the first time that I use jupyter notebook and Enum. Please help :) Thank you.

http://stackoverflow.com/q/52362011
answer count: 0
type: Question
upvote count: 5
tagged with: deep-learning
has title: How to initialize the weights in pytorch with my own function? (cs231n PyTorch notebook)
downvote count: 0
favorite count: 0
tagged with: pytorch
type: UnansweredQuestion
score: 5
tagged with: python
has body: In the cs231n pytorch notebook, they define random_weight function to return a tensor object that initialized by Kaiming normalization, and zero_weight function to return a tensor contains zero bias. The random_weight implementation: def random_weight(shape): if len(shape) == 2: # FC weight fan_in = shape[0] else: fan_in = np.prod(shape[1:]) w = torch.randn(shape, device=device, dtype=dtype) * np.sqrt(2. / fan_in) w.requires_grad = True return w The zero_weight implementation: def zero_weight(shape): return torch.zeros(shape, device=device, dtype=dtype, requires_grad=True) Now the goal is to define a three-layer ConvNet using the pytorch sequential api, and we have to use the two above functions to initialize all the weights in the ConvNet. I found some implementation like this: model = nn.Sequential(....) def init_weights(layer): if type(layer) in [nn.Conv2d, nn.Linear]: random_weight(layer.weight.size()) zero_weight(layer.bias.size()) model.apply(init_weights) optimizer = optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9, nesterov=True) But I suspect that the weights are not initialized by the two functions. Because I print the layer.weight.data before and after calling the random_weight, I got same data. So I try to modify the init_weights code like this: def init_weights(layer): if type(layer) in [nn.Conv2d, nn.Linear]: layer.weight.data = random_weight(layer.weight.size()) layer.bias.data = zero_weight(layer.bias.size()) But the performance really sucks, I get about 10% accuracy on the validation set. So, does anyone know the right way to using this two functions to initialize the weights? All suggestions are welcome! Thanks a lot!

http://stackoverflow.com/a/66900991
answers question: http://stackoverflow.com/q/52413568
score: 2
downvote count: 0
upvote count: 2
type: Answer
has body: My solution is close to Bob McCormick. The difference is that it's using the credentials method for using service account info instead of JSON file. Here i'm using Googles Secret Manager to import service account information so that my code can connect to a different GCP project: from google.cloud import secretmanager from google.oauth2 import service_account # Create the Secret Manager client. secret_client = secretmanager.SecretManagerServiceClient() # Build the resource name of the secret version. name = f"projects/{project-id}/secrets/{very-secret-secret-name}/versions/latest" # Access the secret version. secret_response = secret_client.access_secret_version(request={"name": name}) # Getting the secret data secret_payload = json.loads(secret_response.payload.data.decode("UTF-8")) # Applying the credentials as INFO instead of JSON credentials = service_account.Credentials.from_service_account_info( secret_payload, scopes=["https://www.googleapis.com/auth/cloud-platform"], )

http://stackoverflow.com/comment/91601504
has text: The first case and the last case are the same, which suggests you can simplify that code to one `if..else`.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52327228

http://stackoverflow.com/comment/91553646
score: 0
type: Comment
type: QuestionComment
has text: It's unclear what you want to do here. You have two collections that you want to apply to _something_ in some manner. Why 120? Do you want to visit each commission or not? If you do want to visit each commission, what makes sense to you for a default value?
comment on: http://stackoverflow.com/q/52302442

http://stackoverflow.com/q/52319432
accepted answer: http://stackoverflow.com/a/52319742
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/91587022
tagged with: tail
has body: I have a python script in a folder of a remote machine. For executing it, I make a ssh session from my local computer, go to that folder and run. Commands I use: ssh remotehost user@remotehost:~$ cd /my/folder user@remotehost:~$ python abc.py &gt;&gt; abc.log Now the problem is ssh session. The script takes lot of time and due to internet issues, ssh session terminates and script doesn't complete. Assume that the remote is always up and running. Can I run the script without caring of the ssh session termination and do tail -f abc.log with ssh anytime I want ?
tagged with: ssh
tagged with: python
has title: Run a script on remote host without caring ssh session
favorite count: 0
tagged with: remote-access
has answer: http://stackoverflow.com/a/52319742
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52319690
has answer: http://stackoverflow.com/a/52319690
type: Question
upvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/91586445

http://stackoverflow.com/comment/91562347
type: AnswerComment
comment on: http://stackoverflow.com/a/52307531
type: Comment
has text: I got these error: `Traceback (most recent call last): File "C:/Users/R/Pycharm/W3PythonPractise/Scarapenew.py", line 27, in <module> print(filename.get_text()) File "C:\Python37\lib\site-packages\bs4\element.py", line 1884, in __getattr__ "ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key AttributeError: ResultSet object has no attribute 'get_text'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?`
score: 0

http://stackoverflow.com/comment/91526254
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52289000
has text: You can use [getattr](https://docs.python.org/3/library/functions.html#getattr). For your case it could look like this: import kpi_module kpi_func = getattr(kpi_module, KPIToCalculate) try: kpi_result, status = kpi_func(raw_data) except AttributeError: status = not_defined

http://stackoverflow.com/comment/91555177
type: QuestionComment
comment on: http://stackoverflow.com/q/52303232
score: 1
has text: If you cannot change anything, then you cannot solve your problem. _Other answers_ seem to have very good suggestions. A variable is declared within a function if it is not needed outside. Otherwise it belongs elsewhere.
type: Comment

http://stackoverflow.com/comment/91805425
comment on: http://stackoverflow.com/a/52430071
type: AnswerComment
score: 0
type: Comment
has text: Note that this won't do async calls to all pages.

http://stackoverflow.com/a/52408187
has comment: http://stackoverflow.com/comment/91760315
has comment: http://stackoverflow.com/comment/91762977
has comment: http://stackoverflow.com/comment/91760174
answers question: http://stackoverflow.com/q/52408105
has body: Let us store that number you want to mask in a variable called masked. unmasked = str(unmasked) masked = len(unmasked[:-4])*"#"+unmasked[-4:] I hope this works.
upvote count: 14
has comment: http://stackoverflow.com/comment/91760253
has comment: http://stackoverflow.com/comment/91760073
type: Answer
score: 14
downvote count: 0

http://stackoverflow.com/q/52278362
has body: I'm following a tutorial on OpenCV but I have ran into a problem that I can't seem to fix. The code I currently have: import numpy as np import cv2 import matplotlib.pyplot as plt img = cv2.imread('/home/Desktop/family.png') face_cascade = cv2.CascadeClassifier('/home/Desktop/family.png') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) print(face_cascade) faces = face_cascade.detectMultiScale(gray, 1.3, 5) print (faces) for (x,y,w,h) in faces: cv2.rectangle(img, (x,y), (w+h, y+h), (255,0,0),5) roi_gray = gray[y:y:h, x:x+w] roi_color = img[y:y:h, x:x+w] plt.imshow(img) plt.show() The output of this is: &lt;CascadeClassifier 0x7f5f22e9eb30&gt; Traceback (most recent call last): File "/home/testtt.py", line 10, in &lt;module&gt; faces = face_cascade.detectMultiScale(gray, 1.3, 5) TypeError: Incorrect type of self (must be 'CascadeClassifier' or its derivative) Does anyone see what I am doing wrong? Clearly face_cascade is of type CascadeClassifier but yet it later on fails.
has comment: http://stackoverflow.com/comment/91504931
type: Question
has answer: http://stackoverflow.com/a/52278558
has title: OpenCV: Incorrect type of self (must be 'CascadeClassifier' or its derivative)
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: opencv

http://stackoverflow.com/q/52323427
answer count: 1
has title: The result of filter and list comprehension of a DataFrame column is not what I expected
tagged with: python
type: UnansweredQuestion
score: 0
has body: Basically I want to find IDs that are in DataFrame A but not in DataFrame B using python. I followed the suggestions in this post, but the result is not what I expected. Consider the following scenario: a = pd.DataFrame(data= {"id":[1, 1, 1, 2, 3, 4, 5],'score':[90,90,91,92,93,94,99]}) b = pd.DataFrame(data= {"id":[1, 2, 3, 4, 5],'letter':['a','b','c','d','e']}) Doing: set([x for x in a['id'] if x not in b['id']]) as the post mentioned above suggests, gives {5}, which is the same when doing: set(filter(lambda x: x not in b['id'], a['id'])) And this is not what I expected. The expected result should be an empty set(), which can be achieved by doing: set(a["id"]) - set(b["id"]) Could someone explain why the above codes yield different result? It will be greatly appreciated.
has answer: http://stackoverflow.com/a/52323580
tagged with: dataframe
linked to: http://stackoverflow.com/q/2104305
type: Question
tagged with: filter

http://stackoverflow.com/q/52290839
has comment: http://stackoverflow.com/comment/91532421
tagged with: deep-learning
linked to: http://stackoverflow.com/q/43876770
tagged with: pandas
downvote count: 1
has comment: http://stackoverflow.com/comment/91617390
favorite count: 0
has comment: http://stackoverflow.com/comment/91538200
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91531069
has answer: http://stackoverflow.com/a/52375848
has body: I have a data set which looks something like: emotion images 0 0 [[70, 80, 82, 72, 58, 58, 60, 63, 54, 58, 60, ... 1 0 [[151, 150, 147, 155, 148, 133, 111, 140, 170,... 2 2 [[231, 212, 156, 164, 174, 138, 161, 173, 182,... 3 4 [[24, 32, 36, 30, 32, 23, 19, 20, 30, 41, 21, ... 4 6 [[4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 15, 2... The emotion column is a categorical variable and images contain numpy array which represent images (size = (48, 48)). My task is Image Classification, for which I'm using keras. When I try: model.fit(df['images'], df['emotion'], epochs= 10, batch_size = 32) I get a Value Error: ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (28708, 1) I understand that fit() expects numpy objects and I have tried using 'df.values' as suggested here. But it doesn't really work for me. I'd like to preprocess in a way that also batches my input with size 32. I don't know how to preprocess or reshape my data from here so that I can train it on my network with keras. how do I change my data to have 4 dimensions as is expected by my network? model.summary() _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_7 (Conv2D) (None, 46, 46, 64) 640 _________________________________________________________________ activation_7 (Activation) (None, 46, 46, 64) 0 _________________________________________________________________ conv2d_8 (Conv2D) (None, 44, 44, 32) 18464 _________________________________________________________________ activation_8 (Activation) (None, 44, 44, 32) 0 _________________________________________________________________ max_pooling2d_4 (MaxPooling2 (None, 22, 22, 32) 0 _________________________________________________________________ conv2d_9 (Conv2D) (None, 20, 20, 32) 9248 _________________________________________________________________ activation_9 (Activation) (No…
has comment: http://stackoverflow.com/comment/91680649
has comment: http://stackoverflow.com/comment/91531026
score: 1
has answer: http://stackoverflow.com/a/59631241
has comment: http://stackoverflow.com/comment/91533189
type: Question
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/91551444
has title: Error when checking input: expected conv2d_input to have 4 dimensions, but got array with shape (28708, 1)
tagged with: keras

http://stackoverflow.com/q/52386422
tagged with: python
has title: Mayavi - hide "diagonal" lines in wireframe
tagged with: mayavi
has answer: http://stackoverflow.com/a/56144328
upvote count: 3
tagged with: mayavi.mlab
type: Question
score: 3
tagged with: matplotlib
downvote count: 0
answer count: 1
favorite count: 0
has body: I've just started using mayavi and was wondering if there's a way to plot the wireframe representation of the surface that looks like the one I'm used from matplotlib 3d. Minimal example: # sphere example import numpy as np from mayavi import mlab from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D # azimut and polar angle phi = np.linspace(0,2*np.pi,10) theta = np.linspace(0,np.pi,10) phi, theta = np.meshgrid(phi,theta) # cartesian coordinates x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) #plotting using matplotlib fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_wireframe(x,y,z) #plotting using mayavi mlab.mesh(x,y,z,representation='wireframe', color=(0,0,1)) As you can see the outputs differ: matplotlib prints the lines with constant phi resp theta. Mayavi however, also prints diagonal lines (highlighted in yellow) connecting those paths. I prefer the matplotlib version. Is there a way to achieve the same wireframe with mayavi? TIA
type: UnansweredQuestion

http://stackoverflow.com/comment/91852094
score: 0
comment on: http://stackoverflow.com/q/52403589
type: QuestionComment
has text: @StephenRauch Any IIR or FIR is ok, as long as the cutoff C(t) can vary smoothly along the time t (i.e. C(t) is not a piecewise constant function).
type: Comment

http://stackoverflow.com/a/65520606
type: Answer
answers question: http://stackoverflow.com/q/52383577
has body: Following the installation link specified by @Leo Liu-MSFT, I selected below two options only and the issue get resolved without restarting my machine.
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/91617890
score: 0
type: Comment
type: QuestionComment
has text: @Tendero Why have you eliminated the other question? :-)
comment on: http://stackoverflow.com/q/52297143

http://stackoverflow.com/q/52311278
score: 2
has comment: http://stackoverflow.com/comment/91671119
has comment: http://stackoverflow.com/comment/91574970
has comment: http://stackoverflow.com/comment/91574535
has comment: http://stackoverflow.com/comment/91570034
type: Question
has comment: http://stackoverflow.com/comment/91573108
has title: peewee not null constraint failed, adding _id to class
has body: Here's the model I'm trying to implement in peewee/python: class Person(BaseModel): name = peewee.Charfield(unique=True) rate = peewee.FloatField() class Unit(BaseModel): person = peewee.ForeignKeyField(Person) I create the tables, then try creating some dummy data in the database: from above import Person, Unit ben = Person() ben.name = "Ben Dover" ben.rate = 21.5 ben.save() hour_one = Unit() hour_one.person = ben hour_one.save() When I run both programs, I get an error on the second one at the hour_one.save() line with the following error: peewee.IntegrityError: NOT NULL constraint failed: unit.person_id I don't know why peewee thinks there's a person_id attribute on person. I thought person.name would be the unique identifying column in that table. I tried replacing unique=True with primary_key=True, and also tried including both, but the error persists. I could understand if I hadn't supplied ben.name, but I did. So what information is peewee missing that it thinks is null?
tagged with: peewee
has comment: http://stackoverflow.com/comment/91576160
has comment: http://stackoverflow.com/comment/91569860
has comment: http://stackoverflow.com/comment/91583283
has comment: http://stackoverflow.com/comment/91573934
tagged with: sqlite
downvote count: 0
favorite count: 0
tagged with: python-3.x
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91653242
has text: Configuring Docker can be tricky, writing a good Docker image can be tricky (especially if you've never done any software packaging at all), and you can't run a Docker container without administrator-level privileges. I would not encourage Docker as a first solution here. (A `requirements.txt` or a good `setup.py` file is a much better answer, and a prerequisite for Docker in any case.)
comment on: http://stackoverflow.com/a/52353901
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/92049280
type: AnswerComment
comment on: http://stackoverflow.com/a/52435906
type: Comment
has text: @hkoko try to install it by wheel http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyldap
score: 0

http://stackoverflow.com/q/52380638
accepted answer: http://stackoverflow.com/a/52380974
tagged with: api
tagged with: python-3.5
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/91706081
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52380687
has comment: http://stackoverflow.com/comment/91705617
has title: Assigining a variable to Python json value
tagged with: python
has comment: http://stackoverflow.com/comment/91705647
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52380687
has body: If i have a python json and i want to assigned a variable to one of the values in the python json, if booking.hotel.feedback_option == True: name = request.GET.get('firstname') email= request.GET.get('email') values = """ { "Name" ="'+str(name)+'", "HasExternalDoubleOptIn": true, "Email"="'+str(email)+'", "CustomFields": [ "Checkout=2018-09-07" ] } """ headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' } data = values.encode() req = Request('https://api.moosend.com/v3/subscribers/7c343r9ad-er56-4c51-810e-74e27f8505c2/subscribe.json?apikey=77f343914-4t3c-4d61-8435-9346f5b4adf6', data=data, headers=headers) response_body = urlopen(req).read()
type: Question
has comment: http://stackoverflow.com/comment/91705971
has answer: http://stackoverflow.com/a/52380974
has comment: http://stackoverflow.com/comment/91705566

http://stackoverflow.com/comment/91491579
type: Comment
comment on: http://stackoverflow.com/a/52272100
type: AnswerComment
has text: How could `filename` ever be `None` in this context actually ?
score: 0

http://stackoverflow.com/a/52396674
has comment: http://stackoverflow.com/comment/91738114
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91738090
type: Answer
has comment: http://stackoverflow.com/comment/91738168
upvote count: 2
has body: Each logging function you call from the module will have the root logger send the requested message at the corresponding level, so with the default configuration, you should see messages for at least everything WARN and higher.
accepted answer of: http://stackoverflow.com/q/52396636
has comment: http://stackoverflow.com/comment/91738213
has comment: http://stackoverflow.com/comment/91738171
answers question: http://stackoverflow.com/q/52396636
has comment: http://stackoverflow.com/comment/91738186

http://stackoverflow.com/a/52388850
has comment: http://stackoverflow.com/comment/91723692
has comment: http://stackoverflow.com/comment/91723746
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52388728
has comment: http://stackoverflow.com/comment/91723526
answers question: http://stackoverflow.com/q/52388728
downvote count: 1
has comment: http://stackoverflow.com/comment/91722712
type: AcceptedAnswer
has body: @micke, wanna bet this is due to history? I'm guessing the open function was one of the first added to Python because, well... the creator of the language needed that early on. I'd argue that having open as a built-in function is weird, not the other way around. Also note that you're using the variable f outside of the with block. And the with block automatically calls close on f when the block exits, so the del f statement is not necessary. That's the whole point of using with blocks (forgetting to .close() is a very common mistake)
score: 0
type: Answer

http://stackoverflow.com/a/52279723
score: 1
downvote count: 0
has body: If you want a solution without list comprehension and zip, you could do the following: def chunk_list(list_to_chunk): buffer_list = [] for index in range(1, len(list_to_chunk) - 1): new_list = [list_to_chunk[index], \ list_to_chunk[index-1], list_to_chunk[index+1]] buffer_list.append(new_list) return buffer_list The code uses a for-loop over every index from 1 to the second last index (range).
answers question: http://stackoverflow.com/q/52279479
type: Answer
upvote count: 1

http://stackoverflow.com/a/52337767
has comment: http://stackoverflow.com/comment/91625048
has comment: http://stackoverflow.com/comment/91625019
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52336807
downvote count: 0
has body: The solution is to use layouts, and set the alignment in QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft. I also recommend using the new connection syntax, on the other hand if you are going to inherit from QMainWindow in the constructor you must call it. And finally when you use QMainWindow you must set a central widget. import time from PyQt4 import QtCore, QtGui from PIL import ImageGrab, ImageQt class Main(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.setGeometry(200, 200, 1000, 700) self.setWindowTitle('threads') main_widget = QtGui.QWidget() self.setCentralWidget(main_widget) lay = QtGui.QVBoxLayout(main_widget) self.testButton = QtGui.QPushButton("Click") self.testButton.setFixedHeight(30) self.testButton.clicked.connect(self.capture) mainFrame = QtGui.QFrame() mainFrame.setStyleSheet("background-color: rbg(50, 50, 50)") _lay = QtGui.QVBoxLayout(mainFrame) _lay.setContentsMargins(0, 0, 0, 0) self.label_ = QtGui.QLabel() _lay.addWidget(self.label_, 0, QtCore.Qt.AlignTop|QtCore.Qt.AlignLeft) lay.addWidget(self.testButton) lay.addWidget(mainFrame) @QtCore.pyqtSlot(QtGui.QImage) def changeFrame(self, image): pixmap = QtGui.QPixmap.fromImage(image) self.label_.setPixmap(pixmap) @QtCore.pyqtSlot() def capture(self): self.thread_ = CaptureScreen() self.thread_.changedFrame.connect(self.changeFrame, QtCore.Qt.QueuedConnection) self.thread_.start() self.testButton.setDisabled(True) class CaptureScreen(QtCore.QThread): changedFrame = QtCore.pyqtSignal(QtGui.QImage) def __del__(self): print("?????") self.exiting = True self.quit() self.wait() def run(self): while True: time.sleep(1/60) w, h = 420, 220 img = ImageGrab.grab(bbox=(0, 0, w, h)) frame = ImageQt.toqimage(img) self.changedFrame.emit(QtGui.QImage(frame)) if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) w = Main() w.show() sys.exit(app.exec_())
accepted answer of: http://stackoverflow.com/q/52336807
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/91624930

http://stackoverflow.com/a/52313371
type: Answer
has comment: http://stackoverflow.com/comment/91575354
has body: From the Scikit Documentation, the value given by r2_score can be negative if your model is arbitrarily worse than random. Now, obviously this is not what one wants from using ML; you expect better than random results. The first thing I would note is that your data seems like it may be quite nonlinear, in which case PCA struggles to improve model performance. One potential substitute for PCA which accounts for essentially any nonlinearities in data is the use of autoencoders to preprocess data (Good article on these here). They can account for nonlinearities in data if you use non-linear activation functions on some of your hidden layers of the autoencoder, which may help your model's performance. There are many articles around the web that explain this, let me know if you want some resources if you so choose to pursue this course The next thing that I would note is that r2_score is really not the best way to measure error, and that using mean-squared error is much more popular, especially for linear regression. So, if you want to keep your model as simple as this, I would simply ignore the r2_score and move on from there. However, that being said, linear regression is not equipped to solve very complex problems due to its simplicity, and judging by the picture you provided, it's pretty clear to me that linear regression is very rough when applied to this dataset. I would be interested to know the difference in mean-squared-error between the PCA and non-PCA applied data. Here, the PCA should have less error than the the normal, non-PCA applied data. If it does not, then either your data is horribly non-linear (maybe?) or there is an error in your code (I looked over it and nothing is immediately obviously wrong with it). For linear regression, mean-squared-error is really almost the unanimous error function of choice, and is remarkably effective. Hope this answers your question, leave a comment/question about my answer if you have one and I will try to clarify as be…
has comment: http://stackoverflow.com/comment/91574263
has comment: http://stackoverflow.com/comment/91574212
accepted answer of: http://stackoverflow.com/q/52311416
has comment: http://stackoverflow.com/comment/91574396
has comment: http://stackoverflow.com/comment/91575308
has comment: http://stackoverflow.com/comment/91575265
has comment: http://stackoverflow.com/comment/91575124
has comment: http://stackoverflow.com/comment/91575224
has comment: http://stackoverflow.com/comment/91574883
score: 0
has comment: http://stackoverflow.com/comment/91574001
has comment: http://stackoverflow.com/comment/91575245
has comment: http://stackoverflow.com/comment/91575065
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52311416

http://stackoverflow.com/comment/91581511
comment on: http://stackoverflow.com/q/52315520
score: 0
type: Comment
type: QuestionComment
has text: Why did you add: `self.client.disconnect()`? Can you get nodes after being disconnected?

http://stackoverflow.com/q/52349325
has answer: http://stackoverflow.com/a/52349410
upvote count: 0
has comment: http://stackoverflow.com/comment/91644130
score: -2
has comment: http://stackoverflow.com/comment/91643987
has comment: http://stackoverflow.com/comment/91643875
has comment: http://stackoverflow.com/comment/91643931
has comment: http://stackoverflow.com/comment/91644018
has comment: http://stackoverflow.com/comment/91643977
has comment: http://stackoverflow.com/comment/91644002
has comment: http://stackoverflow.com/comment/91645588
answer count: 1
has comment: http://stackoverflow.com/comment/91644010
has title: Trying to join items in a list in python
favorite count: 0
has comment: http://stackoverflow.com/comment/91643976
has body: Oddly this isn't working. I have a list and I am trying to join each work together into one variable. Everything I have tried with join doesn't work right and spits out some weird garbage. Where am I making this blunder? street = ['20', 'mi', 'west', 'of'] #I've tried #street = ''.join(street) #street = ' '.join(street) #I need the output to be #street = '20 mi west of'
has comment: http://stackoverflow.com/comment/91643967
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/91643945
tagged with: list
tagged with: join
has comment: http://stackoverflow.com/comment/91643892
has comment: http://stackoverflow.com/comment/91644006
type: Question
has comment: http://stackoverflow.com/comment/91644023
has comment: http://stackoverflow.com/comment/91643949

unicode
tags question: http://stackoverflow.com/q/52359579
tag name: unicode
type: Tag
tags question: http://stackoverflow.com/q/52411253
tags question: http://stackoverflow.com/q/52328683
tags question: http://stackoverflow.com/q/52311407
tags question: http://stackoverflow.com/q/52379803
tags question: http://stackoverflow.com/q/52425315
tags question: http://stackoverflow.com/q/52416031
tags question: http://stackoverflow.com/q/52286525
tags question: http://stackoverflow.com/q/52333540
tags question: http://stackoverflow.com/q/52351619
tags question: http://stackoverflow.com/q/52293860
tags question: http://stackoverflow.com/q/52273054
tags question: http://stackoverflow.com/q/52274464
tags question: http://stackoverflow.com/q/52305532

http://stackoverflow.com/q/52373464
has comment: http://stackoverflow.com/comment/91691873
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52373723
accepted answer: http://stackoverflow.com/a/52373723
tagged with: python
has body: I have a dataframe that looks like this: date code1 code2 code3 6/1/18 X Y Z 6/1/18 A B C 6/1/18 S D F 6/5/18 T R Y 6/5/18 L M Q 6/29/18 N T Z 6/29/18 K G V 6/29/18 B A C 7/4/18 E F G I have two dates that I need to add: 7/1/18 and 7/2/18. I need to copy all the entries for the last day of the previous month (6/29/18), only changing the date. Output: date code1 code2 code3 6/1/18 X Y Z 6/1/18 A B C 6/1/18 S D F 6/5/18 T R Y 6/5/18 L M Q 6/29/18 N T Z 6/29/18 K G V 6/29/18 B A C 7/4/18 E F G 7/1/18 N T Z 7/1/18 K G V 7/1/18 B A C 7/2/18 N T Z 7/2/18 K G V 7/2/18 B A C The 7/1 and 7/2 dates have been added, using the same column values as 6/29. (The output can be ordered by date as well, it doesn't matter).
has comment: http://stackoverflow.com/comment/91691622
type: Question
has title: Pandas - duplicating multiple rows with new values
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91691991
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91691928
possible better answer: http://stackoverflow.com/a/52373839
answer count: 2
has comment: http://stackoverflow.com/comment/91691675
has comment: http://stackoverflow.com/comment/91691967
has answer: http://stackoverflow.com/a/52373839

http://stackoverflow.com/q/52319958
tagged with: pyspark
has body: I am trying to find all of the distinct values in each column in a dataframe and show in one table. Example data: |-----------|-----------|-----------| | COL_1 | COL_2 | COL_3 | |-----------|-----------|-----------| | A | C | D | | A | C | D | | A | C | E | | B | C | E | | B | C | F | | B | C | F | |-----------|-----------|-----------| Example output: |-----------|-----------|-----------| | COL_1 | COL_2 | COL_3 | |-----------|-----------|-----------| | A | C | D | | B | | E | | | | F | |-----------|-----------|-----------| Is this even possible? I have been able to do it in separate tables, but it would be much better all in one table. Any ideas?
tagged with: apache-spark
upvote count: 1
answer count: 1
favorite count: 0
has title: Pyspark - Select the distinct values from each column
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
downvote count: 0
accepted answer: http://stackoverflow.com/a/52321776
linked to: http://stackoverflow.com/q/51140470
type: Question
tagged with: apache-spark-sql
score: 1
has answer: http://stackoverflow.com/a/52321776

http://stackoverflow.com/q/52418234
has comment: http://stackoverflow.com/comment/91780222
type: Question
has title: How to make two models related to each other(vice versa) in django. one company should have mutiple catalog but one catalog can have only one company
score: -2
downvote count: 2
tagged with: django
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/91782221
upvote count: 0
has body: class Catalog(models.Model): name = models.CharField(max_length=200) no_of_pcs = models.IntegerField(null=True,blank=True) per_piece_price = models.DecimalField(null=True,blank=True,max_digits=10,decimal_places=2) def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=200) phone_number = models.IntegerField(null=True,blank=True) user = models.ManyToManyField(User) catalog = models.ManyToManyField(Catalog) def __str__(self): return self.name`***
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52418925
favorite count: 0

http://stackoverflow.com/comment/91580128
has text: you may check this question - maybe there is a fix for your problem! https://stackoverflow.com/questions/44102738/why-cant-i-import-opencv3-even-though-the-package-is-installed
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52316354

http://stackoverflow.com/comment/91625048
comment on: http://stackoverflow.com/a/52337767
type: Comment
score: 0
type: AnswerComment
has text: yes I implemented it aswell. It looks alot more neat. Thanks :o)

http://stackoverflow.com/comment/91529047
type: Comment
comment on: http://stackoverflow.com/a/52289843
score: 0
has text: and you use lstm_shape further in your code i assume? or?
type: AnswerComment

http://stackoverflow.com/comment/91783414
has text: How could an inherently unordered `dict` define a deterministic replacement strategy for multiple, possibly overlapping multi-character patterns?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52420009

http://stackoverflow.com/comment/91542626
type: Comment
comment on: http://stackoverflow.com/q/52294431
has text: They are both remote machines. For sure there will be many differences in the architecture. I will post above.
score: 0
type: QuestionComment

http://stackoverflow.com/a/52351314
answers question: http://stackoverflow.com/q/52351283
upvote count: 1
has body: You are calculating log2(0), which is - inf. Hence you are getting the error. Try range(1,n).
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/127277470
score: 0
has text: What if we have a list of dictionaries as ```replacement```?
type: AnswerComment
comment on: http://stackoverflow.com/a/52420142
type: Comment

http://stackoverflow.com/comment/91639962
has text: @HardQuestions there isn't.
comment on: http://stackoverflow.com/q/52347116
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/52343444
answers question: http://stackoverflow.com/q/52343357
score: 2
downvote count: 0
has body: You can't cast a UInt16 object - which you defined - to an int object. You need to change you code to become something like this. test_UInt16 from data_types import UInt16 def test_UInt16_constructor(): # default value should be 0 assert (UInt16().value == 0) # initialize with arbitrary integer value assert (UInt16(1 &lt;&lt; 8).value == (1 &lt;&lt; 8)) UInt16 class UInt16: def __init__(self, initial_value=0): self.value = initial_value Also it's a better practice to use built in test method (unittest class)
type: Answer
upvote count: 2

http://stackoverflow.com/a/52383582
type: Answer
has body: Nice code. The smallest change with the best improvement is to calculate from_second according to the current time position in the file like this: from_second = counter/2
answers question: http://stackoverflow.com/q/52357463
score: 0

http://stackoverflow.com/comment/91679245
type: Comment
has text: @Bazingaa - sure, but thinking what OP want ;)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52367540

http://stackoverflow.com/q/52420347
has title: Socket didn't make connection with server
has answer: http://stackoverflow.com/a/52420607
score: 0
answer count: 2
type: UnansweredQuestion
tagged with: sockets
tagged with: python
linked to: http://stackoverflow.com/q/7749341
has answer: http://stackoverflow.com/a/52420843
type: Question
tagged with: network-programming
has body: Please help me in this code. Error is given below. Error: socket succesfully created 111 connection failed traceback most recent call last file custom-iec.py line 27 in module s.sendstartdt typeerror send argument 1 must be string buffer list import socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) a = socket.connect_ex(('XXX.XXX.XXX.XXX', 2500)) #s = socket.socket() port=2500 a=socket.connect_ex(('XXX.XXX.XXX.XXX', port)) print a Packet = [ 0x68, 0x04, 0x43, 0x00, 0x00, 0x00 ] socket.send(Packet) print s.recv(256) s.close

http://stackoverflow.com/comment/91844232
has text: @Feign' Here is an [example](https://stackoverflow.com/questions/52450529/use-gtk-events-pending-to-show-a-loading-gtktreeview/52450530#52450530) using events_pending. It can't be used for what you need (querying databases), but since you asked :)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52420899

http://stackoverflow.com/comment/91495193
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52273855
has text: Where in the code is it crashing? Or do you not have access to the C code?

http://stackoverflow.com/a/52358700
has comment: http://stackoverflow.com/comment/91684808
upvote count: 1
has comment: http://stackoverflow.com/comment/103621433
has body: Such behavior occurs, because you passed main.py as the argument to python (python main.py). When you execute a script in such way, python interprets main module as __main__, but b module still updates main.a variable instead of __main__.a, because b has re-imported your main.py module as main. So to make it work, we can either update __main__.a in api_a function from perspective of b module OR print main.a variable instead of __main__.a from perspective of __main__ module. def api_a(): print("api_a()") import sys sys.modules['__main__'].a = 1 or def main(): ... thread_B.join() import sys print("a = " + str(sys.modules['main'].a)) __main__ docs
answers question: http://stackoverflow.com/q/52356112
has comment: http://stackoverflow.com/comment/103621955
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/q/52293079
type: Question
has answer: http://stackoverflow.com/a/52293182
type: AnsweredQuestion
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/52293182
tagged with: for-loop
tagged with: pandas
has comment: http://stackoverflow.com/comment/91534242
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91534023
favorite count: 0
has comment: http://stackoverflow.com/comment/91533932
tagged with: python
has body: I have split a dataframe into two based on a condition. I converted the column 'ItemName' from both dataframes into a list. I tried to use difflib to perform approximate string matching between two columns, one in each of these dataframes, both called 'ItemName'. I would like to join the list called 'matchlist' as a column into the source dataframe or on the other hand it is fine if I can append each output of the for loop into a new column in the source dataframe. source = list(datadf['ItemName']) destination = list(datadf['ItemName']) matchlist = [] for i in source: x = difflib.get_close_matches(i, destination, 3, 0.6) matchlist.append(x) I did try join and merge options in pandas but without any error the newly added columns only shown NaN values. Both the columns called 'ItemName' contain string values only. can someone help with an idea how to fix this?
score: 1
upvote count: 1
has title: append each value from a for loop into a column cell in a pandas dataframe

http://stackoverflow.com/comment/91772130
has text: Is it always a constant? For example is it always 5 for all the inputs of the model? Why don't you use a Lambda layer instead?
type: Comment
comment on: http://stackoverflow.com/q/52413371
score: 0
type: QuestionComment

http://stackoverflow.com/q/52321602
answer count: 2
has answer: http://stackoverflow.com/a/68170732
linked to: http://stackoverflow.com/q/56949628
has body: How does one hold shift and and click with the mouse using pyautogui? pyautogui.hotkey('shift', click(1611, 600)) have tried the line above. But it doesn't work
type: UnansweredQuestion
tagged with: pyautogui
has title: Pyautogui - Need to hold shift and click
downvote count: 0
score: 6
favorite count: 0
type: Question
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/52474897

http://stackoverflow.com/comment/91780005
comment on: http://stackoverflow.com/a/52417487
type: Comment
has text: hi sorry if the question wasn't clear, am not too sure on the technicalities of python as I'm pretty new to the program. my objective is to generate random samples from the 3 normal distributions and this is done by means of repeated random sampling of 300. then i add it into a list in order to visualise the sampling distribution.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52394269
has comment: http://stackoverflow.com/comment/91733755
has answer: http://stackoverflow.com/a/52394735
possible better answer: http://stackoverflow.com/a/52394522
score: 0
tagged with: bash
answer count: 3
upvote count: 1
downvote count: 1
tagged with: shell
favorite count: 0
has comment: http://stackoverflow.com/comment/91733815
tagged with: python
has answer: http://stackoverflow.com/a/52394522
accepted answer: http://stackoverflow.com/a/52394520
type: AnsweredQuestion
has body: In the following code I want to decrement the number after Vec2( which is 11 in the first line below: new Point([84], '[',{ x: 49.22, y: 33.75 }, 4.28, 13.5, [new Vec2(11, 2)]), new Point([85], ']', { x: 53.5, y: 33.75 }, 4.28, 13.5, [new Vec2(12, 2)]), new Point([87], '[', { x: 57.78, y: 33.75 }, 6.42, 13.5, [new Vec2(13, 2), new Vec2(14, 2)]) Output expected: new Point([84], '[',{ x: 49.22, y: 33.75 }, 4.28, 13.5, [new Vec2(10, 2)]), new Point([85], ']', { x: 53.5, y: 33.75 }, 4.28, 13.5, [new Vec2(11, 2)]), new Point([87], '[', { x: 57.78, y: 33.75 }, 6.42, 13.5, [new Vec2(12, 2), new Vec2(13, 2)]) I have hundreds of lines like above, I want to script it in python shell or bash. How can I do that?
has title: Python Shell or Bash: How to decrement a number in a string many times in a file
type: Question
has answer: http://stackoverflow.com/a/52394520
has comment: http://stackoverflow.com/comment/91733711

http://stackoverflow.com/a/52426877
answers question: http://stackoverflow.com/q/52301412
accepted answer of: http://stackoverflow.com/q/52301412
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/91840764
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/91832637
has body: I solved it with the following: try: """code here""" except subprocess.CalledProcessError: """unlock files and try again"""
score: 1

apache-spark
tags question: http://stackoverflow.com/q/52338462
tags question: http://stackoverflow.com/q/52327837
tags question: http://stackoverflow.com/q/52412597
tags question: http://stackoverflow.com/q/52275705
tags question: http://stackoverflow.com/q/52318352
tags question: http://stackoverflow.com/q/52417801
tags question: http://stackoverflow.com/q/52375797
tags question: http://stackoverflow.com/q/52322216
tags question: http://stackoverflow.com/q/52343688
tag name: apache-spark
tags question: http://stackoverflow.com/q/52362068
tags question: http://stackoverflow.com/q/52376475
tags question: http://stackoverflow.com/q/52367750
tags question: http://stackoverflow.com/q/52412070
tags question: http://stackoverflow.com/q/52396449
tags question: http://stackoverflow.com/q/52389487
tags question: http://stackoverflow.com/q/52287553
tags question: http://stackoverflow.com/q/52428093
tags question: http://stackoverflow.com/q/52420831
tags question: http://stackoverflow.com/q/52351735
tags question: http://stackoverflow.com/q/52383793
tags question: http://stackoverflow.com/q/52312543
tags question: http://stackoverflow.com/q/52394306
tags question: http://stackoverflow.com/q/52418187
tags question: http://stackoverflow.com/q/52298772
tags question: http://stackoverflow.com/q/52361128
tags question: http://stackoverflow.com/q/52319958
tags question: http://stackoverflow.com/q/52393400
type: Tag
tags question: http://stackoverflow.com/q/52350339

http://stackoverflow.com/q/52304411
has title: How to add a stopping condition for Jacobian Matrix?
tagged with: python-3.x
type: UnansweredQuestion
has body: def jacobi(m,numiter=100): #Number of rows determins the number of variables numvars = m.shape[0] #construct array for final iterations history = np.zeros((numvars,numiter)) i = 1 while(i &lt; numiter): #Loop for numiter for v in range(numvars): # Loop over all variables current = m[v,numvars] # Start with left hand side (augmented side of matrix) for col in range(numvars): #Loop over columns if v != col: # Don't count colume for current variable current = current - (m[v,col]*history[col, i-1]) #subtract other guesses form previous timestep current = current/m[v,v] #divide by current variable coefficent history[v,i] = current #Add this answer to the rest i = i + 1 #iterate #plot each variable for v in range(numvars): plt.plot(history[v,: i]); return history[:,i-1] I have this code that calculates Jacobian method. How do I add a stopping condition for when the solutions converge? i.e. the values for the current iteration have changed less than some threshold e from the values for the previous iteration. The threshold e will be an input to the function and the default value to 0.00001
tagged with: python
has answer: http://stackoverflow.com/a/52304577
type: Question
score: 0
answer count: 1

http://stackoverflow.com/a/52306774
has comment: http://stackoverflow.com/comment/91560832
score: 0
type: Answer
has body: You can add \.? for optional period: (Jan\.?(?:uary)|...
answers question: http://stackoverflow.com/q/52306754

http://stackoverflow.com/q/52350774
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/52351218
accepted answer: http://stackoverflow.com/a/52351218
possible better answer: http://stackoverflow.com/a/52351212
score: 4
has comment: http://stackoverflow.com/comment/91647029
tagged with: python
upvote count: 4
favorite count: 0
has title: Fourier Transform Using Numpy
downvote count: 0
has body: I'm trying to calculate the Fourier Transform of the following Gaussian: # sample spacing dx = 1.0 / 1000.0 # Points x1 = -5 x2 = 5 x = np.arange(x1, x2, dx) def light_intensity(): return 10*sp.stats.norm.pdf(x, 0, 1)+0.1*np.random.randn(x.size) fig, ax = plt.subplots() ax.plot(x,light_intensity()) I create a new array in the spacial frequency domain (Fourier Transform of Gaussian is a Gaussian so these values should be similar). I plot and get this: fig, ax = plt.subplots() xf = np.arange(x1,x2,dx) yf= np.fft.fftshift(light_intensity()) ax.plot(xf,np.abs(yf)) Why is it splitting into two peaks?
tagged with: continuous-fourier
has comment: http://stackoverflow.com/comment/91647095
has answer: http://stackoverflow.com/a/52351212
has comment: http://stackoverflow.com/comment/91646991
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/91668649
type: Comment
type: QuestionComment
has text: @AmosEgel Instead of showing the y axis as 0,1,2,3 i want to display them as in the dataframe
comment on: http://stackoverflow.com/q/52362047
score: 0

http://stackoverflow.com/q/52394954
has comment: http://stackoverflow.com/comment/91736279
has answer: http://stackoverflow.com/a/52396000
has body: I'm still getting the gist of xpath and how it works (have been trying to learn from w3 for a while) but I'm sort of confused how to extract this section of code from this webpage: https://www.pro-football-reference.com/years/2005/ (I've been looking through the source here: view-source:https://www.pro-football-reference.com/years/2005/). I would like to extract the URLs from lines 363 - 383. Week 1 Week 2 Week 3 Week 4 Week 5 Week 6 Week 7 Week 8 Week 9 Week 10 Week 11 Week 12 Week 13 Week 14 Week 15 Week 16 Week 17 Wild Card Divisional Conf Champ Super Bowl I've tried using $x('//ul[@class=""]/@href') in the . console but it doesn't really work. Could someone help me extract the href from these? Any help or advice would be greatly appreciated!
has title: How to extract URLs from this site with xpath and scrapy using href?
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/52395793
tagged with: python
tagged with: xpath
type: UnansweredQuestion
tagged with: scrapy
type: Question

http://stackoverflow.com/comment/91805240
type: Comment
has text: I am accessing it through DataCamp website, i dont have the file!, its a learning portal. they have preloaded the file. I dont have access.
type: AnswerComment
comment on: http://stackoverflow.com/a/52428999
score: 0

http://stackoverflow.com/comment/91740175
type: Comment
comment on: http://stackoverflow.com/a/52324580
has text: FYI: `signature` is not available on Python 2.7 or 3.4. While `signature` is available from a backport package `fundsign`, since it is a backport of 3.3 functionality it doesn't have `apply_defaults` (which is also not on available in pypy).
score: 0
type: AnswerComment

http://stackoverflow.com/a/52350426
answers question: http://stackoverflow.com/q/52350407
downvote count: 0
has comment: http://stackoverflow.com/comment/91684410
has body: If I understand correctly, it's not an index you want to add, but column names. You can do this directly from pd.read_csv: cols = ["ULSymbol", "ULPrice", "Flag", "OptionSymbol", "Ext", "Type", "Expiry", "Date", "Strike", "Last", "Bid", "Ask", "Volume", "OI", "IV", "Delta", "Gamma", "Theta", "Vega", "AKA"] opt_chain = pd.read_csv("market_prices/2018-08-21.csv", header=None, names = cols)
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/91752484
type: Comment
type: QuestionComment
has text: @roganjosh ok , there is no simple way it means ?
score: 0
comment on: http://stackoverflow.com/q/52404410

http://stackoverflow.com/a/55364431
score: 5
upvote count: 5
downvote count: 0
has body: I overcame this issue by wrapping the sigmoid function with np.minimum &amp; np.maximum: def sigmoid(x): sig = 1 / (1 + np.exp(-x)) # Define sigmoid function sig = np.minimum(sig, 0.9999) # Set upper bound sig = np.maximum(sig, 0.0001) # Set lower bound return sig As a result my losses started looking like this But both training and test losses converged well &amp; I received ~90% of accuracy on a tiny dataset using logistic regression.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52423163
answers question: http://stackoverflow.com/q/52423163
type: Answer
has comment: http://stackoverflow.com/comment/137246501

http://stackoverflow.com/comment/91518026
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52284823
has text: @coldspeed OP did; they appended it into the dictionary with duplicate keys...
score: 0

http://stackoverflow.com/a/52419349
score: 0
has comment: http://stackoverflow.com/comment/91782260
type: Answer
has comment: http://stackoverflow.com/comment/91782474
answers question: http://stackoverflow.com/q/52419117
has body: As it looks, default encoding is ascii while Python3 it's utf-8, below syntax to open the file can be used open(file, encoding='utf-8') Check your system default encoding, &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.stdout.encoding 'UTF-8' If it's not UTF-8, reset the encoding of your system. export LANGUAGE=en_US.UTF-8 export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 export LC_TYPE=en_US.UTF-8

http://stackoverflow.com/a/52274961
upvote count: 1
has body: You need to take the square root of the denominator, since the norm of a vector v is defined as sqrt(innerprod(v, v)). Does this give you the expected answer? import numpy as np def angle(A, x, y): nominator = x@A@y denominator = np.sqrt((x@A@x)*(y@A@y)) angle = np.arccos(nominator/denominator) return(angle) angle(A, x, y) 2.6905658417935308
score: 1
has comment: http://stackoverflow.com/comment/91499558
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52274704
accepted answer of: http://stackoverflow.com/q/52274704
type: Answer

http://stackoverflow.com/a/62986706
type: Answer
has body: Here's how I solved for this: @app.route('/download-data/') def download_data(): """Download the data to the user as a csv...""" # Retrieve the data from user's request data = cache.get("my_data") if not data: return jsonify({ "ERROR": "data not found." }) # - - - - - - - - - - - - - - - - - - - - - - - - - # Load from the format it was saved in df = pd.DataFrame.from_records(data) csv_data = df.to_csv(index=False, encoding='utf-8') response = Response(csv_data,mimetype='text/csv') response.headers.set("Content-Disposition", "attachment", filename="data.csv") return response
answers question: http://stackoverflow.com/q/52287070
score: 0

http://stackoverflow.com/comment/91619187
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52336053
has text: I've just gone to some lengths to check this - the error is actually the same. I think you may have misunderstood what I meant by `loading` I have changed this to `importing` in the question to make it totally clear I'm importing `64bit` code into `32bit` python
score: 0

http://stackoverflow.com/comment/91618056
type: QuestionComment
has text: @vasia but I am using "Popen". I am expecting to see this output on my web page: ; <<>> DiG 9.8.3-P1 <<>> www.google.com ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 20433 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0 ;; QUESTION SECTION: ;www.google.com. IN A ;; ANSWER SECTION: www.google.com. 254 IN A 216.58.206.36 ;; Query time: 3 msec ;; SERVER: 10.5.13.52#53(10.5.13.52) ;; WHEN: Fri Sep 14 16:58:51 2018 ;; MSG SIZE rcvd: 48
comment on: http://stackoverflow.com/q/52335195
score: 0
type: Comment

http://stackoverflow.com/q/52281025
has answer: http://stackoverflow.com/a/52281061
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/52281077
type: UnansweredQuestion
score: 6
type: Question
has body: I'm working with a Pandas dataframe like this: col1 col2 id name 0 1 2 1 harry 1 2 3 1 harry 2 3 4 2 harry 3 4 5 3 harry 4 5 6 4 harry 5 1 9 6 jane 6 2 10 6 jane 7 3 11 7 jane 8 4 12 7 jane 9 5 12 8 jane I'd like to create a new dataframe where, for each name, I take the first 3 rows with unique id values. For instance, for harry, this would be rows 0, 2, and 3. Row 1 is excluded since it has the same id as row 0. The correct output for my example dataframe is: col1 col2 id name 0 1 2 1 harry 2 3 4 2 harry 3 4 5 3 harry 5 1 9 6 jane 7 3 11 7 jane 9 5 12 8 jane Example dataframe is given by this code: example = pd.DataFrame({"col1":[1,2,3,4,5, 1,2,3,4,5], "id":[1,1,2,3,4, 6, 6, 7, 7, 8], "col2":[2,3,4,5,6, 9, 10, 11, 12, 12], "name":["harry", "harry", "harry", "harry", "harry", "jane", "jane","jane","jane","jane",]}) This code works but is very ugly and not vectorized: result_df = pd.DataFrame(columns=example.columns) names_to_ids = {} for i, row in example.iterrows(): curr_name = row["name"] curr_id = row["id"] print curr_name, curr_id if curr_name not in names_to_ids: result_df = result_df.append(row) names_to_ids[curr_name] = [curr_id] elif len(names_to_ids[curr_name]) &lt; 3 and curr_id not in names_to_ids[curr_name]: result_df = result_df.append(row) names_to_ids[curr_name].append(curr_id)
has answer: http://stackoverflow.com/a/52281376
downvote count: 0
favorite count: 0
answer count: 3
tagged with: pandas
has title: Pandas: Select First 3 Rows With Distinct Values in Specific Column

http://stackoverflow.com/q/52305294
type: AnsweredQuestion
type: Question
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52305357
has body: I am trying to run a python script every sleep_time, but I want this sleep_time variable to change based on the current time of day. The program is used with analyzing stock data so during the day (8:30am-5:30pm) I want the program to update its data every 60 seconds. When it is not between this time, I only need it to update every 10 minutes. The current code I have is as follows: sleep_time = 60 ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%H:%M') if (st &gt;= '8:30' and st &lt;='17:30'): sleep_time = 60 if(st &lt; '8:30' and st &gt;'17:30'): sleep_time = 600 while True: #runs this code every sleep_time seconds to constantly update ... time.sleep(sleep_time) But I can t get it to work because st is a string and I am not sure how to compare a string like this. Any help would be appreciated
score: 0
accepted answer: http://stackoverflow.com/a/52305357
has answer: http://stackoverflow.com/a/52305477
possible better answer: http://stackoverflow.com/a/52305477
has title: Changing a variable based on current time of day

http://stackoverflow.com/a/52294929
answers question: http://stackoverflow.com/q/52294701
has comment: http://stackoverflow.com/comment/100074013
downvote count: 0
has comment: http://stackoverflow.com/comment/100074217
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/100079463
has body: Python object serialization &amp; persistence You could use the pickle module to store and load data to and from disk. To store data to a file you can use pickle.dump(obj, file) To load data from a given file use pickle.load(file) Example import pickle class Queue: def __init__(self): self.queue = list() def add(self, item): if item not in self.queue: self.queue.insert(0, item) return True return False # edit your queue &amp; add elements as you wish my_queue = Queue() my_queue.add(1) my_queue.add(2) # save with open("my_saved_queue.obj","wb+") as queue_save_file: pickle.dump(my_queue, queue_save_file) print(f"&gt; saved queue: {my_queue.queue}") # load with open("my_saved_queue.obj","rb") as queue_save_file: my_loaded_queue: Queue = pickle.load(queue_save_file) print(f"&gt; loaded queue: {my_loaded_queue.queue}") # output: # &gt; saved queue: [2, 1] # &gt; loaded queue: [2, 1] Additional information More information can be found in the official Python documentation in the chapter Persistence.

http://stackoverflow.com/comment/99964696
type: Comment
score: 0
has text: Is there chance that we set the initial value to other values instead of 0?
comment on: http://stackoverflow.com/a/52443510
type: AnswerComment

http://stackoverflow.com/a/52338524
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52338177
type: Answer
has comment: http://stackoverflow.com/comment/91624915
accepted answer of: http://stackoverflow.com/q/52338177
has body: You could use the re library, Python standard library implementation of regular expressions. The requests library is also a good tool to have under your belt for these kinds of tasks. For example import re import requests url = "http://www.nasdaq.com/symbol/amzn" regex = '&lt;div id="qwidget_lastsale" class="qwidget-dollar"&gt;$(.*?)&lt;/div&gt;' # Retrieve the page. page_text = requests.get(url).text # Print the first capture group of the regular expression search. print(re.match(regex, page_text).group(1)) However, for any more sophisticated HTML parsing tasks I'd recommend the lxml.html or BeautifulSoup libraries.
score: 0

http://stackoverflow.com/comment/91610632
type: Comment
type: QuestionComment
has text: I am sorry, I had it wrong before. It is not `xi` passed as a list, but `n`. When you compute `dTheta` and `dPhi` you use `n` instead of `i` when calling `k2`, `k3` and `k4`. Aside from that, you should consider improving your code a bit (e.g. no code for the plotting is reported, use Python3, `n` can be defined using a `range`, encapsulate your code in function, follow a clearer coding style like [PEP8](https://www.python.org/dev/peps/pep-0008/)). Also, the question should be better formulated. My suggestion would avoid the error, but I would not know if the code solves the Lane-Emden eqn.
comment on: http://stackoverflow.com/q/52330621
score: 0

http://stackoverflow.com/q/52422195
upvote count: 8
type: Question
has answer: http://stackoverflow.com/a/52423162
has answer: http://stackoverflow.com/a/52422917
has title: Pandas + groupby
has body: The dataset contains 4 columns, where name is the name of the child, yearofbirth denotes the year in which the child was born, number represents the number of babies who were named with that particular name. For example, entry 1 reads, in the year 1880, 7065 girl children were named Mary. Through pandas, I`m trying to find out every year which name was the most used one. My code df.groupby(['yearofbirth']).agg({'number':'max'}).reset_index() The above code partially answers the question in hand. I want to want the name along with the maximum number.
tagged with: pandas-groupby
answer count: 3
tagged with: pandas
linked to: http://stackoverflow.com/q/15705630
score: 8
favorite count: 0
has comment: http://stackoverflow.com/comment/91788273
tagged with: data-analysis
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91787419
tagged with: python
downvote count: 0
has answer: http://stackoverflow.com/a/52423090

http://stackoverflow.com/q/52294850
linked to: http://stackoverflow.com/q/25557686
has answer: http://stackoverflow.com/a/52295224
has comment: http://stackoverflow.com/comment/91537631
upvote count: 1
answer count: 1
has body: I was learning how can I log to the same file from different processes from these official examples: 1,2. Then I tried a simple example of logging from different processes but without following the things suggested in above examples, that is by following usual way without considering multi process scenario for logging: Code import time import multiprocessing as mup import sys import os import logging def worker(name): logging.basicConfig( filename='temp.log', level=logging.INFO, filemode = 'a', format= '[%(asctime)s][%(levelname)s]: %(message)s') logger = logging.getLogger() a = 0 while(a &lt; 5): print(name,":",a) logger.info("{}: {}".format(name,a)) a = a+1 time.sleep(0.2) pass print("Exiting worker: ", name, "(", os.getpid(), ")") def start_server(): b = 0 while(b&lt;3): new_worker = mup.Process(target=worker,args=('worker-'+str(b),)) new_worker.daemon = True new_worker.start() b = b + 1 time.sleep(3600) start_server() Console worker-0 : 0 worker-0 : 1 worker-1 : 0 worker-0 : 2 worker-1 : 1 worker-2 : 0 worker-0 : 3 worker-1 : 2 worker-2 : 1 worker-0 : 4 worker-1 : 3 worker-2 : 2 Exiting worker: worker-0 ( 13300 ) worker-1 : 4 worker-2 : 3 Exiting worker: worker-1 ( 13228 ) worker-2 : 4 Exiting worker: worker-2 ( 11000 ) temp.log [2018-09-12 17:28:21,442][INFO]: worker-0: 0 [2018-09-12 17:28:21,643][INFO]: worker-0: 1 [2018-09-12 17:28:21,655][INFO]: worker-1: 0 [2018-09-12 17:28:21,843][INFO]: worker-0: 2 [2018-09-12 17:28:21,855][INFO]: worker-1: 1 [2018-09-12 17:28:21,871][INFO]: worker-2: 0 [2018-09-12 17:28:22,044][INFO]: worker-0: 3 [2018-09-12 17:28:22,056][INFO]: worker-1: 2 [2018-09-12 17:28:22,071][INFO]: worker-2: 1 [2018-09-12 17:28:22,244][INFO]: worker-0: 4 [2018-09-12 17:28:22,256][INFO]: worker-1: 3 [2018-09-12 17:28:22,272][INFO]: worker-2: 2 [2018-09-12 17:28:22,456][INFO]: worker-1: 4 [2018-09-12 17:28:22,472][INFO]: worker-2: 3 [2018-09-12 17:28:22,672][INFO]: worker-2: 4 Surprisingly it was working. I thought I should face some file access co…
has comment: http://stackoverflow.com/comment/91537492
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: logging
downvote count: 0
score: 1
has title: Why logging to the same file from different processes works while the docs says it shouldn't?
linked to: http://stackoverflow.com/q/27494725
tagged with: multiprocessing
type: Question

http://stackoverflow.com/comment/91800058
type: AnswerComment
has text: P.S. @amanbirs "However, other methods like Gradient Boosting should give you better performance". Finally, boosters gave me way worse performance. Have a look here (https://datascience.stackexchange.com/questions/38535/xgboost-performs-significantly-worse-than-random-forest) if you want for more information.
comment on: http://stackoverflow.com/a/52315402
type: Comment
score: 0

http://stackoverflow.com/q/52342786
linked to: http://stackoverflow.com/q/474528
duplicate of: http://stackoverflow.com/q/474528
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4541190
answer count: 0
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
has body: I need to run a specific function every second. I have searched for a solution and found this one: import threading def printit(): threading.Timer(5.0, printit).start() print "Hello, World!" printit() It seems to be the code I have been searching for. But after running those lines of code for 20 Minutes I have got following error message: Exception in thread Thread-1896: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner File "/usr/lib/python3.5/threading.py", line 1180, in run File "/home/pi/scanner/api/brightness.py", line 37, in adjust_brightness File "/home/pi/scanner/api/brightness.py", line 14, in get_brightness OSError: [Errno 24] Too many open files It seems that every time the function is called a new thread starts. Is there a way to stop the previous thread before the new one gets generated? Or are there other solutions where this doesn't happen?
type: Question
tagged with: python-multithreading
has comment: http://stackoverflow.com/comment/91632036
tagged with: python
linked to: http://stackoverflow.com/q/3393612
has title: How to prevent Python from opening too many files while threading?
has comment: http://stackoverflow.com/comment/91632641
upvote count: 1

http://stackoverflow.com/comment/91701954
type: QuestionComment
has text: @klaus D But, i dont want to send data with different representation, should be in hex format only.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52373121

http://stackoverflow.com/q/52358705
has answer: http://stackoverflow.com/a/52358773
upvote count: 1
downvote count: 1
possible better answer: http://stackoverflow.com/a/52359401
type: Question
has body: I'm working on a class that works with graphs. One of the ways to instantiate such a graph-object is to use a filepath as an constructor argument and the graph structure gets read/replicated from there. To do the actual parsing I use a secondary function. Which is the correct way to actually set the graph field? Shortened, assuming magic returns the graph structure: class Graph: def __init__(self, parse): self.graph = self._parse_file(parse) def _parse_file(file_path): return magic(file_path) or class Graph: def __init__(self, parse): self._parse_file(parse) def _parse_file(file_path): self.graph = magic(file_path) Does it even matter? It seems to me like I'm missing something.
has comment: http://stackoverflow.com/comment/91663032
has title: Proper way to instantiate an object when its content gets parsed from argument
answer count: 2
accepted answer: http://stackoverflow.com/a/52358773
favorite count: 0
has comment: http://stackoverflow.com/comment/91663423
score: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52359401

http://stackoverflow.com/a/52358353
has body: You should use numpy.partition to avoid a full sort. This will reduce the time complexity of finding the three maximum values from O(nlogn) to O(n), which will make a massive difference on large DataFrames: np.sum(np.partition(df.values, -3)[:, -3:], 1) df.assign(max3=np.sum(np.partition(df.values, -3)[:, -3:], 1)) 0 1 2 3 4 max3 0 591949 2575703 22479693 2202865 499835 27258261 1 2705 11426 339913 5438 1016 356777 2 18 119 4162 18 0 4299 3 264 1213 14999 246 116 16476 4 0 35 1292 10 0 1337 5 0 0 1442 0 0 1442 6 0 28 5596 20 0 5644 7 0 10 102 56 0 168 8 33 0 1224 17 0 1274 9 39 198 9505 62 35 9765 Timings In [411]: df = pd.DataFrame(np.random.rand(5000, 5000)) In [412]: %timeit np.sum(np.sort(df.values)[:,-3:],axis=1) 1.69 s ± 92.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [413]: %timeit np.sum(np.partition(df.values, -3)[:, -3:], 1) 364 ms ± 23.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
score: 8
type: Answer
downvote count: 0
upvote count: 8
answers question: http://stackoverflow.com/q/52358248
accepted answer of: http://stackoverflow.com/q/52358248
type: AcceptedAnswer

http://stackoverflow.com/comment/91592965
type: Comment
comment on: http://stackoverflow.com/q/52322385
type: QuestionComment
has text: It didn't help me. Still it is giving me the same issue.
score: 0

http://stackoverflow.com/comment/91589631
has text: Maybe not quite what you are looking for, but in Python 3 you could do `f'foo{" "*3}bar{" "*4}'`.
type: Comment
comment on: http://stackoverflow.com/q/52320928
score: 0
type: QuestionComment

http://stackoverflow.com/q/52300369
has answer: http://stackoverflow.com/a/52300498
upvote count: 2
type: UnansweredQuestion
downvote count: 2
type: Question
score: 0
has title: How to replace DOCTYPE element in Python?
answer count: 1
has body: My input file is: <?xml version="1.0" encoding="utf-8"?> ABC I want to change the DOCTYPE element (commented - see below): <?xml version="1.0" encoding="utf-8"?> ABC
favorite count: 0
tagged with: python
tagged with: python-3.x

http://stackoverflow.com/comment/91644111
comment on: http://stackoverflow.com/a/52349410
score: 0
type: AnswerComment
type: Comment
has text: It looks like it keeps spitting out elements of a list and not combining them into one new element

http://stackoverflow.com/q/52384628
tagged with: pytorch
has answer: http://stackoverflow.com/a/52540644
tagged with: cmake
type: AnsweredQuestion
has title: Compile PyTorch with additional linker options
type: Question
answer count: 1
has body: I have a modified version of the gloo library. I am able to compile and run programs that use this library (similar to what you can find in gloo/gloo/examples). Now, I want to build pytorch with my library. I replaced the third_party/gloo folder in PyTorch with my version of gloo and I am trying to compile it. However, my version of gloo requires some additional libraries and special linker options. Where should these linker options be added in the pytorch build system? Without these linker options, my compilation stops with the linker error: /pytorch/build/lib/libcaffe2_gpu.so: undefined reference to &lt;my code&gt; /pytorch/build/lib/libcaffe2.so: undefined reference to &lt;my code&gt;
score: 0
accepted answer: http://stackoverflow.com/a/52540644
tagged with: python

http://stackoverflow.com/comment/91616546
type: Comment
score: 0
has text: I understood the problem but currently I am going somewhere and I will answer you after a couple of hours
type: AnswerComment
comment on: http://stackoverflow.com/a/52323222

http://stackoverflow.com/a/52415615
answers question: http://stackoverflow.com/q/52415497
has comment: http://stackoverflow.com/comment/91775117
has comment: http://stackoverflow.com/comment/91775815
has comment: http://stackoverflow.com/comment/91774964
has comment: http://stackoverflow.com/comment/91775287
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91775782
accepted answer of: http://stackoverflow.com/q/52415497
has comment: http://stackoverflow.com/comment/91775802
has comment: http://stackoverflow.com/comment/91775224
type: Answer
has comment: http://stackoverflow.com/comment/91775188
has comment: http://stackoverflow.com/comment/91775836
has comment: http://stackoverflow.com/comment/91775825
has comment: http://stackoverflow.com/comment/91775882
has comment: http://stackoverflow.com/comment/91775088
upvote count: 2
score: 1
has body: This assumes that there isn't multiple blocks of integers (e.g. www.something212.com/page=?13) You could try using list comprehensions and str.isdigit() url = 'https://www.investopedia.com/articles/retirement/?page=6' digits = [d for d in url if d.isdigit()] digit = ''.join(digits) digit &gt;&gt;&gt; 6 Edited: now works with digits above 9
downvote count: 1
has comment: http://stackoverflow.com/comment/91775104
has comment: http://stackoverflow.com/comment/91775228
has comment: http://stackoverflow.com/comment/91775158

http://stackoverflow.com/comment/91777382
has text: It asks you to use the authentication. Did you try this `http://localhost:9999/? token=9777b5132d5ad6e00ddb64f3f6d4f8ca3a705f90ad515d7b` to login your Jupyter notebook?
type: Comment
comment on: http://stackoverflow.com/q/52397069
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91540143
comment on: http://stackoverflow.com/q/52295087
type: Comment
type: QuestionComment
has text: You're welcome. The two retrieved clusters may not correspond to what you intend though, so it will take some tweaking.
score: 0

http://stackoverflow.com/q/52344329
downvote count: 0
has body: I have a virtual server that has 2 IP addresses. I wrote a python script that sends HTTP request (by using requests library). the script is the following: import requests headers = { 'User-agent': 'Mozilla/5.0', 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip' } url = 'https://www.google.com' request_no_proxy = requests.get( url, headers=headers, ) by default, it sends the request with primary IP of the server. how can I send request by second IP of the server?
tagged with: python
favorite count: 0
score: 2
has comment: http://stackoverflow.com/comment/91634784
answer count: 0
upvote count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/15148225
tagged with: python-requests
has title: how to send HTTP request with 2 IP addresses of the server?
tagged with: server
has comment: http://stackoverflow.com/comment/91634696
has comment: http://stackoverflow.com/comment/91634624
type: Question
linked to: http://stackoverflow.com/q/7221577

http://stackoverflow.com/q/52369647
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52369699
score: 1
tagged with: set
downvote count: 1
type: Question
has title: Drop 'NaN' value in set that is in a dataframe
tagged with: pandas
has answer: http://stackoverflow.com/a/52369699
answer count: 1
tagged with: nan
favorite count: 0
upvote count: 2
has body: I have a dataframe that looks like this but with multiple rows: column_1 column_2 column_3 1 {lk, 18m, NaN} {kjaf, NaN} I would like to take the NaN out of each set, but iterating through the rows results in RuntimeError: Set changed size during iteration. The code that I have used so far is as follows: for index, row in df.iterrows(): col2 = row['column_2'] col3 = row['column_3'] for x in col2: col2.discard('NaN') for y in col3: col3.discard('NaN')
tagged with: python
has comment: http://stackoverflow.com/comment/91683730

http://stackoverflow.com/q/52359033
score: 0
has comment: http://stackoverflow.com/comment/91663135
has body: I am a python newbie and im trying to use a dictionary to count the number of items in x. x = [1,2,1,4,3,2,5,9] def counts(my_list): counts = dict() for item in my_list: counts[x] = counts.get(item,0)+1 return counts counts(x) Any help that makes this work would be greatly appreciated!!
has comment: http://stackoverflow.com/comment/91662481
has answer: http://stackoverflow.com/a/52359202
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52359059
type: Question
answer count: 3
has title: Creating a dictionary that keeps track of the count of the number of items in a list
tagged with: python
has comment: http://stackoverflow.com/comment/91662504
has answer: http://stackoverflow.com/a/52359109
tagged with: dictionary

http://stackoverflow.com/q/52296536
has answer: http://stackoverflow.com/a/52296887
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52296720
has answer: http://stackoverflow.com/a/52296720
score: 4
has title: Pandas: Starting from the second row. subtract from previous row and use it as value to the next subtraction
type: Question
upvote count: 4
answer count: 3
tagged with: pandas
downvote count: 0
accepted answer: http://stackoverflow.com/a/52296887
favorite count: 0
has body: Context I need to code an algorithm using Pandas to, starting from the second row, subtract a column value from the previous row, and use the result to keep subtracting the next row, etc. Example INPUT: ID VALUE 0 1 1 10 2 30 3 45 4 78 OUTPUT (just the result, not the operation itself): ID VALUE 0 1 1 9 #(10-1) 2 21 #(30-9) 3 24 #(45-21) 4 54 #(78-24) What I Tried df['VALUE'] = df['VALUE'] - df['VALUE]'.shift() # Doesn't starts with the second row, and use the original dataframe to subtract df['VALUE'] = df['VALUE'].diff() # Doesn't starts with the second row, and use the original dataframe to subtract
tagged with: python
has answer: http://stackoverflow.com/a/52296998

http://stackoverflow.com/comment/91631903
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52342801
has text: Well yes.... but your error would indicate you weren't issuing the rename specifying the E drive... that's why I was asking you to check what the values are for those... there's nothing stopping a rename command that equates to `rename E:\test.txt E:\test2.txt`... (even if you're on C or D or whatever)

http://stackoverflow.com/a/52341812
accepted answer of: http://stackoverflow.com/q/52341739
has comment: http://stackoverflow.com/comment/91630334
downvote count: 0
score: 1
type: AcceptedAnswer
has body: It's because most of the tables are within comments and your script wont grab them unless you kick out those vicious signs --&gt;,&lt;!-- from response. Try the following. It should give you 20 tables from that page. import requests from bs4 import BeautifulSoup url = 'https://www.pro-football-reference.com/boxscores/201809060phi.htm' r = requests.get(url).text res = r.replace("&lt;!--","").replace("--&gt;","") soup = BeautifulSoup(res, 'lxml') tables = soup.findAll("div",{"class":"table_outer_container"}) print (len(tables))
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52341739

http://stackoverflow.com/comment/91527327
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52289726
has text: yes, I understand this enables you to use the logging module to send messages to sentry, but that's not what I'm looking for. I want unhandled exceptions to be sent.

http://stackoverflow.com/q/52298365
has body: I've set up a logger using the code below: logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) handler = logging.FileHandler(filename='application.log', mode='a+') handler.setLevel(logging.DEBUG) logger.addHandler(handler) Whenever I attempt to write to the log, using the below code: logger.info("Application Started") I get the following Traceback: --- Logging error --- Traceback (most recent call last): File "/usr/lib/python3.7/logging/__init__.py", line 985, in emit stream.write(msg) TypeError: a bytes-like object is required, not 'str' Call stack: File "/home/&lt;user&gt;/Code/&lt;app_name&gt;/src/&lt;app_name&gt;.py", line 48, in &lt;module&gt; main() File "/home/&lt;user&gt;/Code/&lt;app_name&gt;/src/&lt;app_name&gt;.py", line 42, in main logger.info("Application Started") Message: 'Application Started' Arguments: () I'm aware that given the exception above, you would expect the file to have been opened in binary mode, except it's not, I'm only opening using "a+" mode. Update I've tried adding encoding='utf-8' to the filehandler, along with mode='a+t' and removing the named parameter filename as per the suggestions in the comments below to no avail.
upvote count: 1
answer count: 1
tagged with: logging
has comment: http://stackoverflow.com/comment/91545506
has comment: http://stackoverflow.com/comment/91545240
has comment: http://stackoverflow.com/comment/91545475
has answer: http://stackoverflow.com/a/52298915
has comment: http://stackoverflow.com/comment/91545401
has comment: http://stackoverflow.com/comment/91545279
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91544744
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91545310
has comment: http://stackoverflow.com/comment/91544808
favorite count: 0
tagged with: typeerror
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/52298915
has comment: http://stackoverflow.com/comment/91545098
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91545137
has title: TypeError when writing to logfile

http://stackoverflow.com/q/52401504
type: Question
has comment: http://stackoverflow.com/comment/91747235
accepted answer: http://stackoverflow.com/a/52403970
has title: Django creating Comment System with Ajax
upvote count: 0
answer count: 1
favorite count: 0
has body: I want to create a comment system for my page. The system should work without refreshing page.I am very new at Ajax and I probably missing somethings but I don't know what. When I click "comment" button, the page shows something like; my codes: view.py def post_detail(request, pk, ): post = get_object_or_404(Post, pk=pk) form = CommentForm(request.POST or None) if form.is_valid(): name = request.POST['name'] content = request.POST['content'] comment = Comment() comment.name = name comment.content= content return JsonResponse(model_to_dict(comment), safe=False) context = { 'post': post, 'form': form, } return render(request, 'blog/post_detail.html', context) models.py class Comment(models.Model): name = models.CharField(max_length=200, verbose_name='name') content = models.TextField(verbose_name='comment') created_date = models.DateTimeField(auto_now_add=True) comment.html {% load crispy_forms_tags %} {% csrf_token %} post_detail.html ... Yorum Ekle: {% include 'blog/comment.html' %} {% for comment in post.comments.all %} {{ comment.name }} | önce {% endfor %} forms.py ` class CommentForm(forms.ModelForm): class Meta: model = Comment fields = [ 'name', 'content', ] What are my mistakes and how can I fix it? Please help me. Thanks for your attentions.
tagged with: ajax
tagged with: python
tagged with: django
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52403970
tagged with: http://stackoverflow.com/tag/json
score: -1
has comment: http://stackoverflow.com/comment/91751651

http://stackoverflow.com/q/52382555
has body: I have a Python Lambda function that should create a PDF report. I tried to add a custom Dockerfile to install Latex at Lambda similar to https://github.com/samoconnor/lambdalatex 1 But the function cannot find the installed Latex files. (The copied file template.tex at the end of the Dockerfile is there) My serverless.yaml: plugins: - serverless-python-requirements custom: pythonRequirements: dockerizePip: non-linux dockerFile: Dockerfile The Dockerfile: FROM lambci/lambda:build-python3.6 # The TeXLive installer needs md5 and wget. RUN yum -y install perl-Digest-MD5 &amp;&amp; \ yum -y install wget \ yum -y install latexmk RUN mkdir /var/src WORKDIR /var/src # Download TeXLive installer. ADD http://mirror.ctan.org/systems/texlive/tlnet/install-tl-unx.tar.gz /var/src/ #COPY install-tl-unx.tar.gz /var/src/ # Minimal TeXLive configuration profile. COPY texlive.profile /var/src/ # Intstall base TeXLive system. RUN tar xf install*.tar.gz RUN cd install-tl-* &amp;&amp; \ ./install-tl --profile ../texlive.profile ENV PATH=/var/task/texlive/2017/bin/x86_64-linux/:$PATH # Install extra packages. RUN tlmgr install xcolor \ tcolorbox \ pgf \ environ \ trimspaces \ etoolbox \ booktabs \ lastpage \ pgfplots \ marginnote \ tabu \ varwidth \ makecell \ enumitem \ setspace \ xwatermark \ catoptions \ ltxkeys \ framed \ parskip \ endnotes \ footmisc \ zapfding \ symbol \ lm \ sectsty \ stringstrings \ koma-script \ multirow \ calculator \ adjustbox \ xkeyval \ collectbox \ siunitx \ l3kernel \ l3packages \ helvetic \ charter \ latexmk # Install latexmk. RUN tlmgr install latexmk # Remove LuaTeX. RUN tlmgr remove --force luatex # Remove large unneeded files. RUN rm -rf /var/task/texlive/2017/tlpkg/texlive.tlpdb* \ /var/task/texlive/2017/texmf-dist/source/latex/koma-script/doc \ /var/task/texlive/2017/texmf-dist/doc RUN mkdir -p /var/task/texlive/2017/tlpkg/TeXLive/Digest/ &amp;&amp; \ mkdir -p /var/task/texlive/2017/tlpkg/TeXLive/auto/Digest/MD5/ &amp;&amp; \ cp /usr/lib64/perl5/ven…
tagged with: python
answer count: 0
type: UnansweredQuestion
upvote count: 7
type: Question
score: 7
has title: Install Latex on Python AWS Lambda Function using Serverless Framework
downvote count: 0
tagged with: amazon-web-services
favorite count: 0
tagged with: aws-lambda
tagged with: docker
tagged with: serverless-framework

http://stackoverflow.com/q/52339138
downvote count: 0
tagged with: javascript
tagged with: annotatorjs
tagged with: pybossa
favorite count: 0
has comment: http://stackoverflow.com/comment/92452609
score: 4
type: UnansweredQuestion
has body: I'd like to annotate text (aka. highlight and add a label) for the purpose of training NER (named entity recognition) models. But it looks like none of the default templates can do this. And I've been doing a lot of googling but I haven't made much progress. Ideally it might look something like below. Though I'm happy with anyway to achieve annotation. I realize this is possible to do with Pybossa and Annotator.js but there doesn't appear to be any tutorials in existance. Can anyone provide the steps/code to do this in Pybossa?
tagged with: python
has answer: http://stackoverflow.com/a/52363100
has title: How to create a text annotation template in Pybossa?
type: Question
upvote count: 4
answer count: 1

http://stackoverflow.com/comment/91504781
type: QuestionComment
type: Comment
has text: The code I gave you gives you error? It runs normally for me. The point was that even though the user1 has two values it only keeps one in the barplot. That's what you mean error?
score: 0
comment on: http://stackoverflow.com/q/52277337

http://stackoverflow.com/comment/91751807
type: Comment
comment on: http://stackoverflow.com/q/52403860
type: QuestionComment
has text: I did in my first comment?
score: 1

http://stackoverflow.com/q/52392558
has answer: http://stackoverflow.com/a/52392950
tagged with: postgresql
tagged with: oracle-database
tagged with: python
type: UnansweredQuestion
has title: How to make a query for two tables in two different servers (python)?
has body: I'm stuck a bit with a following problem: I have two different servers within separated tables: Oracle with table "A" and PostgreSQL with table "B". I`m trying to make a program via python, which joins these two tables and writes the result into csv file. What is the best way to do it? (Importing a table from one db to another? Making a JOIN outside the db?) Would be happy for your help!
type: Question
tagged with: database
score: 0
answer count: 1

http://stackoverflow.com/q/52399006
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/91841819
tagged with: boto3
has comment: http://stackoverflow.com/comment/91768130
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91841173
has comment: http://stackoverflow.com/comment/91864883
has title: Amazon S3 with Django can't load all the static files
tagged with: python
score: 2
has body: I'm using Amazon S3 to be my static and media files storage. My Django project is running in Digital ocean ubuntu 16.04. After running python manage.py collectstatic I found the CSS and js did not work in my website. And then I found that the CSS and js hadn't been upload in the S3. I think this is the reason why the cs and js did not work because they are not in there. there is only 'static' folder in S3. in this static folder there are not my project static files but the admin xadmin and another plug's static files Above is the folder under static in S3. When I check the url of the js it looks like this: &lt;link rel="stylesheet" href="https://myproject.s3.amazonaws.com/css/main.css?Signature=imJphDmnb4U%2BWOWHjE0Iagk2tow%3D&amp;amp;AWSAccessKeyId=AKIAI4LFEI2ASSMOYRTQ&amp;amp;Expires=1537337559"&gt; &lt;link rel="icon" href="https://myproject.s3.amazonaws.com/images/logo-blue.png?Signature=ACidpeC946mBazTtHx0McVIk6rM%3D&amp;amp;AWSAccessKeyId=AKIAI4LFEI2ASSMOYRTQ&amp;amp;Expires=1537337559"&gt; But in my project the main.css is under static folder, the images are under media folder. This is so weird for me. This is my project folder looks like: And I found that, after running python manage.py collectstatic the system didn't copy the static and media at all Here is the main part of my settings.py: import os import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(BASE_DIR, 'apps')) sys.path.insert(0, os.path.join(BASE_DIR, 'extra_apps')) ROOT_URLCONF = 'myproject.urls' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') AWS_ACCESS_KEY_ID = 'myproject' AWS_SECRET_ACCESS_KEY = 'myproject' AWS_STORAGE_BUCKET_NAME = 'myproject' AWS_S3_FILE_OVERWRITE = False AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME # the sub-directories of media and static files STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = …
has comment: http://stackoverflow.com/comment/91768317
linked to: http://stackoverflow.com/q/52449377
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91768212
tagged with: django
tagged with: django-storage
type: Question

http://stackoverflow.com/comment/91603417
score: 1
comment on: http://stackoverflow.com/q/52328272
type: Comment
type: QuestionComment
has text: Could you explain how did you come from `a` to `b`? It is not clear why, for example, `1360` became `102`, and `230` became `255`.

http://stackoverflow.com/comment/91616916
type: Comment
score: 1
has text: Some of the indentation in the code in the question is broken.
comment on: http://stackoverflow.com/q/52334602
type: QuestionComment

http://stackoverflow.com/a/52313732
has comment: http://stackoverflow.com/comment/91575816
has comment: http://stackoverflow.com/comment/91578208
has comment: http://stackoverflow.com/comment/91577204
has comment: http://stackoverflow.com/comment/92014361
has comment: http://stackoverflow.com/comment/91575253
has comment: http://stackoverflow.com/comment/92009046
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92014859
has comment: http://stackoverflow.com/comment/91577549
has comment: http://stackoverflow.com/comment/91577866
has comment: http://stackoverflow.com/comment/91574763
has comment: http://stackoverflow.com/comment/91574724
has comment: http://stackoverflow.com/comment/91575330
has comment: http://stackoverflow.com/comment/92014753
has comment: http://stackoverflow.com/comment/92015069
type: Answer
has comment: http://stackoverflow.com/comment/91575746
has comment: http://stackoverflow.com/comment/92011559
has comment: http://stackoverflow.com/comment/92014458
has comment: http://stackoverflow.com/comment/91575686
has comment: http://stackoverflow.com/comment/91575321
upvote count: 1
has comment: http://stackoverflow.com/comment/91578115
accepted answer of: http://stackoverflow.com/q/52298676
has comment: http://stackoverflow.com/comment/91575536
answers question: http://stackoverflow.com/q/52298676
score: 1
has body: This works: from bs4 import BeautifulSoup import requests url = 'https://www.hujjat.org/' r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') path = 'C:/Users/John/Documents/Python/' namaazNames = soup.select('div.NamaazTimeName') namaazNames = [namaazName.text for namaazName in namaazNames] namaazTimes = soup.select('div.NamaazTime') namaazTimes = [namaazTime.text for namaazTime in namaazTimes] del namaazNames[1] del namaazTimes[1] for namaazName, namaazTime in zip(namaazNames, namaazTimes): with open(path + namaazName + '.txt', 'w') as file: file.write(namaazTime)
has comment: http://stackoverflow.com/comment/92014703

http://stackoverflow.com/comment/91627782
comment on: http://stackoverflow.com/a/52340347
type: AnswerComment
score: 0
has text: But once you put `ax.set_aspect('equal')`, the size doesn't matter right? Or am I unable to understand what you are trying to say? Explain please
type: Comment

http://stackoverflow.com/q/52426347
has comment: http://stackoverflow.com/comment/91795954
has answer: http://stackoverflow.com/a/52427794
tagged with: class
type: Question
has title: python For loop for class attributes?
linked to: http://stackoverflow.com/q/6886493
answer count: 2
tagged with: python
has body: Is there a way i can loop a function with an argument in a class if that argument is not equal to None? I know how to do this with a lot of if loops, but is there another way I can do this? Here's an example of what I want to do: class Name: def __init__(self,name,favfood,favcolour,favsport): self.name = name self.favfood = favfood self.favcolour = favcolour self.favsport = favsport henry = Name("Henry","Sushi","Blue",None) I want a function that prints out all his favourite things, but will skip it if it is None, a for loop for classes pretty much. Is there a way to have a forloop for every attribute in a class?
score: 0
has answer: http://stackoverflow.com/a/52426533
type: UnansweredQuestion

numpy
tags question: http://stackoverflow.com/q/52383664
tags question: http://stackoverflow.com/q/52350481
tags question: http://stackoverflow.com/q/52348939
tags question: http://stackoverflow.com/q/52317268
tags question: http://stackoverflow.com/q/52360834
tags question: http://stackoverflow.com/q/52356567
tags question: http://stackoverflow.com/q/52386182
tags question: http://stackoverflow.com/q/52337931
tags question: http://stackoverflow.com/q/52334909
tags question: http://stackoverflow.com/q/52413123
tags question: http://stackoverflow.com/q/52288029
tags question: http://stackoverflow.com/q/52274704
tags question: http://stackoverflow.com/q/52345762
tags question: http://stackoverflow.com/q/52404794
tags question: http://stackoverflow.com/q/52429696
tags question: http://stackoverflow.com/q/52378011
tags question: http://stackoverflow.com/q/52357542
tags question: http://stackoverflow.com/q/52374062
tags question: http://stackoverflow.com/q/52349377
tags question: http://stackoverflow.com/q/52361743
tags question: http://stackoverflow.com/q/52305719
tags question: http://stackoverflow.com/q/52400953
tags question: http://stackoverflow.com/q/52409479
tags question: http://stackoverflow.com/q/52338865
tags question: http://stackoverflow.com/q/52331966
tags question: http://stackoverflow.com/q/52307410
tags question: http://stackoverflow.com/q/52328155
tags question: http://stackoverflow.com/q/52303407
tags question: http://stackoverflow.com/q/52367739
tags question: http://stackoverflow.com/q/52350774
tags question: http://stackoverflow.com/q/52407819
tags question: http://stackoverflow.com/q/52418839
tags question: http://stackoverflow.com/q/52324800
tags question: http://stackoverflow.com/q/52358039
tags question: http://stackoverflow.com/q/52272219
tags question: http://stackoverflow.com/q/52420450
tags question: http://stackoverflow.com/q/52324657
tags question: http://stackoverflow.com/q/52291284
tags question: http://stackoverflow.com/q/52390002
tags question: http://stackoverflow.com/q/52376009
tags question: http://stackoverflow.com/q/52383129
tags question: http://stackoverflow.com/q/52379610
tags question: http://stackoverflow.com/q/52373167
tags question: http://stackoverflow.com/q/52397513
tags question: http://stackoverflow.com/q/52323907
tags question: http://stackoverflow.com/q/52316683
tags question: http://stackoverflow.com/q/52343946
tags question: http://stackoverflow.com/q/52388194
tags question: http://stackoverflow.com/q/52414943
tags question: http://stackoverflow.com/q/52375356
tags question: http://stackoverflow.com/q/52285454
tags question: http://stackoverflow.com/q/52311575
tags question: http://stackoverflow.com/q/52349625
tags question: http://stackoverflow.com/q/52338433
tags question: http://stackoverflow.com/q/52355463
tags question: http://stackoverflow.com/q/52301862
tags question: http://stackoverflow.com/q/52333067
tags question: http://stackoverflow.com/q/52417929
tags question: http://stackoverflow.com/q/52390665
tags question: http://stackoverflow.com/q/52323208
tags question: http://stackoverflow.com/q/52351426
tags question: http://stackoverflow.com/q/52418546
tags question: http://stackoverflow.com/q/52323524
tags question: http://stackoverflow.com/q/52368146
tags question: http://stackoverflow.com/q/52313237
tags question: http://stackoverflow.com/q/52306666
tags question: http://stackoverflow.com/q/52396315
tags question: http://stackoverflow.com/q/52357676
tags question: http://stackoverflow.com/q/52322364
tags question: http://stackoverflow.com/q/52311755
tags question: http://stackoverflow.com/q/52359607
tags question: http://stackoverflow.com/q/52380811
tags question: http://stackoverflow.com/q/52403589
tags question: http://stackoverflow.com/q/52366421
tags question: http://stackoverflow.com/q/52373014
tags question: http://stackoverflow.com/q/52329721
tags question: http://stackoverflow.com/q/52352593
tags question: http://stackoverflow.com/q/52337439
tags question: http://stackoverflow.com/q/52345144
tags question: http://stackoverflow.com/q/52358337

http://stackoverflow.com/q/52366574
has comment: http://stackoverflow.com/comment/91677447
type: Question
upvote count: 2
possible better answer: http://stackoverflow.com/a/52366719
has comment: http://stackoverflow.com/comment/91677712
has answer: http://stackoverflow.com/a/52366853
tagged with: python
has answer: http://stackoverflow.com/a/52366719
has title: How to access the index before i in Python?
accepted answer: http://stackoverflow.com/a/52366824
answer count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/91677439
has comment: http://stackoverflow.com/comment/91677320
has body: struggling a bit understanding how to access indices in Python loops. How would you write this code in Python? int x = 5; for (int i = 0; i &lt; s.length; i++) { if (s[i] + s[i - 1] == x) { System.out.println("Success"); } } So far, I have tried the enumerate method, but I don't think it's working as intended. x = 5 for i, c in enumerate(s): if (i, c + (i - 1), c == x): print("Success") Sorry if this has been asked before, but I couldn't really find a solution to this exact way of handling indices in Python loops. Would really appreciate the help.
has comment: http://stackoverflow.com/comment/91677409
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52366824
score: 1
favorite count: 0

http://stackoverflow.com/q/52350978
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52351092
has answer: http://stackoverflow.com/a/52351092
has title: pyrtlsdr on windows doesnt import
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/60760007
has answer: http://stackoverflow.com/a/65528758
tagged with: python-3.6
answer count: 4
favorite count: 0
tagged with: python-3.x
downvote count: 0
has answer: http://stackoverflow.com/a/58825045
accepted answer: http://stackoverflow.com/a/58825045
has body: I'm trying to get pyrtlsdr-0.2.9 to work on a windows 10 computer with python 3.6. First, I installed it with pip like the instructions says on the site. Then, for some reason when I try to import the module or run an example script I get the following error message: Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; import rtlsdr File "C:\...\Programs\Python\Python36-32\lib\site-packages\rtlsdr\__init__.py", line 56, in &lt;module&gt; from .librtlsdr import librtlsdr File "C:\...\Programs\Python\Python36-32\lib\site-packages\rtlsdr\librtlsdr.py", line 50, in &lt;module&gt; librtlsdr = load_librtlsdr() File "C:\...\Programs\Python\Python36-32\lib\site-packages\rtlsdr\librtlsdr.py", line 45, in load_librtlsdr raise ImportError('Error loading librtlsdr. Make sure librtlsdr '\ ImportError: Error loading librtlsdr. Make sure librtlsdr (and all of its dependencies) are in your path I've tried to lightly edit the module and to keep it in the same folder as my script in which case I get this error: OSError: Error code -12 when opening SDR (device index = 0) How can I get this module to work on windows? librtlsdr works with my dongle, but apparently not via python.
tagged with: python

http://stackoverflow.com/comment/91753862
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52392876
has text: One last question. QNetworkAccessManager can handle a network connection error? I didn't found documentation about this.

http://stackoverflow.com/comment/91651318
comment on: http://stackoverflow.com/q/52353172
type: Comment
type: QuestionComment
score: 1
has text: No, normally it should work. What exactly does it produce here? `None`?

http://stackoverflow.com/a/61336851
answers question: http://stackoverflow.com/q/52394408
type: Answer
has body: To get the path, follow the steps below. In the search bar type the following and press enter This will then show all the metadata. There find the path to the profile
score: 34
downvote count: 0
upvote count: 34

http://stackoverflow.com/a/52430096
has body: Based on this answer, you can do the following to convert your comma decimal: def conv(x): return x.replace(',', '.').encode() read = np.genfromtxt((conv(x) for x in open("x.csv")), delimiter=';') &gt;&gt;&gt; read array([[120.4619 , 1.639486], [121.4262 , 1.623145], [122.3904 , 1.607553], [123.3547 , 1.592153], [124.3189 , 1.576472], [125.2832 , 1.56022 ], [126.2474 , 1.543355], [127.2117 , 1.526069], [128.1759 , 1.508706], [129.1402 , 1.491635], [130.1044 , 1.475144], [131.0686 , 1.459387], [132.0329 , 1.444416]])
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52429696
downvote count: 0

http://stackoverflow.com/a/52358698
downvote count: 0
score: 1
has body: It is hard to say from your description, but if you're using Flask, you're most probably using (or will use in production) multiple processes, and you probably have a connection pool (i.e. multiple connections) in each process. So while each connection is executing queries sequentially, this query can be ran concurrently by multiple connections at the same time. To prevent your application from obtaining the same row at the same time while handling different requests, you should use transactions and techniques like SELECT FOR UPDATE. The exact solution depends on your exact use case.
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52357407
accepted answer of: http://stackoverflow.com/q/52357407
type: Answer

http://stackoverflow.com/a/52338697
has comment: http://stackoverflow.com/comment/91679061
has body: Your problem looks like one of the most common problems in database operation. I do not fully understand what you want to get because you have not formulated the task. Now to the possible solution - avoid loops at all. You have a very long table with columns time, FlightID, Operator, Terminal, A_D. Other columns and dates do not matter if I understand you correctly. Also start_time and end_time are the same in every row. By the way you may get time column with the code table.loc[:, 'time'] = table.loc[:, 'START'].dt.time. table = table.drop_duplicates(subset=['time', 'FlightID', 'Operator', 'Terminal']). And your table gonna become significantly shorter. Split table into table_arr and table_dep according to A_D value: table_arr = table.loc[table.loc[:, 'A_D'] == 'A', ['FlightID', 'Operator', 'Terminal', 'time']], table_dep = table.loc[table.loc[:, 'A_D'] == 'D', ['FlightID', 'Operator', 'Terminal', 'time']] Seems like all you tried to get with loops you may get with a single line: table_result = table_arr.merge(table_dep, how='right', on=['Operator', 'Terminal'], suffixes=('_arr', '_dep')). It is basically the same operation as JOIN in SQL. According to my understanding of your problem and having the tiny piece of data you have provided you get just the desired output (correspondence between FlightID_dep and FlightID_arr for all FlightID_dep values) without any loop so much faster. table_result is: FlightID_arr Operator Terminal time_arr FlightID_dep time_dep 0 DL401 DL 3 06:50:00 DL001 09:30:00 1 DL402 DL 3 07:45:00 DL001 09:30:00 2 NaN VS 3 NaN VS001 15:15:00 Of course, in general case (with actual data) you will need one more step - filter table_result on condition time_arr &lt; time_dep or any other condition you have. Unfortunately the data you have provided is not enough to fully solve your problem. Complete code is: import io import pandas as pd data = ''' START,END,A_D,Operator,FlightID,Terminal,TROUND_ID,tot 2017-03-26 16:55:00,2017-10-28 16:55:00,A,QR,QR00…
score: 1
answers question: http://stackoverflow.com/q/52279699
has comment: http://stackoverflow.com/comment/91679878
has comment: http://stackoverflow.com/comment/91677696
upvote count: 1
has comment: http://stackoverflow.com/comment/91632147
has comment: http://stackoverflow.com/comment/91679588
has comment: http://stackoverflow.com/comment/91631780
type: Answer
downvote count: 0

http://stackoverflow.com/a/52393926
type: Answer
score: 0
has body: Invalid JSON is probably generated by an incorrect generator. This seems to be more common that should be. There is a tool, call dirty-json which might be of help: https://github.com/RyanMarcus/dirty-json There's also an on-line verion. Your invalid JSON is interpreted like this: { "header": " Clothing \r\n\t\t\t\t\t \r\n\t\t\t\t 438 styles found ", "refinements": " \r\n \r\nRefineClear all \t\r\n \r\n\t\t Refine" }
has comment: http://stackoverflow.com/comment/91875530
answers question: http://stackoverflow.com/q/52393610

http://stackoverflow.com/comment/91599010
has text: Yes, it must be deterministic, as I want other people to be able to run the same program with same outcome.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52325560
score: 0

http://stackoverflow.com/comment/91646280
has text: While this does provide a better way of doing it, this question was actually asking if it was possible and if so how. I know that I should do it in a different way (and I probably will), but this was a project to try some interesting python features.
comment on: http://stackoverflow.com/a/52350395
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52359606
has body: Currently I have a table that looks like this: I'm trying to give each month in the year column a year value (e.g. September = 09-2011, December = 12-2011, March = 03-2012 etc.) I'm completely stumped on how to do this as i'm new to working with pandas. Does anyone have any pointers on how to manage this using pandas?
possible better answer: http://stackoverflow.com/a/52359782
has answer: http://stackoverflow.com/a/52359782
has answer: http://stackoverflow.com/a/52359747
tagged with: python
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/52359747
has title: Setting a date column in python pandas
score: 0
answer count: 2
tagged with: pandas

http://stackoverflow.com/comment/91747066
type: QuestionComment
score: 0
has text: Why not test the method by calling it directly in the test? i.e Create an object for that class and call the method with the relevant parameters
comment on: http://stackoverflow.com/q/52400853
type: Comment

http://stackoverflow.com/q/52405799
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52405948
downvote count: 3
has comment: http://stackoverflow.com/comment/91755311
type: Question
has comment: http://stackoverflow.com/comment/91755410
tagged with: http://stackoverflow.com/tag/json
has body: I am very much new to JSON parsing. Below is my JSON: [ { "description": "Newton", "exam_code": { "date_added": "2015-05-13T04:49:54+00:00", "description": "Production", "exam_tags": [ { "date_added": "2012-01-13T03:39:17+00:00", "descriptive_name": "Production v0.1", "id": 1, "max_count": "147", "name": "Production" } ], "id": 1, "name": "Production", "prefix": "SA" }, "name": "CM" }, { "description": "Opera", "exam_code": { "date_added": "2015-05-13T04:49:54+00:00", "description": "Production", "test_tags": [ { "date_added": "2012-02-22T12:44:55+00:00", "descriptive_name": "Production v0.1", "id": 1, "max_count": "147", "name": "Production" } ], "id": 1, "name": "Production", "prefix": "SA" }, "name": "OS" } ] Here I am trying to find if name value is CM print description value. If name value is OS then print description value. Please help me to to understand how JSON parsing can be done?
linked to: http://stackoverflow.com/q/2835559
has answer: http://stackoverflow.com/a/52405948
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91755774
favorite count: 0
has comment: http://stackoverflow.com/comment/91755350
score: -3
tagged with: python
tagged with: parsing
has title: Parsing JSON data if a key value is matched and print a key value in Python

http://stackoverflow.com/comment/91506284
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52279054
has text: Try to capture http packets, and see what's the difference.

enums
tags question: http://stackoverflow.com/q/52331085
tags question: http://stackoverflow.com/q/52278177
tags question: http://stackoverflow.com/q/52314545
tag name: enums
type: Tag
tags question: http://stackoverflow.com/q/52324480

http://stackoverflow.com/q/52298850
favorite count: 0
tagged with: python
tagged with: discord
accepted answer: http://stackoverflow.com/a/52298941
has body: I'm working on a python based discord bot that has the following command @client.command(name="Mine", description="Mine daily.", brief="Mine daily.", aliases=['mine', 'm'], pass_context=True) @commands.cooldown(1, 30, commands.BucketType.user) async def mine(ctx, arg): &lt;content&gt; But when users hit the 30 second rate limit of the command it outputs the error to the python shell Ignoring exception in command Mine Traceback (most recent call last): File "C:\Users\raner\AppData\Local\Programs\Python\Python36\lib\site- packages\discord\ext\commands\bot.py", line 846, in process_commands yield from command.invoke(ctx) File "C:\Users\raner\AppData\Local\Programs\Python\Python36\lib\site- packages\discord\ext\commands\core.py", line 367, in invoke yield from self.prepare(ctx) File "C:\Users\raner\AppData\Local\Programs\Python\Python36\lib\site- packages\discord\ext\commands\core.py", line 351, in prepare raise CommandOnCooldown(bucket, retry_after) discord.ext.commands.errors.CommandOnCooldown: You are on cooldown. Try again in 28.58s What I want to do is have something that gets the remaining cooldown and puts it into something that can be said back to the user on discord e.g. 'This command is ratelimited, please try again in 28.58s' I haven't been able to find much help for this online, and most of it is outdated or doesn't seem to work. Thanks!
upvote count: 2
score: 2
type: AnsweredQuestion
tagged with: discord.py
has title: discord.py bot getting cooldown time remaining of command
type: Question
has answer: http://stackoverflow.com/a/52298941
answer count: 1
downvote count: 0

http://stackoverflow.com/q/52360924
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91669425
has comment: http://stackoverflow.com/comment/91666280
has comment: http://stackoverflow.com/comment/91666464
favorite count: 0
has comment: http://stackoverflow.com/comment/91669934
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: Query an array in PyMongo
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52363018
upvote count: 3
tagged with: pymongo
tagged with: django
type: Question
linked to: http://stackoverflow.com/q/52829141
score: 3
has comment: http://stackoverflow.com/comment/91669999
has body: I am trying to query an array using PyMongo and I am getting all the values instead of just the one matching 'A A' Format of Array: "tags": [ { "tag": { "name": "A A" } } ] Python Code: import pymongo from pprint import pprint myclient = pymongo.MongoClient("mongodb://00.00.00.0:27017") mydb = myclient["dbName"] mycol = mydb["thePage"] for x in mycol.find({},{"_id": 0, "tags.tag.name": "A A"}): pprint(x) Result: [{'tag': {'name': 'A A'}}, {'tag': {'name': 'B B'}}, {'tag': {'name': 'C C'}}] Expected Result: {'name': 'A A'} I get the result I need using MongoDB: db.dbName.where("tags.tag.name").eq("A A")
tagged with: mongodb
has answer: http://stackoverflow.com/a/52363018

http://stackoverflow.com/q/52280944
accepted answer: http://stackoverflow.com/a/52281673
has comment: http://stackoverflow.com/comment/91510494
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91510242
has body: I have the following pandas dataframe - Atomic Number R C 0 2.0 49.0 0.040306 1 3.0 205.0 0.209556 2 4.0 140.0 0.107296 3 5.0 117.0 0.124688 4 6.0 92.0 0.100020 5 7.0 75.0 0.068493 6 8.0 66.0 0.082244 7 9.0 57.0 0.071332 8 10.0 51.0 0.045725 9 11.0 223.0 0.217770 10 12.0 172.0 0.130719 11 13.0 182.0 0.179953 12 14.0 148.0 0.147929 13 15.0 123.0 0.102669 14 16.0 110.0 0.120729 15 17.0 98.0 0.106872 16 18.0 88.0 0.061996 17 19.0 277.0 0.260485 18 20.0 223.0 0.164312 19 33.0 133.0 0.111359 20 36.0 103.0 0.069348 21 37.0 298.0 0.270709 22 38.0 245.0 0.177368 23 54.0 124.0 0.079491 The trend between r and C is generally a linear one. What I would like to do if possible is find an exhaustive list of all the possible combinations of 3 or more points and what their trends are with scipy.stats.linregress so that I can find groups of points that fit linearly the best. Which would ideally look something like this for the data, (Source) but I am looking for all the other possible trends too. So the question, how do I feed all the 16776915 possible combinations (sum_(i=3)^24 binomial(24, i)) of 3 or more points into lingress and is it even doable without a ton of code?
tagged with: linear-regression
has comment: http://stackoverflow.com/comment/91510838
type: Question
has comment: http://stackoverflow.com/comment/91510906
upvote count: 4
has comment: http://stackoverflow.com/comment/91510048
has title: Python: Finding multiple linear trend lines in a scatter plot
has answer: http://stackoverflow.com/a/52281673
score: 4
has comment: http://stackoverflow.com/comment/91510835
has comment: http://stackoverflow.com/comment/91511045
has comment: http://stackoverflow.com/comment/91510472
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91510300
has comment: http://stackoverflow.com/comment/91510689
favorite count: 0
has comment: http://stackoverflow.com/comment/91510023

http://stackoverflow.com/comment/91544919
comment on: http://stackoverflow.com/q/52298586
score: 1
type: Comment
type: QuestionComment
has text: Maybe you can find what you need in this link : https://stackoverflow.com/questions/10373247/how-do-i-write-a-python-dictionary-to-a-csv-file

http://stackoverflow.com/q/52403235
has title: Combine two lists without duplicate values
accepted answer: http://stackoverflow.com/a/52411063
score: 7
has answer: http://stackoverflow.com/a/52403390
has answer: http://stackoverflow.com/a/52410776
tagged with: python-2.7
has answer: http://stackoverflow.com/a/62446754
downvote count: 0
answer count: 7
favorite count: 0
has answer: http://stackoverflow.com/a/52403453
has answer: http://stackoverflow.com/a/52403480
possible better answer: http://stackoverflow.com/a/62446754
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52411063
has body: list1 = ["palani", "samy","be"] list2 = ["palani", "samys","be"] def find_common(list1,list2): for x in list1: for y in list2: if x == y : list2.remove(x) print" unique string 1:",list1 print" unique string 2:",list2 print" combained string 2:",list1.append(list2) find_common(list1,list2) Why am I getting None?
has answer: http://stackoverflow.com/a/78400694
upvote count: 7
type: Question

http://stackoverflow.com/comment/91582103
type: QuestionComment
has text: And on gohlke's site you can find a PyMesh wheel.
comment on: http://stackoverflow.com/q/52317268
score: 0
type: Comment

http://stackoverflow.com/q/52292818
tagged with: web-scraping
tagged with: python-requests
type: Question
score: 3
has answer: http://stackoverflow.com/a/52294983
upvote count: 3
answer count: 1
downvote count: 0
has body: I am using the requests library in python and attempting to scrape a website that has lots of public reports and documents in .pdf format. I have successfully done this on other websites, but I have hit a snag on this one: the links are javascript functions (objects? I don't know anything about javascript) that redirect me to another page, which then has the raw pdf link. Something like this: import requests from bs4 import BeautifulSoup as bs url = 'page with search results.com' html = requests.get(url).text soup = bs(html) obj_list = soup.findAll('a') for a in obj_list: link = a['href'] print(link) &gt;&gt; javascript:readfile2("F","2201","2017_2201_20170622F14.pdf") Ideally I would like a way to find what url this would navigate to. I could use selenium and click on the links, but there are a lot of documents and that would be time- and resource-intensive. Is there a way to do this with requests or a similar library? Edit: It looks like every link goes to the same url, which loads a different pdf depending on which link you click. This makes me think that there is no way to do this in requests, but I am still holding out hope for something non-selenium-based.
favorite count: 0
has comment: http://stackoverflow.com/comment/91533566
has title: Webscraping: Downloading a pdf from a javascript link
tagged with: python
has comment: http://stackoverflow.com/comment/91533634
type: UnansweredQuestion

http://stackoverflow.com/a/52409439
accepted answer of: http://stackoverflow.com/q/52408867
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/52408867
score: 2
has body: That is going in the right direction, but the idea is that, instead of having MyCNN produce a single angle value for each example, produce two values. So if the return value of MyCNN is currently something with shape like (None,) or (None, 1), you should change it to (None, 2) - that is, the last layer should have one more output. If you have doubts about how to do this please provide more details about the body of MyCNN. Then you would just have: outs = tf.tanh(logits_CNN[:, 0]) outc = tf.tanh(logits_CNN[:, 1]) out_radians = tf.atan2(outs, outc) # This is the final angle output in radians About the loss, I am not sure I understand your Y input. If you are trying to predict an angle, shouldn't it be a float value, and not an integer? In that case you would have: # Example angle in radians y_CNN = tf.placeholder(tf.float32, (None,)) # ... loss_operation_CNN = tf.reduce_mean(0.5 * (tf.square(tf.sin(y_CNN) - outs) + tf.square(tf.cos(y_CNN) - outc)))
has comment: http://stackoverflow.com/comment/91763421
has comment: http://stackoverflow.com/comment/91763385
has comment: http://stackoverflow.com/comment/91763089
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52276027
upvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/52278878
downvote count: 0
favorite count: 0
has title: Why tarfile module does not allow compressed appending?
tagged with: tarfile
has body: There is no straight way to append to a compressed tar archive. As the documentation states: Note that 'a:gz', 'a:bz2' or 'a:xz' is not possible. As a workaround you can either use the uncompressed append mode 'a' and then handle the compression and decompression yourself, or you can handle the appending yourself and use the compressed read/write modes to recreate the tar archive. My question is: Why does it have to be this complicated? Is there any reason you can think of why the developers would decide to not include the compressed appending mode in the code?
tagged with: python
tagged with: append
score: 2
type: AnsweredQuestion
tagged with: compression
type: Question
linked to: http://stackoverflow.com/q/50464559
accepted answer: http://stackoverflow.com/a/52278878

http://stackoverflow.com/q/52344317
has comment: http://stackoverflow.com/comment/91648784
has title: How can I use Crystal in Python packages/extensions?
linked to: http://stackoverflow.com/q/89228
tagged with: python
score: 2
tagged with: python-3.x
tagged with: crystal-lang
upvote count: 2
has comment: http://stackoverflow.com/comment/91646567
has body: Is it possible to use Crystal in Python3 packages/extensions?
has answer: http://stackoverflow.com/a/52898640
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52898640
has comment: http://stackoverflow.com/comment/91735512
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/q/52380972
score: 16
has comment: http://stackoverflow.com/comment/91706846
upvote count: 16
has answer: http://stackoverflow.com/a/52381213
type: AnsweredQuestion
has title: Numpy filter using condition on each element
has body: I have a filter expression as follows: feasible_agents = filter(lambda agent: agent &gt;= cost[task, agent], agents) where agents is a python list. Now, to get speedup, I am trying to implement this using numpy. What would be the equivalent using numpy? I know that this works: threshold = 5.0 feasible_agents = np_agents[np_agents &gt; threshold] where np_agents is the numpy equivalent of agents. However, I want threshold to be a function of each element in the numpy array.
accepted answer: http://stackoverflow.com/a/52381213
possible better answer: http://stackoverflow.com/a/52381136
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52381136
answer count: 2
has comment: http://stackoverflow.com/comment/91706343
downvote count: 0
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/91706456

http://stackoverflow.com/comment/91644663
has text: You also need to show the contents of the file. Only first few lines.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52349686
score: 0

trace
tag name: trace
type: Tag
tags question: http://stackoverflow.com/q/52365956

http://stackoverflow.com/q/52386747
type: Question
has comment: http://stackoverflow.com/comment/91719424
tagged with: matplotlib
has body: I have a loop which loads and plots some data, something like this: import os import numpy as np import matplotlib.pyplot as plt for filename in filenames: plt.figure() if os.path.exists(filename): x, y = np.loadtxt(filename, unpack=True) plt.plot(x, y) plt.savefig(filename + '.png') plt.close() Now, if the file does not exist, the data is not loaded or plotted but an (empty) figure is still saved. In the above example I could correct for this simply by including all of the plt calls inside of the if statement. My real use case is somewhat more involved, and so I am in search for a way to ask matplotlib/plt/the figure/the axis whether or not the figure/axis is completely empty or not. Something like for filename in filenames: plt.figure() if os.path.exists(filename): x, y = np.loadtxt(filename, unpack=True) plt.plot(x, y) if not plt.figure_empty(): # &lt;-- new line plt.savefig(filename + '.png') plt.close()
tagged with: figure
has answer: http://stackoverflow.com/a/52386892
accepted answer: http://stackoverflow.com/a/52386892
answer count: 3
possible better answer: http://stackoverflow.com/a/52387825
has title: Matplotlib: Check for empty plot
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52386923
tagged with: python
score: 8
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/52387825
upvote count: 8

http://stackoverflow.com/comment/91731578
has text: @Miguel There was an easier way after all. `factorplot` does a better job with the legend but I prefer an axes-level plot for this and the legend can be moved.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52392783
type: Comment

http://stackoverflow.com/q/52283183
has comment: http://stackoverflow.com/comment/91514793
linked to: http://stackoverflow.com/q/7106417
has answer: http://stackoverflow.com/a/52283723
type: Question
has comment: http://stackoverflow.com/comment/91515273
has title: Sort a list according two items inside tuples- Python
has comment: http://stackoverflow.com/comment/91515473
has comment: http://stackoverflow.com/comment/91517887
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91514603
has comment: http://stackoverflow.com/comment/91515279
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91515884
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91514710
has comment: http://stackoverflow.com/comment/91514701
has comment: http://stackoverflow.com/comment/91515358
has body: I will appreciate some help to fix my code and take the right results. Let's say that my lists(tuple inside a list) may have that 3 outputs for example: list1 = [('a', 3.30, '' ,'' ), ('b', 3.20, '' , '' ), ......] list2 = [('a', 3.30, 2.90, '' ), ('b', 3.20, 2.95, '' ), ........] list3 = [('a', 3.30, 2.90, '' ), ('b', 3.20, '' , ''), ........] My lists always have a price in [1] place and sometimes have in [2] place. I want to sort my list according all that prices. My code below works good for example list1 and example list2. from operator import itemgetter sort_list = sorted(list, key=itemgetter(1)) sort_list = sorted(sort_list, key=itemgetter(2)) print(sort_list) But for list3 doesn't work well, because it recognize the empty cell of [2] and it shorted first. I would like to ignore the price of an empty cell, if there is. So the print output for list3 should be ('a', 3.30, 2.90, '' ), ('b', 3.20, '' , ''). Because, 2.90 &lt; 3.20 and I ignore the empty space Thank you
tagged with: python

http://stackoverflow.com/a/52414113
type: Answer
answers question: http://stackoverflow.com/q/52413912
has body: What you're seeing is the string representation of the Element object returned by the builtin repr method, not the content of the root tree. To see the tags in the object try: for child in root: print child.tag, child.attrib Check out the docs for more info on accessing specific tags.
has comment: http://stackoverflow.com/comment/91772160
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52413912
score: 0

http://stackoverflow.com/comment/91535716
type: QuestionComment
has text: @DanielR. Indeed, it was just a matter of importing external data and selecting the comma delimiter. Thank you!
comment on: http://stackoverflow.com/q/52289146
score: 0
type: Comment

http://stackoverflow.com/q/52279722
answer count: 1
downvote count: 0
has title: How to properly use xmlfile api from lxml
favorite count: 0
tagged with: lxml
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
tagged with: python-3.x
has body: I have a large (5+ gigs) XML file which I need to parse, do some operation & write a new XML file. dummy.xml <?xml version="1.0" encoding="UTF-8"?> Product Catalog false product1 false product1 false product1 As you see the above XML has 3 product tags & I need to filter some product-ids on basis of a pre-defined list of ids. I am using lxml iterparse to parse the XML iteratively & want to use xmlfile API to create a new XML incrementally to keep the memory footprint low. So, my motive is to filter out the product tags which don't meet the criteria & copy the rest of the XML tags as it is. from lxml import etree f = './dummy.xml' f1 = './test.xml' context = etree.iterparse(f, events=('start',)) productsToExport = ['1234'] with etree.xmlfile(f1, encoding='utf-8') as xf: xf.write_declaration() with xf.element('catalog xmlns="http://www.namespace.com" catalog-id="test-catalog"'): for event, element in context: tagName = etree.QName(element.tag).localname if (tagName == 'product'): pid = element.get('product-id') if (pid in productsToExport): xf.write(element) elif (tagName == 'header'): xf.write(element) # copy existing header tag as it is Above code works ok & generates a XML as below <?xml version='1.0' encoding='utf-8'?> Product Catalog false product1 If you observe the above XML it has few issues: Closing tag has xmlns & catalog-id present in it All tags like header, product have xmlns attribute present in it I checked xmlfile api documentation but couldn't find a way to fix above issues. EDIT: I managed to resolve the 1st issue by using below attribs = {'xmlns' : 'http://www.namespace.com', 'catalog-id' : 'test-catalog'} with xf.element('catalog', attribs): # previous logic So, now am left with removing the namespace from every element.
upvote count: 3
type: UnansweredQuestion
type: Question
score: 3
has answer: http://stackoverflow.com/a/52285100

http://stackoverflow.com/q/52408991
answer count: 0
has title: Use video from web using OpenCv Python in Linux
upvote count: 1
has body: I'm trying to use opencv to work on the video from web (by the link). In Windows It's running fine. But in Ubuntu with python 3.6 &amp; opencv-contrib-python (latest 3.4.3) is not working(isOpened() -> False). I installed it by pip in an anaconda environment. I can use downloaded video to computer, but I can't use It only by passing link. Sample code: vcap = cv2.VideoCapture('https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_2mb.mp4') if not vcap.isOpened(): print("File Cannot be Opened") while(vcap.isOpened()): ret, frame = vcap.read() cv2.imshow('frame',frame) Is it connected to default compilation? Or any other ideas? Build intormation: General configuration for OpenCV 3.4.3 Version control: 3.4.3 Extra modules: Location (extra): /io/opencv_contrib/modules Version control (extra): 3.4.3 Platform: Timestamp: 2018-09-09T13:49:56Z Host: Linux 4.4.0-101-generic x86_64 CMake: 3.9.0 CMake generator: Unix Makefiles CMake build tool: /usr/bin/gmake Configuration: Release CPU/HW features: Baseline: SSE SSE2 SSE3 requested: SSE3 Dispatched code generation: SSE4_1 SSE4_2 FP16 AVX AVX2 requested: SSE4_1 SSE4_2 AVX FP16 AVX2 AVX512_SKX SSE4_1 (3 files): + SSSE3 SSE4_1 SSE4_2 (1 files): + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 (1 files): + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 AVX AVX (5 files): + SSSE3 SSE4_1 POPCNT SSE4_2 AVX AVX2 (9 files): + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2 C/C++: Built as dynamic libs?: NO C++ Compiler: /opt/rh/devtoolset-2/root/usr/bin/c++ (ver 4.8.2) C++ flags (Release): -Wl,-strip-all -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winit-self -Wno-narrowing -Wno-delete-non-virtual-dtor -Wno-comment -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections -msse -msse2 -msse3 -fvisibility=hidden -fvisibil…
type: Question
tagged with: opencv
score: 1
tagged with: video-capture
downvote count: 0
favorite count: 0
tagged with: linux
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91579452
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52313176
type: Comment
has text: @IljaEverilä: this exposes a different issue: passing in a DBAPI2 connection *may* work, but only SQLite3 is actually supported, and there may well be issues with type conversions.

http://stackoverflow.com/q/52342533
upvote count: 1
type: Question
tagged with: pyspark
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52343145
has title: Python Mock not getting assigned for class
accepted answer: http://stackoverflow.com/a/52343145
score: 1
tagged with: python-unittest
has body: I have my python class class FetchData: def __init__(self, spark): self.spark = spark def filter_data_from_s3(self, table_name, s3_location, sql_query, table_schema, partition_column): # DO SOMETHING Another file which calls this class is FilterData.py from accessor.FetchData import FetchData from pyspark.sql import SparkSession import sys def main(args): spark = SparkSession \ .builder \ .appName("ROAD") \ .config(conf=sparkConf) \ .getOrCreate() try: args_map = DataUtils.parse_args(args) logger.info("Parsed Argument Map for Filtering Data : {}".format(args_map)) f = FetchData(spark) for table in table_list: table_name = table.get("table_name") s3_location = table.get("s3_location") sql_query = DataUtils.un_parametrize(table.get("sql_query"), args_map) table_schema = table.get("table_schema", args) f.filter_data_from_s3(table_name=table_name, s3_location=s3_location, sql_query=sql_query, table_schema=table_schema, partition_column=args_map.get('partition_column')) finally: spark.stop() if __name__ == "__main__": main(sys.argv) I have written a test case to test filterData.py main function I want to mock filter_data_from_s3 call. Here is the test case i have written - class TestFilterData(unittest.TestCase): @patch('accessor.FetchData') def test_main_call_times_for_na(self, fetch_data_mock): print(fetch_data_mock) spark_session = get_spark_session() CUSTOMER_ACCESS_SCHEMA = StructType( [StructField('enc_customer_id', StringType(), False), StructField('marketplace_id', IntegerType(), False)] ) df = spark_session.createDataFrame([ ("customerid1", 1), ("customerid1", 2), ("customerid2", 2) ], CUSTOMER_ACCESS_SCHEMA) fetch_data_mock.filter_data_from_s3.return_value = df test_args = ["", "--run_date=2018-09-01", "--num_days=730", "--region=NA", "--marketplace_id=1", "--region_id=1", "--num_asins=1000"] FilterData.main(test_args) if __name__ == '__main__': unittest.main() When i call my test case, it actually makes call to filter data and fails. Rather I want my mock meth…

http://stackoverflow.com/comment/91520030
has text: Put that in the question please. I'll edit in short order.
type: Comment
comment on: http://stackoverflow.com/a/52285814
type: AnswerComment
score: 1

http://stackoverflow.com/q/52351426
has answer: http://stackoverflow.com/a/52352973
tagged with: python
has title: for loop & nested list; sample median
type: UnansweredQuestion
upvote count: 1
downvote count: 1
type: Question
tagged with: numpy
has body: I am in an introductory course for python so I'm not really sure how to frame the question, but this is what I have: samplesize_list = [[1, 5, 10], [2, 4, 7], [3, 4, 6]] label_List = ['size16', 'size13', 'size13'] std_list = [50, 30, 60] mean_list = [100, 80, 70] repeat = 50 What I want to do is loop through the nested list to visualise sample distribution of the sample median of each sample size such that: size16 refers to [1, 5, 10] and std_list of 50 and mean_list of 100 applies to each element of that list. What I should get: 3 graphs of size16, size13 and size13 each visualising the sample distribution of the sample median in each respective sample size. What I did: repeat_median = np.empty(repeat, dtype = float) for j in samplesize_list: for i in range(len(samplesize_list[i])): size = samplesize_list[j] for i in range(repeat): sample_data = np.random.normal(mean_list[j], std_list[j], size) repeat_median[i] = np.median(sample_data) plt.subplot(len(samplesize_list), 1, j+1) sns.distplot(repeat_median, color = 'blue', label = label_list[j]) plt.legend(loc = "upper right") plt.show() I'm not sure what I'm missing or where I've went wrong. Would be nice to get some help on this! Note: in the samplesize_list, [1, 5, 10] refers to the number of people in each age group that makes up the sample.
score: 0
answer count: 1
favorite count: 0
tagged with: statistics

http://stackoverflow.com/comment/91696855
type: QuestionComment
has text: I've plugged in your answer and it works, and yeah I've realised that in the code few different places where the ( was... (\d+\S+).
score: 0
comment on: http://stackoverflow.com/q/52375873
type: Comment

http://stackoverflow.com/a/68296127
has comment: http://stackoverflow.com/comment/120703150
upvote count: 1
score: 1
has body: Please follow the steps to add a customize configuration file for default properties Create behave.ini file and features file at the same level set properties in this file, which you want to run default, for example i have set default_tags=@defaulttag Now when i run the behave command, then it execute only scenario that has a tag @defaulttag
downvote count: 0
answers question: http://stackoverflow.com/q/52368151
type: Answer

http://stackoverflow.com/comment/91731862
has text: Could you define a `@staticmethod` like `def validate_url(url, *args)` that runs inside of `some_func`? You could then decorate `validate_url`. Seems hacky and non-Pythonic, but that's the first thing I'd try
comment on: http://stackoverflow.com/q/52391727
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91771142
type: AnswerComment
comment on: http://stackoverflow.com/a/52413671
type: Comment
has text: The initialization method is not part of your timing, so that doesn't affect the question.
score: 0

http://stackoverflow.com/q/52289385
has body: I want to upload Image to my database. I can do it by using ModelSerializer. No problem, but if I want to pass using serializers.Serializer. So my serializers.py looks like this: class QuestionSerializer(serializers.Serializer): image = serializers.ImageField() name = serializers.CharField(max_length=120) And my models.py looks like this: class UploadedImage(models.Model): image = models.ImageField("Uploaded image", upload_to=scramble_uploaded_filename) name = models.CharField(max_length=120) And views.py: class UploadedImagesViewSet(viewsets.ModelViewSet): queryset = UploadedImage.objects.all() serializer_class = QuestionSerializer def create(self,request): serializer1 = self.get_serializer(data=request.data) serializer.is_valid() data = serializer1.data print(data) img,iss = UploadedImage.objects.get_or_create(name=data['name'],defaults={'image':files['image']}) return Response("UploadedImage") In views.py when i do data=request.data it shows keyError in image When I do data=request.FILES it shows KeyErrorIn name. How can I fix this error? How can I upload image and save name in database? traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/upload/ Django Version: 2.0.7 Python Version: 3.6.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'app1', 'practice'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/query.py" in get_or_create 487. return self.get(**lookup), Fal…
has title: KeyError when use request.data and request.FILES?
score: 0
has comment: http://stackoverflow.com/comment/91547902
has comment: http://stackoverflow.com/comment/91528101
answer count: 1
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/91527982
has answer: http://stackoverflow.com/a/52290746
type: UnansweredQuestion
tagged with: python
tagged with: django
type: Question

http://stackoverflow.com/q/52316522
score: 1
upvote count: 1
type: Question
answer count: 1
downvote count: 0
favorite count: 0
has body: In my denary to binary converter it seems to take in the users input and work out if it needs to add 0's or 1's. But it doesnt come out with any output at the end. def converter(denarynumber): binarylist = [] while (denarynumber &gt; 0): if denarynumber % 2 &gt; 0: binarylist.append(1) elif denarynumber % 2 == 0: binarylist.append(0) denarynumber // 2 denarynumber = int(denarynumber) print(binarylist[::-1]) def main(): print("This is a dec. to bin. converter") denarynumber = int(input("Please enter your denary number:")) converter(denarynumber) main()
has answer: http://stackoverflow.com/a/52316646
type: UnansweredQuestion
tagged with: python
has title: Denary to Binary converter comes with no output

string
tags question: http://stackoverflow.com/q/52378945
tags question: http://stackoverflow.com/q/52338346
tags question: http://stackoverflow.com/q/52427367
tags question: http://stackoverflow.com/q/52377285
tags question: http://stackoverflow.com/q/52426807
tags question: http://stackoverflow.com/q/52302509
tags question: http://stackoverflow.com/q/52280146
tags question: http://stackoverflow.com/q/52295246
tags question: http://stackoverflow.com/q/52396975
tags question: http://stackoverflow.com/q/52277302
tags question: http://stackoverflow.com/q/52401194
tags question: http://stackoverflow.com/q/52340963
tags question: http://stackoverflow.com/q/52297699
tags question: http://stackoverflow.com/q/52396365
tags question: http://stackoverflow.com/q/52424772
tags question: http://stackoverflow.com/q/52395030
tags question: http://stackoverflow.com/q/52365750
tags question: http://stackoverflow.com/q/52412990
tags question: http://stackoverflow.com/q/52401762
tags question: http://stackoverflow.com/q/52299774
tags question: http://stackoverflow.com/q/52317879
tags question: http://stackoverflow.com/q/52316625
tags question: http://stackoverflow.com/q/52417206
tags question: http://stackoverflow.com/q/52300258
tags question: http://stackoverflow.com/q/52406584
tags question: http://stackoverflow.com/q/52328683
tags question: http://stackoverflow.com/q/52347366
tags question: http://stackoverflow.com/q/52358507
tags question: http://stackoverflow.com/q/52280878
tags question: http://stackoverflow.com/q/52396963
tags question: http://stackoverflow.com/q/52315034
tag name: string
tags question: http://stackoverflow.com/q/52293488
tags question: http://stackoverflow.com/q/52353953
tags question: http://stackoverflow.com/q/52291519
tags question: http://stackoverflow.com/q/52372746
tags question: http://stackoverflow.com/q/52386589
tags question: http://stackoverflow.com/q/52338795
tags question: http://stackoverflow.com/q/52285502
tags question: http://stackoverflow.com/q/52396291
tags question: http://stackoverflow.com/q/52414577
tags question: http://stackoverflow.com/q/52415497
tags question: http://stackoverflow.com/q/52371382
tags question: http://stackoverflow.com/q/52280087
tags question: http://stackoverflow.com/q/52298345
tags question: http://stackoverflow.com/q/52279061
type: Tag
tags question: http://stackoverflow.com/q/52355260
tags question: http://stackoverflow.com/q/52325560
tags question: http://stackoverflow.com/q/52348506
tags question: http://stackoverflow.com/q/52427538
tags question: http://stackoverflow.com/q/52353743
tags question: http://stackoverflow.com/q/52292286
tags question: http://stackoverflow.com/q/52366997
tags question: http://stackoverflow.com/q/52360537
tags question: http://stackoverflow.com/q/52309339
tags question: http://stackoverflow.com/q/52412777
tags question: http://stackoverflow.com/q/52401280
tags question: http://stackoverflow.com/q/52420009
tags question: http://stackoverflow.com/q/52355710
tags question: http://stackoverflow.com/q/52377789
tags question: http://stackoverflow.com/q/52299082
tags question: http://stackoverflow.com/q/52371062
tags question: http://stackoverflow.com/q/52382780
tags question: http://stackoverflow.com/q/52273148
tags question: http://stackoverflow.com/q/52351508
tags question: http://stackoverflow.com/q/52285759
tags question: http://stackoverflow.com/q/52415373
tags question: http://stackoverflow.com/q/52354518
tags question: http://stackoverflow.com/q/52346168
tags question: http://stackoverflow.com/q/52284968
tags question: http://stackoverflow.com/q/52426777
tags question: http://stackoverflow.com/q/52273275
tags question: http://stackoverflow.com/q/52395578
tags question: http://stackoverflow.com/q/52368556
tags question: http://stackoverflow.com/q/52323971
tags question: http://stackoverflow.com/q/52342084
tags question: http://stackoverflow.com/q/52371125
tags question: http://stackoverflow.com/q/52407819

switch-statement
tags question: http://stackoverflow.com/q/52321021
type: Tag
tag name: switch-statement

http://stackoverflow.com/q/52344777
tagged with: arduino-esp8266
downvote count: 0
tagged with: esp8266
tagged with: udp
has title: How can I debug latency in a UDP multicast request/reply?
has body: I'm building a real-time wireless link between a PC base station and a dozen robots, each transmitting at 60Hz. For testing I wrote a Python script that sends UDP multicast packets over my WiFi network. And then on another multicast group I have two ESP8266 sending replies. One sends at 60Hz to simulate the real set-up, and the other spams at 10 times that rate to simulate congestion from the other devices. First I only looked at packet loss, which was kind of as expected. But then I started to look at round-trip time. I made my Python script write the current time, and made the "real" node echo them back. (spammer messages are ignored) With the spammer node turned off I get 10ms round-trip, but with the spammer, it starts at 100ms and slowly grows to over a second. How can I debug this issue? I tried to use Wireshark, but since they are separate UDP streams with custom data in them, I could not figure out any sensible analysis. I figured the packets probably get stuck in a queue somewhere, so some googling suggested you can look at the queue length with the following command. Sure, the queue is not empty, but if I turn the spammer node off, nothing much changes in the queue length, while round-trip drops back to 10ms. netstat -c --udp -an Proto Recv-Q Send-Q Local Address Foreign Address State udp 40256 0 0.0.0.0:8080 0.0.0.0:* I thought maybe my Python code is just too slow to handle 600 messages per second. Running on PyPy made absolutely no difference, so I'm a bit hesitant to write the whole thing in C. It has almost 2ms per packet to do almost nothing. Base station code: import socket import struct import sched, time import threading base_multicast = '239.255.0.34' robot_multicast = '239.255.0.35' port = 8080 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', port)) mreq = struct.pack("4sl", socket.inet_aton(robot_multicast), socket.INADDR_ANY) sock.setsockopt(so…
favorite count: 0
tagged with: multicast
has comment: http://stackoverflow.com/comment/92712689
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
type: Question

http://stackoverflow.com/q/52341073
type: AnsweredQuestion
upvote count: 10
type: Question
has comment: http://stackoverflow.com/comment/91638875
has comment: http://stackoverflow.com/comment/91655044
answer count: 2
downvote count: 0
score: 10
tagged with: database
possible better answer: http://stackoverflow.com/a/54714011
tagged with: postgresql
has answer: http://stackoverflow.com/a/52355991
has answer: http://stackoverflow.com/a/54714011
tagged with: sql
has title: psycopg2 - Using SQL object with execute_values
has comment: http://stackoverflow.com/comment/91630811
favorite count: 0
tagged with: python
tagged with: psycopg2
has body: I'm inserting data using execute_values, which takes a sql query. The query is constructed using psycopg2.sql.SQL as recommended in the documentation, but execute_values won't take that object. Here's the code I have: import psycopg2 as pg from psycopg2 import extras from psycopg2 import sql config = { 'host' : 'localhost', 'user' : 'username', 'password' : 'password', 'dbname' : 'myDatabase' } connection = pg.connect(**config) cursor = connection.cursor() tableName = 'myTable' dataset = [[1,2],[3,4],[5,6]] queryText = "INSERT INTO {table} (uid,value) VALUES %s" query = sql.SQL(queryText).format(table=sql.Identifier(tableName)) extras.execute_values(cursor,query,dataset) The last line gives the following error: AttributeError: 'Composed' object has no attribute 'encode' If the query is specified directly as a string, as below, then the execution runs. query = """INSERT INTO "myTable" (uid,value) VALUES %s""" It's possible to insert the table name into the query using string format, but apparently that shouldn't be done, even at gunpoint. How can I safely insert a variable table name into the query and use execute_values? I can't find a built-in way to convert the SQL object to a string.
has comment: http://stackoverflow.com/comment/91655015
accepted answer: http://stackoverflow.com/a/52355991

http://stackoverflow.com/a/52413294
type: Answer
answers question: http://stackoverflow.com/q/52299118
has body: It turns out it was just a bug. The solution was simple, I copied my script to a new file, deleted the old one and it worked, simple as that.
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/52299118

http://stackoverflow.com/comment/91725512
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52390125
has text: Is this your special requirement to iterate over list on indexes 1,3,5.... Not on 0,2,4,6..... Consider if blender comes at index either 0,2,4,6... of any one List then will it not be considered as common element on lists??
type: Comment

http://stackoverflow.com/comment/91773442
comment on: http://stackoverflow.com/q/52414766
type: Comment
type: QuestionComment
has text: That return format is a mess, I can't imagine it's some standard :/
score: 1

http://stackoverflow.com/comment/91518350
score: 0
type: QuestionComment
has text: Use the string module?
type: Comment
comment on: http://stackoverflow.com/q/52284968

http://stackoverflow.com/comment/133620286
comment on: http://stackoverflow.com/a/57484556
has text: Doesn't work for me, also I don't see anywhere a command to replace text.
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/91581080
score: 2
has text: Can you just use polar coordinates with random angle and radius?
comment on: http://stackoverflow.com/q/52316725
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52311339
upvote count: 6
has body: I have a simple program to run 8 processes, It remarkably reduces the script running time by using multiprocessing, however, I am not sure how many processes should I put to maximum my CPU utilization. Currently my cpu is 6 cores with only 1 physical cpu as it is a VPS. : def spider1(): def spider2(): def spider3(): def spider4(): def spider5(): def spider6(): def spider7(): def spider8(): if __name__ == '__main__': p1 = multiprocessing.Process(target=spider1,) p2 = multiprocessing.Process(target=spider2,) p3 = multiprocessing.Process(target=spider3,) p4 = multiprocessing.Process(target=spider4, ) p5 = multiprocessing.Process(target=spider5, ) p6 = multiprocessing.Process(target=spider6, ) p7 = multiprocessing.Process(target=spider7, ) p8 = multiprocessing.Process(target=spider8, ) p1.start() p2.start() p3.start() p4.start() p5.start() p6.start() p7.start() p8.start()
has comment: http://stackoverflow.com/comment/91570008
downvote count: 1
has comment: http://stackoverflow.com/comment/91569795
has comment: http://stackoverflow.com/comment/91570489
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/91570440
has comment: http://stackoverflow.com/comment/91570359
has comment: http://stackoverflow.com/comment/91570388
has comment: http://stackoverflow.com/comment/91570807
has comment: http://stackoverflow.com/comment/91570203
has title: Python 3 Multiprocessing - How many processes should I use?
linked to: http://stackoverflow.com/q/42103367
tagged with: web-crawler
has answer: http://stackoverflow.com/a/52312038
has answer: http://stackoverflow.com/a/52311581
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/91570746
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91572271
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91570656
tagged with: python

http://stackoverflow.com/comment/91716649
type: Comment
has text: i would be happy to help. But: please provide something we can reproduce(https://stackoverflow.com/help/mcve) for example, give us the right DataFrame with the right names on the columns. also i don't see the `w.observe(update_plot, names="selected_label")` in your code, did you have it when you test the code?
score: 0
comment on: http://stackoverflow.com/q/52380997
type: QuestionComment

http://stackoverflow.com/comment/91538041
type: QuestionComment
comment on: http://stackoverflow.com/q/52295245
score: 1
has text: The subclassing was removed: https://docs.djangoproject.com/en/dev/internals/deprecation/#deprecation-removed-in-1-10
type: Comment

http://stackoverflow.com/comment/91552250
has text: Yes, it uses the `re` library in fact. But you have to set the flag `regex=True`
comment on: http://stackoverflow.com/a/52302095
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52346525
tagged with: http://stackoverflow.com/tag/r
has title: Rpubs equivalence for Python
answer count: 1
tagged with: python
tagged with: jupyter
favorite count: 0
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/52347709
upvote count: 3
accepted answer: http://stackoverflow.com/a/52347709
type: AnsweredQuestion
score: 3
has body: Rpubs works great for sharing and posting r presentations. Is there an equivalent site for python, or more specifically Jupyter notebooks?
type: Question
downvote count: 0
tagged with: markdown

http://stackoverflow.com/q/52360834
type: Question
has comment: http://stackoverflow.com/comment/91667473
has comment: http://stackoverflow.com/comment/91666037
has comment: http://stackoverflow.com/comment/91665999
has comment: http://stackoverflow.com/comment/91665974
has comment: http://stackoverflow.com/comment/91667117
tagged with: numpy
has comment: http://stackoverflow.com/comment/91668598
score: 0
tagged with: array-broadcasting
has comment: http://stackoverflow.com/comment/91738376
has comment: http://stackoverflow.com/comment/91667850
has comment: http://stackoverflow.com/comment/91666193
has comment: http://stackoverflow.com/comment/91666294
linked to: http://stackoverflow.com/q/41102645
has comment: http://stackoverflow.com/comment/91666055
tagged with: python
linked to: http://stackoverflow.com/q/49467836
has body: I have two arrays like a == array([[x0, y0], [x1, y1], ... ,[xn, yn]]) b == array([[u0, v0], [u1, v1], ... ,[un, vn]]) e.g. for (x0, y0) in a, I need to find its closest correspondent (e.g. based on Euclidean distance) on b, and I need to do this for all elements in a. What's the fastest way in python?
duplicate of: http://stackoverflow.com/q/41102645
has comment: http://stackoverflow.com/comment/91667622
answer count: 0
has comment: http://stackoverflow.com/comment/91713268
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91666020
has comment: http://stackoverflow.com/comment/91666231
has comment: http://stackoverflow.com/comment/91667681
linked to: http://stackoverflow.com/q/52366421
has title: Numpy, for each element of one array, find its closest point in another array

http://stackoverflow.com/comment/91687837
has text: `message = " Hello World! "` here you can add your dynamic message such sync status.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52371593
type: Comment

http://stackoverflow.com/comment/91619628
comment on: http://stackoverflow.com/q/52335731
type: Comment
has text: can you guys help me now to solve it with efficiency?
score: 0
type: QuestionComment

http://stackoverflow.com/q/52340535
upvote count: 2
tagged with: oauth-2.0
tagged with: python-requests
tagged with: urllib
type: Question
has title: Valid, working domain gives "socket.gaierror: [Errno -2] Name or service not known"
downvote count: 0
has body: I'm working on a project in which I need to implement SSO. My SSO OAuth2 credentials are along the lines of: SECRET = 'abcdefghijklmn12345678' ACCESS_TOKEN_URL = "https://myprovider.example.com/as/token.oauth2" USER_API_URL = "https://myprovider.example.com/idp/userinfo.openid" JWKS_URL = "https://myprovider.example.com/pf/JWKS" REDIRECT_URI = "http://localhost/api/1/auth/ping" AUTH_ENDPOINT = "https://myprovider.example.com/as/authorization.oauth2" The library I am using has been tested and should work, but for some reason fails with: [2018-09-13 14:09:29,796] ERROR in app: Exception on /api/1/auth/ping [POST] Traceback (most recent call last): File "/www/lemur/lib/python3.6/site-packages/urllib3/connection.py", line 171, in _new_conn (self._dns_host, self.port), self.timeout, **extra_kw) File "/www/lemur/lib/python3.6/site-packages/urllib3/util/connection.py", line 59, in create_connection for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): File "/usr/lib/python3.6/socket.py", line 745, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -2] Name or service not known During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/www/lemur/lib/python3.6/site-packages/urllib3/connectionpool.py", line 600, in urlopen chunked=chunked) File "/www/lemur/lib/python3.6/site-packages/urllib3/connectionpool.py", line 343, in _make_request self._validate_conn(conn) File "/www/lemur/lib/python3.6/site-packages/urllib3/connectionpool.py", line 849, in _validate_conn conn.connect() File "/www/lemur/lib/python3.6/site-packages/urllib3/connection.py", line 314, in connect conn = self._new_conn() File "/www/lemur/lib/python3.6/site-packages/urllib3/connection.py", line 180, in _new_conn self, "Failed to establish a new connection: %s" % e) urllib3.exceptions.NewConnectionError: &lt;urllib3.connection.VerifiedHTTPSConnection object at 0x7fc15ed415f8&gt;: Fail…
favorite count: 0
type: UnansweredQuestion
tagged with: sockets
tagged with: python
score: 2
answer count: 0

http://stackoverflow.com/a/52376263
accepted answer of: http://stackoverflow.com/q/52357753
answers question: http://stackoverflow.com/q/52357753
score: 4
type: AcceptedAnswer
downvote count: 0
has body: I finally fixed the issue: by changing the os directory to the one of my env (os.chdir) using chown/chmod to give edit/create rights to www-data
type: Answer
upvote count: 4

http://stackoverflow.com/a/52406569
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52363163
accepted answer of: http://stackoverflow.com/q/52363163
has body: There were two problems regarding this issue. The solution @martineau offered has to be applied. However this is not enough. The annotation tool VIA has changed JSON formatting in later versions, apparently. Now instead of a dictionary, "regions" has a list. This means, if you somehow try to read them into polygons you need to remove '.values()' addition in your line, which should look like the following in any occasion. polygons = [r['shape_attributes'] for r in a['regions']] names = [r['region_attributes'] for r in a['regions']] and not polygons = [r['shape_attributes'] for r in a['regions'].values()] names = [r['region_attributes'] for r in a['regions'].values()]

http://stackoverflow.com/q/52336862
has comment: http://stackoverflow.com/comment/91621024
has comment: http://stackoverflow.com/comment/91620977
has comment: http://stackoverflow.com/comment/91620978
has comment: http://stackoverflow.com/comment/91620944
downvote count: 4
upvote count: 0
answer count: 1
favorite count: 0
has body: Why is this wrong? I had ran it before and it worked but for some reason now it isn't running. It's very easy and I'm a beginner so I'm struggling to figure it out. def checkTemp(x): if x == 0: return 0 elif x &gt; 32: return 'above' elif x == 32: return 'freezing' elif x &lt; 32: return 'below' def aboveBelowFreeze(tempList): ''' Given a list of temperatures, return a list of strings that say 'above', 'below', or 'freezing', depending on whether the temperature was above 32, below 32, or equal to 32. Create a helper function if you need it. ''' return ([checkTemp(x) for x in tempList])
accepted answer: http://stackoverflow.com/a/52336946
tagged with: python
type: AnsweredQuestion
has title: Simple Python Question w/ List Comprehension
type: Question
score: -4
tagged with: python-3.6
has answer: http://stackoverflow.com/a/52336946

http://stackoverflow.com/a/52273888
type: Answer
upvote count: 2
has body: I'm sorry to say that probably there isn't a simple and easy way to go with something like this: Since you're dealing with a database I will assume you have a wide range of possible questions, and that using a simple synonym table will not do Natural Language Processing (NLP) This is a very active research topic in Machine Learning and, in a nutshell, deals with automatically making sense from text. For your particular scenario. To get some intuition about it, and because it applies perfectly to your question, I would recommend starting with: Question Similarity Calculation for FAQ Answering by Song et al. (2007) For a state-of-the-art tool that will help with your application, I suggest word2vec (that's the paper, but you might also want to follow a tutorial. Other options If NLP looks more complex than what you're aiming for, I would suggest looking at word similarities, such as: Levenshtein distance Hamming distance These, however, will not perform as well as a well trained NLP system.
score: 2
answers question: http://stackoverflow.com/q/52273070
downvote count: 0

http://stackoverflow.com/a/52396100
has comment: http://stackoverflow.com/comment/91843535
type: Answer
answers question: http://stackoverflow.com/q/52396039
upvote count: 3
has comment: http://stackoverflow.com/comment/91845014
score: 3
has body: You can use zip and sum for a functional solution: # don't shadow the built-in `list` l = [7,5,9,4,7,11] # generate all neighboring pairs pairs = zip(l, l[1:]) # generate all sums of pairs sums = list(map(sum, pairs)) print(sums) # [12, 14, 13, 11, 18]
downvote count: 0

http://stackoverflow.com/q/52354098
type: AnsweredQuestion
has title: python unknown label type error in a np array
type: Question
has body: I wanted to make a classification task by using scikit. The dataset that I am working on is the concrete dataset available at: https://archive.ics.uci.edu/ml/datasets/Concrete+Compressive+Strength My code is the following: import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier data=np.genfromtxt("Concrete_Data.csv",delimiter=",") X=data[:,:-1] y=data[:,-1] X_train,X_test,y_train,y_test=train_test_split(X,y) mlp=MLPClassifier(solver="adam",alpha=1e-5,activation='relu',max_iter=1000) mlp.fit(X_train,y_train) But when I run it I got the following message error: Unknown label type: (array([41.05, 67.11, 9.87, 43.38, 11.98, 19.99, 13.46, 35.1 , 28.6 , 36.8 , 17.58, 31.65, 34.49, 31.9 , 18. , 55.65, 40.66, 53.96, I have tried converting X and y by using astype(float), but when I use type() I can see that the arrays are of type &lt;type 'numpy.ndarray'&gt;. I have also checked the dimensions of the arrays and still got that message. How can I fix that? Thanks
answer count: 1
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/52354219
score: 0
has answer: http://stackoverflow.com/a/52354219
tagged with: python

http://stackoverflow.com/comment/112583217
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52279902
has text: https://stackoverflow.com/a/60186800/10375049
score: 0

http://stackoverflow.com/a/52686524
has comment: http://stackoverflow.com/comment/106262022
upvote count: 2
has comment: http://stackoverflow.com/comment/109439309
accepted answer of: http://stackoverflow.com/q/52341979
has body: The problem lies in the Pycharm 'limit' of managing a docker machine on a remote host 'under the hood'. When inserting the volume mapping in the run / debug configuration, it is interpreted as a local path and therefore, in this case, a path that must be present on the remote server. So, for now, the only option is to mount the local path (the folder where the project is located) on the remote host of the Docker service by first sharing it through an SSHFS or NFS service. So ... (1) I shared the Pycharm project folder (local machine ip 192.168.1.10) using NFS; (2) I mounted the shared folder on the server host (on server ip 192.168.1.22; mount -t nfs 192.168.1.10:/home/user/PythonProjects /home/ext-user/mnt/projects) then (3) in the run / debug configuration of Pycharm I mapped the volumes with the path mounted on the remote server ... Run ... the program now runs without any errors. [Run result] These are some specifications of my new configuration: Run/Debug Configuration docker container setting with volume mapping into Run/Debug Configuration I hope the solution can be useful to other people. I also hope that there are better solutions than mine :-)
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52341979
score: 2

http://stackoverflow.com/a/52284572
has body: The User model (user/models.py) should be imported somewhere in the application, try to import into the blueprint file (user/__init__.py) from flask import Blueprint from app.user.models import User bp = Blueprint('user', __name__)
answers question: http://stackoverflow.com/q/52282907
score: 0
has comment: http://stackoverflow.com/comment/91528658
type: Answer

http://stackoverflow.com/q/52356112
has title: Scope of variables (with threads)
answer count: 1
has comment: http://stackoverflow.com/comment/91657562
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/91657486
tagged with: multithreading
has body: I have the following code in two modules. Module "main": #!/usr/bin/python import threading import b a = 0 def api_a(): global a print("api_a()") a = 1 def main(): global a thread_B = b.B_thread() print("a = " + str(a)) thread_B.start() # api_a() thread_B.join() print("a = " + str(a)) if __name__ == '__main__': main() Module "B": #!/usr/bin/python import threading import main class B_thread (threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): print("Starting " + self.name) B_process() print("Exiting " + self.name) def B_process(): main.api_a() If I run this code I get: a = 0 Starting Thread-1 api_a() Exiting Thread-1 a = 0 Why is variable "a" not set to "1" ? If I activate the commented line of code in Module "main" ( api_a() ) the variable "a" will be set to "1". Why is the variable not set when the function api_a() is called via the thread? In the example code I skipped the use of locks to make the code thread-safe. Any ideas? Thanks a lot in advance, Thomas
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/91684649
has answer: http://stackoverflow.com/a/52358700
has comment: http://stackoverflow.com/comment/91657774

http://stackoverflow.com/a/52316646
downvote count: 0
has comment: http://stackoverflow.com/comment/91581101
has comment: http://stackoverflow.com/comment/91580778
type: Answer
has body: Inside yout while loop you are dividing denarynumber but you are not updating its value, causing an infinite loop Try changing denarynumber // 2 to denarynumber = denarynumber // 2
score: 2
answers question: http://stackoverflow.com/q/52316522
has comment: http://stackoverflow.com/comment/91580731
has comment: http://stackoverflow.com/comment/91581152
upvote count: 2

http://stackoverflow.com/comment/91608110
has text: Are there any other files in the directory with name pygame.py ? Cause the error is `NameError` and not a `ModuleNotFoundError`
type: AnswerComment
comment on: http://stackoverflow.com/a/52330669
score: 0
type: Comment

http://stackoverflow.com/comment/91710352
has text: If you try to fetch the given link in shell, you'll come to know my problem. That pop windows doesn't allow me to extract the data and that's why I'm getting nothing
comment on: http://stackoverflow.com/a/52382116
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91685505
has text: Can you provide sample data an expected ouput?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52370351

http://stackoverflow.com/a/52272913
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52272831
type: Answer
has body: To get full results, you can use the following regex : (?:\d+[ $%./-]?)+ It capture sequences of number possibly separated by a single consecutive numeric separator. This captures dates, numbers with single spaces as thundreds separators and currency/percentage signs, but will avoid matching 1. 2 in sentence 1. 2nd sentence and leaves the possibility to use multiples spaces to separate numbers. To include the two previous words, you can use this one : [^\d ]+ [^\d ]+ (?:\d+[ $%./-]?)+ It just captures two sequences of non-numeric characters separated by space before continuing with the previous regex. (note that in the case of the account number, it will only capture "no is ") Try it online !
upvote count: 2

http://stackoverflow.com/comment/91831690
type: Comment
comment on: http://stackoverflow.com/q/52374287
score: 0
has text: @UmangGupta Just now I tried so.The Usage began floating between 74%-85% ,sometimes it reaches 90+%.Not sure whether a much larger batch would stop the usage floating.that's not the solution I expected but still helpful,thanks.
type: QuestionComment

http://stackoverflow.com/a/52386118
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52381909
type: Answer
upvote count: 1
has body: I've overridden the classmethod "create" of tg.renderers.jinja.JinjaRenderer config/Jinja.py try: import jinja2 except ImportError: # pragma: no cover jinja2 = None if jinja2 is not None: from jinja2.loaders import FileSystemLoader from jinja2 import ChoiceLoader, Environment from jinja2.filters import FILTERS from jinja2.exceptions import TemplateNotFound else: # pragma: no cover class FileSystemLoader(object): pass from tg.renderers.base import RendererFactory from tg.renderers.jinja import JinjaRenderer as jr from tg.renderers.jinja import DottedTemplateLoader from tg.i18n import ugettext, ungettext class JinjaRenderer(jr): @classmethod def create(cls, config, app_globals): """Setup a renderer and loader for Jinja2 templates.""" if jinja2 is None: # pragma: no cover return None if config.get('use_dotted_templatenames', True): TemplateLoader = DottedTemplateLoader template_loader_args = {'dotted_finder': app_globals.dotted_filename_finder} else: TemplateLoader = FileSystemLoader template_loader_args = {} if not 'jinja_extensions' in config: config['jinja_extensions'] = [] # Add i18n extension by default if not "jinja2.ext.i18n" in config['jinja_extensions']: config['jinja_extensions'].append("jinja2.ext.i18n") if not 'jinja_filters' in config: config['jinja_filters'] = {} loader = ChoiceLoader( [TemplateLoader(path, **template_loader_args) for path in config['paths']['templates']]) def my_finalize(thing): return thing if thing is not None else '' jinja2_env = Environment(loader=loader, autoescape=True, finalize=my_finalize, auto_reload=config['auto_reload_templates'], extensions=config['jinja_extensions']) # Try to load custom filters module under app_package.lib.templatetools try: if not config['package_name']: raise AttributeError() filter_package = config['package_name'] + ".lib.templatetools" autoload_lib = __import__(filter_package, {}, {}, ['jinja_filters']) try: autoload_filters = dict( map(lambda x: (x, autoload_lib.jinja_filters.__dict__[x]), autoload_lib…

flask
tags question: http://stackoverflow.com/q/52286507
tags question: http://stackoverflow.com/q/52341937
tags question: http://stackoverflow.com/q/52415384
tags question: http://stackoverflow.com/q/52283598
tags question: http://stackoverflow.com/q/52293162
tags question: http://stackoverflow.com/q/52323922
tags question: http://stackoverflow.com/q/52285458
tags question: http://stackoverflow.com/q/52365584
tags question: http://stackoverflow.com/q/52397563
tags question: http://stackoverflow.com/q/52303043
tags question: http://stackoverflow.com/q/52314854
tags question: http://stackoverflow.com/q/52374725
tags question: http://stackoverflow.com/q/52427999
tags question: http://stackoverflow.com/q/52423018
tags question: http://stackoverflow.com/q/52368475
tags question: http://stackoverflow.com/q/52281051
tags question: http://stackoverflow.com/q/52369668
tags question: http://stackoverflow.com/q/52354470
tags question: http://stackoverflow.com/q/52429033
tags question: http://stackoverflow.com/q/52312593
tags question: http://stackoverflow.com/q/52281671
tags question: http://stackoverflow.com/q/52357753
tags question: http://stackoverflow.com/q/52283411
tags question: http://stackoverflow.com/q/52419070
tags question: http://stackoverflow.com/q/52391071
tags question: http://stackoverflow.com/q/52391118
tags question: http://stackoverflow.com/q/52354640
tags question: http://stackoverflow.com/q/52425073
tags question: http://stackoverflow.com/q/52282907
tags question: http://stackoverflow.com/q/52290693
tags question: http://stackoverflow.com/q/52350412
tags question: http://stackoverflow.com/q/52291784
tags question: http://stackoverflow.com/q/52293195
tags question: http://stackoverflow.com/q/52272638
tags question: http://stackoverflow.com/q/52429434
tags question: http://stackoverflow.com/q/52337536
tags question: http://stackoverflow.com/q/52322923
tags question: http://stackoverflow.com/q/52379791
tags question: http://stackoverflow.com/q/52358593
tags question: http://stackoverflow.com/q/52354164
tags question: http://stackoverflow.com/q/52333749
tags question: http://stackoverflow.com/q/52405435
tags question: http://stackoverflow.com/q/52323582
tags question: http://stackoverflow.com/q/52343833
tags question: http://stackoverflow.com/q/52325679
tags question: http://stackoverflow.com/q/52341079
tags question: http://stackoverflow.com/q/52306826
tags question: http://stackoverflow.com/q/52409894
tags question: http://stackoverflow.com/q/52317458
tags question: http://stackoverflow.com/q/52286525
tags question: http://stackoverflow.com/q/52357417
type: Tag
tags question: http://stackoverflow.com/q/52405131
tags question: http://stackoverflow.com/q/52330828
tags question: http://stackoverflow.com/q/52274902
tags question: http://stackoverflow.com/q/52415096
tags question: http://stackoverflow.com/q/52347763
tags question: http://stackoverflow.com/q/52366314
tags question: http://stackoverflow.com/q/52384451
tags question: http://stackoverflow.com/q/52319053
tags question: http://stackoverflow.com/q/52296389
tags question: http://stackoverflow.com/q/52342274
tags question: http://stackoverflow.com/q/52372087
tags question: http://stackoverflow.com/q/52306300
tags question: http://stackoverflow.com/q/52299317
tags question: http://stackoverflow.com/q/52374689
tags question: http://stackoverflow.com/q/52303432
tags question: http://stackoverflow.com/q/52398563
tags question: http://stackoverflow.com/q/52353540
tags question: http://stackoverflow.com/q/52300222
tags question: http://stackoverflow.com/q/52287070
tags question: http://stackoverflow.com/q/52419481
tags question: http://stackoverflow.com/q/52278469
tags question: http://stackoverflow.com/q/52399907
tags question: http://stackoverflow.com/q/52416568
tags question: http://stackoverflow.com/q/52318106
tags question: http://stackoverflow.com/q/52413158
tags question: http://stackoverflow.com/q/52280712
tags question: http://stackoverflow.com/q/52273742
tags question: http://stackoverflow.com/q/52357407

http://stackoverflow.com/comment/91757100
type: AnswerComment
type: Comment
has text: Can you please help me through the for loop. correcting question with condition.
comment on: http://stackoverflow.com/a/52406528
score: 0

http://stackoverflow.com/comment/91523535
score: 1
has text: Got it, Thanks heaps.
type: AnswerComment
comment on: http://stackoverflow.com/a/52287900
type: Comment

http://stackoverflow.com/a/52370524
has body: Comprehension Assuming dates are strings in the same format pd.DataFrame( [(y, r) for s, e, r in zip(*map(df.get, df)) for y in range(int(s[-4:]), int(e[-4:]) + 1)], columns=['year', 'rating'] ) year rating 0 2010 2 1 2011 2 2 2012 2 3 2012 4 4 2013 4 5 2014 4 Similar but using f-string and pd.date_range pd.DataFrame( [(y, r) for s, e, r in zip(*map(df.get, df)) for y in pd.date_range(s, f"12/31/{e[-4:]}", freq='Y').year], columns=['year', 'rating'] )
accepted answer of: http://stackoverflow.com/q/52370069
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52370069

http://stackoverflow.com/q/52277877
tagged with: webdriver
possible better answer: http://stackoverflow.com/a/52279340
answer count: 3
upvote count: 1
linked to: http://stackoverflow.com/q/57640584
favorite count: 0
linked to: http://stackoverflow.com/q/65623799
score: 0
has body: I'm trying to scrape this website using python and selenium. However all the information I need is not on the main page, so how would I click the links in the 'Application number' column one by one go to that page scrape the information then return to original page? Ive tried: def getData(): data = [] select = Select(driver.find_elements_by_xpath('//*[@id="node-41"]/div/div/div/div/div/div[1]/table/tbody/tr/td/a/@href')) list_options = select.options for item in range(len(list_options)): item.click() driver.get(url) URL: http://www.scilly.gov.uk/planning-development/planning-applications Screenshot of the site:
has comment: http://stackoverflow.com/comment/91508066
tagged with: python
has answer: http://stackoverflow.com/a/52279340
tagged with: selenium-webdriver
linked to: http://stackoverflow.com/q/59144599
linked to: http://stackoverflow.com/q/59706039
tagged with: selenium
accepted answer: http://stackoverflow.com/a/52281843
tagged with: web-scraping
downvote count: 1
has answer: http://stackoverflow.com/a/52280043
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91507329
has title: How to open multiple hrefs within a webtable to scrape through selenium
has comment: http://stackoverflow.com/comment/91507681
has answer: http://stackoverflow.com/a/52281843
linked to: http://stackoverflow.com/q/52364188

http://stackoverflow.com/a/52332831
type: Answer
has body: You want .drop_duplicates: df.drop_duplicates(subset=[0,1,2], keep='last', inplace=True)
score: 2
has comment: http://stackoverflow.com/comment/91613920
accepted answer of: http://stackoverflow.com/q/52332756
downvote count: 0
answers question: http://stackoverflow.com/q/52332756
type: AcceptedAnswer
upvote count: 2
has comment: http://stackoverflow.com/comment/91613295

http://stackoverflow.com/comment/91658345
comment on: http://stackoverflow.com/a/52341042
type: Comment
has text: Yup. It works after restarting opening a new notebook.
score: 1
type: AnswerComment

http://stackoverflow.com/q/52362331
possible better answer: http://stackoverflow.com/a/52362832
has answer: http://stackoverflow.com/a/52362832
accepted answer: http://stackoverflow.com/a/52362404
has body: I have one dataframe name as store_data.csv having thousands of data in the dataframe. Sample Data is like this- Date Store1 Store2 Store3 Store4 2018-06-01 2643 1642 2678 3050 2018-07-16 6442 5413 5784 7684 2018-07-24 4587 5743 3948 6124 2018-08-12 3547 8743 7462 8315 How to calculate which store highest total sales for the last month of data in python?
tagged with: numpy
tagged with: pandas
type: AnsweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/91668791
has answer: http://stackoverflow.com/a/52362404
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/91668799
score: 0
answer count: 2
downvote count: 2
tagged with: python
has title: How to calculate highest total sales for the last month of data in python

http://stackoverflow.com/comment/91578493
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52315386
type: AnswerComment
has text: What a mess! You've solved my trouble. I've been spending hours studying the documentation finding more. Thank You for the recommendation!

http://stackoverflow.com/a/52293463
answers question: http://stackoverflow.com/q/52293426
type: Answer
has body: You could collect all the in a list, for example: lst = [] for file in os.listdir(): file_input = open(file,"r") lst.append(file_input.read()) One extra recommendation - in general it might be wise to store the contents of a file as a collection of its lines by for example using file_input.readlines() which returns a list of lines.
has comment: http://stackoverflow.com/comment/91535212
score: 0

http://stackoverflow.com/comment/91560579
score: 0
type: QuestionComment
has text: @Roman Susi. Yes. Exactly.
type: Comment
comment on: http://stackoverflow.com/q/52306592

http://stackoverflow.com/comment/91506227
type: AnswerComment
comment on: http://stackoverflow.com/a/52279117
score: 0
type: Comment
has text: Ok now it works, but, if I use vdot = np.array([0]*900) instead of np.empty_like(v) I keep getting strange results. why?

http://stackoverflow.com/q/52273090
answer count: 1
tagged with: scikit-learn
has title: How can accuracy differs between one_hot_encode and count_vectorizer for the same dataset?
tagged with: python
accepted answer: http://stackoverflow.com/a/52278702
type: AnsweredQuestion
tagged with: machine-learning
type: Question
has body: onehot_enc, BernoulliNB: Here, I have used two different files for reviews and labels and I've used "train_test_split" to randomly split the data into 80% train data and 20% test data. reviews.txt: Colors &amp; clarity is superb Sadly the picture is not nearly as clear or bright as my 40 inch Samsung The picture is clear and beautiful Picture is not clear labels.txt: positive negative positive negative My Code: from sklearn.preprocessing import MultiLabelBinarizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import BernoulliNB from sklearn.metrics import confusion_matrix with open("/Users/abc/reviews.txt") as f: reviews = f.read().split("\n") with open("/Users/abc/labels.txt") as f: labels = f.read().split("\n") reviews_tokens = [review.split() for review in reviews] onehot_enc = MultiLabelBinarizer() onehot_enc.fit(reviews_tokens) X_train, X_test, y_train, y_test = train_test_split(reviews_tokens, labels, test_size=0.20, random_state=1) bnbc = BernoulliNB(binarize=None) bnbc.fit(onehot_enc.transform(X_train), y_train) score = bnbc.score(onehot_enc.transform(X_test), y_test) print("score of Naive Bayes algo is :" , score) // 90% predicted_y = bnbc.predict(onehot_enc.transform(X_test)) tn, fp, fn, tp = confusion_matrix(y_test, predicted_y).ravel() precision_score = tp / (tp + fp) recall_score = tp / (tp + fn) print("precision_score :" , precision_score) //92% print("recall_score :" , recall_score) //97% CountVectorizer, MultinomialNB: Here, I've manually split the same data into train (80%) and test(20%).And I'm supplying these two csv files to the algorithm. But, this is giving less accuracy compared to the above method. Can anyone help me out regarding the same ... train_data.csv: review,label Colors &amp; clarity is superb,positive Sadly the picture is not nearly as clear or bright as my 40 inch Samsung,negative test_data.csv: review,label The picture is clear and beautiful,positive Picture is not clear,negative My Code: from sklea…
tagged with: naivebayes
has answer: http://stackoverflow.com/a/52278702
score: 0

http://stackoverflow.com/comment/91705464
type: QuestionComment
score: 2
has text: interpolating is not the right choice here in my opinion. You should instead fit your data with a 2D power law. See [here](https://scipy-cookbook.readthedocs.io/items/FittingData.html#Fitting-a-2D-gaussian) for details about 2D fitting.
comment on: http://stackoverflow.com/q/52378090
type: Comment

http://stackoverflow.com/a/52390246
upvote count: 5
accepted answer of: http://stackoverflow.com/q/52390002
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52390002
downvote count: 0
score: 5
type: Answer
has comment: http://stackoverflow.com/comment/91727114
has body: Tracking this down was kind of fun. :-) It's not the values, but their types. It's a precision issue: heights, which works, is float64, local_z, which doesn't work, is only float32. We have In [70]: heights Out[70]: array([ 22.110203, 65.49054 , 110.321526, 156.54034 , 166.59094 ]) In [71]: heights.dtype Out[71]: dtype('float64') In [72]: curve_fit(func, heights, v)[0] Out[72]: array([1.35420488, 0.00325281]) and In [73]: local_z Out[73]: array([ 22.110205, 65.49054 , 110.321526, 156.54034 , 166.59094 ], dtype=float32) In [74]: curve_fit(func, local_z, v)[0] C:\Python\lib\site-packages\scipy\optimize\minpack.py:794: OptimizeWarning: Covariance of the parameters could not be estimated category=OptimizeWarning) Out[74]: array([1., 1.]) But if we want to, we can make local_z work: In [75]: curve_fit(func, local_z.astype(np.float64), v)[0] Out[75]: array([1.35420488, 0.00325281]) or heights fail: In [76]: curve_fit(func, heights.astype(np.float32), v)[0] C:\Python\lib\site-packages\scipy\optimize\minpack.py:794: OptimizeWarning: Covariance of the parameters could not be estimated category=OptimizeWarning) Out[76]: array([1., 1.])

http://stackoverflow.com/q/52383129
type: Question
tagged with: numpy
score: 5
accepted answer: http://stackoverflow.com/a/52383337
upvote count: 5
has answer: http://stackoverflow.com/a/52383425
downvote count: 0
has title: MemoryError with numpy arange
favorite count: 0
has answer: http://stackoverflow.com/a/52388245
tagged with: out-of-memory
tagged with: python
has comment: http://stackoverflow.com/comment/91710638
has answer: http://stackoverflow.com/a/52383337
has comment: http://stackoverflow.com/comment/91710449
answer count: 4
type: AnsweredQuestion
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91710433
possible better answer: http://stackoverflow.com/a/52384556
has answer: http://stackoverflow.com/a/52384556
has body: I want to create an array of powers of 10 as a label for the y axis of a plot. I am using the plt.yticks() with matplotlib imported as plt but this does not matter here anyway. I have plots where as the y axis is varying from 1e3 to 1e15. Those are log plots. Matplotlib is automatically displaying those with ticks with 1e2 steps and I want to have a step of 10 instead (in order to be able to use the minorticks properly). I want to use the plt.yticks(numpy.arange(1e3, 1e15, 10)) command as said but numpy.arange(1e3, 1e15, 10) result in a MemoryError. Isn't it supposed to output an array of length 13? Why does the memory gets full? How to overpass this issue and not build the array manually? I also tried using built-in range but it won't work with floats. Thank you.

http://stackoverflow.com/a/52274879
answers question: http://stackoverflow.com/q/52273117
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52273117
has body: The args attribute must be a tuple not a single value. With Python, singleton tuples must have a trailing comma, like (foo,). To fix that, add a trailing comma: thread1 = threading.Thread(target=serial_port, args=(file,)) thread1.start() thread2 = threading.Thread(target=update, args=(fig,)) thread2.start()

http://stackoverflow.com/q/52392923
type: Question
has comment: http://stackoverflow.com/comment/91731412
tagged with: arrays
has body: import random def shuffle(ary): ary = [1,2,3,4,5] d=len[ary] b=d-1 while (d &gt; 0): x=random.randint(0,d) if x == d: ary[b],ary[x]=ary[x],ary[d] return ary print("shuffle list" + str(shuffle(ary)))
downvote count: 6
has answer: http://stackoverflow.com/a/52392987
favorite count: 0
answer count: 3
score: -6
upvote count: 0
tagged with: shuffle
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52393236
has comment: http://stackoverflow.com/comment/91731361
has title: Python - Array won't shuffle and print
has answer: http://stackoverflow.com/a/52393005

http://stackoverflow.com/comment/91792523
type: Comment
comment on: http://stackoverflow.com/a/52424502
has text: Have no idea that this answer gets a downvote : ) can someone explain?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91689587
comment on: http://stackoverflow.com/a/52371452
type: AnswerComment
type: Comment
has text: Double commenting just to mention I'm not TOTALLY sure about the usb installation thing, but if you do a more detailed search on it you might find something interesting?! I'm really suggesting you to have a stable environment before starting working, or you might regret it later if a single variable of that environment gets wrecked ! But I mean, if you find a way to make it work and everything is fine, then feel free to share your solution !
score: 0

http://stackoverflow.com/comment/91699505
comment on: http://stackoverflow.com/a/52377211
type: AnswerComment
score: 0
type: Comment
has text: Thank. I implemented this into my code (Python 3.5, btw), and I am receiving another type error. `TypeError: QMainWindow(parent: QWidget = None, flags: Union[Qt.WindowFlags, Qt.WindowType] = Qt.WindowFlags()): argument 1 has unexpected type 'sip.wrappertype'`

http://stackoverflow.com/comment/91491999
type: QuestionComment
type: Comment
score: 1
has text: Could you please show the full code you use to produce the second image?
comment on: http://stackoverflow.com/q/52272393

http://stackoverflow.com/comment/91573042
type: QuestionComment
has text: General optimizing remarks: First, calling a function in Python comes with some overhead. If this is really something you need to optimize, you can optimize it by inlining the function. Second, a list comprehension is still a loop, it just looks nicer. Third, the map built-in of Python is faster if the function in it, is a built-in, or at least something in C instead of Python. This is caused by the fact that the function call overhead is larger than the loop overhead. Last, a nested loop is often faster than using a map with a tuple, because tuple packing and unpacking is overhead as well.
score: 0
comment on: http://stackoverflow.com/q/52311755
type: Comment

http://stackoverflow.com/comment/91800637
type: Comment
has text: JETM could you go a bit more into detail? That would be awesome. Where should I try that exactly?
score: 0
comment on: http://stackoverflow.com/q/52428385
type: QuestionComment

http://stackoverflow.com/q/52346711
has comment: http://stackoverflow.com/comment/91638985
upvote count: 0
has title: Cannot return the values in the list
has comment: http://stackoverflow.com/comment/91639074
tagged with: python-3.6
has answer: http://stackoverflow.com/a/52346743
has comment: http://stackoverflow.com/comment/91639031
answer count: 3
has comment: http://stackoverflow.com/comment/91639009
favorite count: 0
type: UnansweredQuestion
score: -3
has answer: http://stackoverflow.com/a/52346744
tagged with: python
has comment: http://stackoverflow.com/comment/91639051
has answer: http://stackoverflow.com/a/52346731
downvote count: 3
has body: I want to return the final value of the list which is new_list[3] but it return nothing at the end. I can get the final value of new_list[3] by using print function. I am quite confusing about the return function. Is it possible it return new_list[times] when the 2 for loop is ended? original_list = [100,300,400,900,1500] def filter_list(_list,times): L = len(_list) new_list = [list(_list) for k in range(times+1)] for k in range (0,times): for j in range (0,L): if j == 0: #exclude the term [j-1] because new_list[-1] is not exist new_list[k+1][j] = int(new_list[k][j]*0.2 + new_list[k][j+1]*0.5) elif j == L-1: #exclude the term [j+1] because new_list[L] is not exist new_list[k+1][j] = int(new_list[k][j-1]*0.4 + new_list[k][j]*0.2) else: new_list[k+1][j] = int(new_list[k][j-1]*0.4 + new_list[k][j]*0.2 + new_list[k][j+1]*0.5) return (new_list[times]) filter_list(original_list,3)
type: Question

http://stackoverflow.com/a/53717374
answers question: http://stackoverflow.com/q/52429410
type: AcceptedAnswer
type: Answer
score: 1
upvote count: 1
downvote count: 0
has body: Almost your exact code without the "features" parameter in the get call: import requests selectedSeasonPage = requests.get('https://en.wikipedia.org/wiki/2017–18_La_Liga') print(selectedSeasonPage.text) Gives me: &lt;th scope="row" style="text-align:right;"&gt;&lt;a href="/wiki/Deportivo_Alav%C3%A9s" title="Deportivo Alavés"&gt;Alavés&lt;/a&gt; &lt;/th&gt; &lt;td style="font-weight:normal;background:transparent;"&gt;&amp;#8212;&lt;/td&gt; &lt;td style="white-space:nowrap;font-weight:normal;background:#BBF3FF;"&gt;3–1&lt;/td&gt; &lt;td style="white-space:nowrap;font-weight:normal;background:#FBB;"&gt;0–1&lt;/td&gt; &lt;td style="white-space:nowrap;font-weight:normal;background:#FBB;"&gt;0–2&lt;/td&gt; &lt;td style="white-space:nowrap;font-weight:normal;background:#BBF3FF;"&gt;2–1&lt;/td&gt; &lt;td style="white-space:nowrap;font-weight:normal;background:#BBF3FF;"&gt;1–0&lt;/td&gt; &lt;td style="white-space:nowrap;font-weight:normal;background:#FBB;"&gt;1–2&lt;/td&gt;
accepted answer of: http://stackoverflow.com/q/52429410

http://stackoverflow.com/comment/91637715
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52345998
has text: Did you include the `[-1]` there?

http://stackoverflow.com/q/52346254
has answer: http://stackoverflow.com/a/52353715
type: AnsweredQuestion
has title: ImportError: Failed to import any qt binding, Python - Tensorflow
score: 54
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/76041271
accepted answer: http://stackoverflow.com/a/52353715
has answer: http://stackoverflow.com/a/69076167
has comment: http://stackoverflow.com/comment/91648041
downvote count: 0
answer count: 7
has answer: http://stackoverflow.com/a/53437818
favorite count: 0
has body: I'm starting my adventure with Tensorflow. I think I installed everything correctly, but when running this code, PyCharm returns an error: Traceback (most recent call last): File "C:/Users/tymot/Desktop/myenv3/env/Tensorflow/all_good.py", line 15, in &lt;module&gt; import matplotlib.pyplot as plt File "C:\Users\tymot\Anaconda1\lib\site-packages\matplotlib\pyplot.py", line 115, in &lt;module&gt; _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "C:\Users\tymot\Anaconda1\lib\site-packages\matplotlib\backends\__init__.py", line 62, in pylab_setup [backend_name], 0) File "C:\Users\tymot\Anaconda1\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 15, in &lt;module&gt; from .backend_qt5 import ( File "C:\Users\tymot\Anaconda1\lib\site-packages\matplotlib\backends\backend_qt5.py", line 19, in &lt;module&gt; import matplotlib.backends.qt_editor.figureoptions as figureoptions File "C:\Users\tymot\Anaconda1\lib\site-packages\matplotlib\backends\qt_editor\figureoptions.py", line 20, in &lt;module&gt; import matplotlib.backends.qt_editor.formlayout as formlayout File "C:\Users\tymot\Anaconda1\lib\site-packages\matplotlib\backends\qt_editor\formlayout.py", line 54, in &lt;module&gt; from matplotlib.backends.qt_compat import QtGui, QtWidgets, QtCore File "C:\Users\tymot\Anaconda1\lib\site-packages\matplotlib\backends\qt_compat.py", line 158, in &lt;module&gt; raise ImportError("Failed to import any qt binding") ImportError: Failed to import any qt binding My code which I am trying to run: import numpy as np import tensorflow as tf import matplotlib.pyplot as plt num_features = 2 num_iter = 10000 display_step = int(num_iter / 10) learning_rate = 0.01 num_input = 2 # units in the input layer 28x28 images num_hidden1 = 2 # units in the first hidden layer num_output = 1 # units in the output, only one output 0 or 1 #%% mlp function def multi_layer_perceptron_xor(x, weights, biases): hidden_layer1 = tf.add(tf.matmul(x, weights['w_h1']), bia…
has answer: http://stackoverflow.com/a/73125014
has answer: http://stackoverflow.com/a/77704420
upvote count: 54
possible better answer: http://stackoverflow.com/a/53437818
tagged with: python
has answer: http://stackoverflow.com/a/69580132

http://stackoverflow.com/q/52322207
type: Question
tagged with: conditional-statements
has body: So I'll start by explaining the context of the problem. I have an array populated with multiple strings, and I want to select random elements from that array, but once an element is selected once, it cant be selected again. My solution for this was to simply delete it from the array. I tried: dogs_array =['Bob', 'Fred', 'Jeff', 'Rick', 'Alice', 'Joe','Max', 'Will'] for x in range(3): i = random.randint(0, 7) print(dogs_array[i]) dogs_array.remove(i) However I receive the error: ValueError: list.remove(x): x not in list What should I do?
score: 1
has answer: http://stackoverflow.com/a/52324016
has title: How to remove a random element from an array. Python
has answer: http://stackoverflow.com/a/72852395
tagged with: arrays
has answer: http://stackoverflow.com/a/52322231
favorite count: 0
tagged with: logic
answer count: 5
has comment: http://stackoverflow.com/comment/91592080
has comment: http://stackoverflow.com/comment/91592245
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/62041476
upvote count: 2
type: UnansweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/52322269

http://stackoverflow.com/comment/91802400
type: Comment
comment on: http://stackoverflow.com/q/52395550
score: 0
type: QuestionComment
has text: I've gone ahead and put in the entire code. Happy for any feedback.

http://stackoverflow.com/q/52329057
type: Question
has title: heapq: What is an elegant way to use customized priority key with associated data that are not comparable?
score: 0
tagged with: heapq
has comment: http://stackoverflow.com/comment/91622170
has comment: http://stackoverflow.com/comment/91623954
has body: As shown in a basic example in the doc, one can always use a tuple so that the first element is compared as the priority key. However, what if the associated data are not comparable? What would be an elegant way to resolve this? For example, import heapq h = [(3, 2), (4, 3)] heapq.heapify(h) heapq.heappush(h, (3, (0, 1))) This emits TypeError: unorderable types: tuple() &lt; int()
tagged with: priority-queue
has comment: http://stackoverflow.com/comment/91623818
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91605139
has comment: http://stackoverflow.com/comment/91622329
answer count: 0
has comment: http://stackoverflow.com/comment/91623230

http://stackoverflow.com/comment/103990936
type: Comment
comment on: http://stackoverflow.com/a/52289528
score: 0
type: AnswerComment
has text: @PV8 Updated to add quotes, the better slashes, and you have to have the `!` in front if using jupyter. The server the notebook is running on is linux based right?

http://stackoverflow.com/a/52286707
score: 0
has body: Example file: Fname,LastName,StudentId john,jones,100 billy,bob,101 I use comma to separate cells since it is CSV. You can use csv library, which is in the python's standard library. pandas is more handy, though. Each line is a list of cell values. To match on the j-th column, use line[j]. import csv name_to_search = input("type last name:") with open("example.csv") as f: reader = csv.reader(f) # skip the first row, since it is header. header = next(reader) found = False for line in reader: if line[1] == name_to_search: print(line) found = True break if not found: print(name_to_search, "not found")
answers question: http://stackoverflow.com/q/52286534
type: Answer

http://stackoverflow.com/comment/111141557
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52333182
score: 0
has text: Whats its performance compare to native `gzip` command in shell?

http://stackoverflow.com/comment/91666491
comment on: http://stackoverflow.com/a/52361100
score: 0
type: AnswerComment
type: Comment
has text: It's called python programming.

http://stackoverflow.com/q/52305344
has body: I am trying to create a program that writes user input to a text document, but it is not working. It just loops this one section over and over again. Here is my current code: else: #Creates a new file and writes the pasword to it print("Strong Password") password1 += password1 newName = input("What do you want to save this password as? ") print(newName) file = open("passwordstorer", "w") file.write(newName) file.write(password1) file.close() break
upvote count: 0
has title: Pickle not creating and writing to a file?
favorite count: 0
has comment: http://stackoverflow.com/comment/91572399
tagged with: python
has answer: http://stackoverflow.com/a/52305521
has answer: http://stackoverflow.com/a/52305495
has comment: http://stackoverflow.com/comment/91558304
type: UnansweredQuestion
tagged with: pickle
downvote count: 1
tagged with: passwords
score: -1
type: Question
answer count: 2

fft
tags question: http://stackoverflow.com/q/52387673
type: Tag
tags question: http://stackoverflow.com/q/52293537
tags question: http://stackoverflow.com/q/52312053
tag name: fft
tags question: http://stackoverflow.com/q/52336754
tags question: http://stackoverflow.com/q/52414219

http://stackoverflow.com/comment/91825644
score: 0
type: Comment
type: QuestionComment
has text: @abcdaire I get the following: X =(768, 8) Y = (768,)
comment on: http://stackoverflow.com/q/52424172

http://stackoverflow.com/comment/91643266
score: 0
comment on: http://stackoverflow.com/q/52348874
has text: it would. I was just wondering if its bad practice for when you do have `InsurancePlan` info and `InsuranceCompany` info. You end up using the fk query to `InsuranceCompany` twice
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52355679
has body: You need to return from function. When you do newDict = dict(zip(dict1, dict2)) within a function, a new dictionary is created whose scope is local to the function and is not accessible outside. If you are likely to use this dictionary outside of function, the suggested way is to return the new dictionary back to caller once the function is done. dict1 = ['aa','bb','cc','dd'] dict2 = ['11','22','33','44'] def map_lists(Dict1, Dict2): newDict = dict(zip(dict1, dict2)) return newDict newDict = map_lists(dict1, dict2) print(newDict) Or, there is one another way which I won't recommend, but only FYI. dict1 = ['aa','bb','cc','dd'] dict2 = ['11','22','33','44'] def map_lists(Dict1, Dict2): global newDict newDict=dict(zip(dict1, dict2)) map_lists(dict1, dict2) print(newDict) global is not advised to use as it's not a good programming practice in any language.
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52355635
type: Answer
score: 1

http://stackoverflow.com/comment/91631842
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52342801
score: 0
has text: What are the values of `file` and `f_filename` showing as before you call `os.rename(file, f_filename)` ?

http://stackoverflow.com/q/52272229
has body: I have the problem that the code from below is extremely slow. I haven't been working with Python and Pandas that long, so I don't know exactly where to start. I want to determine the predecessor and successor of each row. Currently I iterate over each row and output the rows that meet my conditions. From these series I determine the maximum and the minimum once. I have the following record: index Case Button Start rowNow 0 x a 2017-12-06 10:17:43.227 0 1 x b 2017-12-06 10:17:44.876 1 2 x c 2017-12-06 10:17:45.719 2 3 y a 2017-12-06 15:28:57.500 3 4 y e 2017-12-06 15:29:19.079 4 And I want to get it: index Case Button Start rowNow prevNum nextNum 0 x a 2017-12-06 10:17:43.227 0 NaN 1 1 x b 2017-12-06 10:17:44.876 1 0 2 2 x c 2017-12-06 10:17:45.719 2 1 NaN 3 y a 2017-12-06 15:28:57.500 3 NaN 4 4 y e 2017-12-06 15:29:19.079 4 3 NaN Could someone give me some tips on how to optimize the speed of this code? Can vectorization be used here at all? for index, row in df.iterrows(): x = df[(df['Case'] == row['Case']) &amp; (df['rowNow'] &lt; row['rowNow']) &amp; (row['Start'] &gt;= df['Start'])] df.loc[index,'prevNum'] = x['rowNow'].max() y = df[(df['Case'] == row['Case']) &amp; (df['rowNow'] &gt; row['rowNow']) &amp; (row['Start'] &lt;= df['Start'])] df.loc[index,'nextNum'] = y['rowNow'].min()
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91491702
favorite count: 0
tagged with: iteration
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/91491768
tagged with: python
has comment: http://stackoverflow.com/comment/91491740
possible better answer: http://stackoverflow.com/a/52272511
answer count: 2
has comment: http://stackoverflow.com/comment/91491556
has answer: http://stackoverflow.com/a/52272511
upvote count: 1
has comment: http://stackoverflow.com/comment/91491641
has answer: http://stackoverflow.com/a/52272490
tagged with: vectorization
has title: Faster methods than iterrows with conditions (predecessor and successor of each row)
linked to: http://stackoverflow.com/q/51149735
tagged with: performance
has comment: http://stackoverflow.com/comment/91491551
linked to: http://stackoverflow.com/q/24870953
accepted answer: http://stackoverflow.com/a/52272490

http://stackoverflow.com/comment/91506890
score: 1
type: AnswerComment
has text: The `as painting` is not necessary, and I would recommend keeping `Color` capitalized (so no `as color`).
type: Comment
comment on: http://stackoverflow.com/a/52278752

http://stackoverflow.com/comment/91537828
score: 0
has text: @MartinEvans all of the files have the same format yes, but I don't know if they will be the same headers each time. However each time it is run all of the CSVs will have the same headers. I hope that is clear?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52293475

http://stackoverflow.com/comment/91585286
comment on: http://stackoverflow.com/q/52318572
score: 0
type: QuestionComment
type: Comment
has text: You could achieve it reading the very first example on [dask-tutorial](https://github.com/dask/dask-tutorial).

http://stackoverflow.com/a/52381251
has body: The http server (tornado) implements so this works : import tornado.ioloop import tornado.web impot pandas as pd df=pf.DataFrame({"test":[1,2,3,4]}) class MainHandler(tornado.web.RequestHandler): def get(self): df.to_json(self)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52371472

http://stackoverflow.com/q/52426691
has comment: http://stackoverflow.com/comment/91799048
has comment: http://stackoverflow.com/comment/91799321
has answer: http://stackoverflow.com/a/52428183
has comment: http://stackoverflow.com/comment/91799951
has comment: http://stackoverflow.com/comment/91799734
has answer: http://stackoverflow.com/a/52426861
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91820003
tagged with: python
has title: Why won't the "total" value update when run multiple times?
has comment: http://stackoverflow.com/comment/91800526
has comment: http://stackoverflow.com/comment/91797311
tagged with: return-value
has comment: http://stackoverflow.com/comment/91799498
has comment: http://stackoverflow.com/comment/91797173
has comment: http://stackoverflow.com/comment/91796895
has answer: http://stackoverflow.com/a/52427027
has comment: http://stackoverflow.com/comment/91799272
has body: The "total" changes the first time I run the function but doesn't return the new value of total so when I run it again it's the same value as before I ran it the first time? total = card[1].value def hit(total): #print (str(hit.counter)) print("You draw the " + string(card[hit.counter])) total = total + card[hit.counter].value print(str(total)) hit.counter += 1 return hit.counter return total the function is called here: choice = raw_input("\n1. Hit\n2. Stay\n") if (choice == "1"): hit(total) This is the same problem simplified x = 1 def call(x): x = x + 1 print x return x call(x) every time this is run it outputs 2 and doesn't update the new value of "x = x + 1"
type: Question
has comment: http://stackoverflow.com/comment/91799426
has comment: http://stackoverflow.com/comment/91796853
has comment: http://stackoverflow.com/comment/91796592
has comment: http://stackoverflow.com/comment/91799482
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91819759
score: 0
answer count: 3

http://stackoverflow.com/comment/91748364
has text: @Jean-FrançoisFabre No, but is that really necessary? The answers do a good enough job explaining that sets (and dicts) eliminate items that hash and compare equal.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52402133

dynamically-generated
tags question: http://stackoverflow.com/q/52302017
tags question: http://stackoverflow.com/q/52384532
tag name: dynamically-generated
type: Tag

http://stackoverflow.com/q/52326526
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/91610086
type: UnansweredQuestion
tagged with: netcdf
score: 6
type: Question
has title: Xarray - daily averages from hourly data in multiple files
has comment: http://stackoverflow.com/comment/91610269
has comment: http://stackoverflow.com/comment/91654251
has comment: http://stackoverflow.com/comment/91654439
upvote count: 6
has comment: http://stackoverflow.com/comment/91652739
has body: I have 5 netCDF files with moored current meters data. Each file looks like this: &lt;xarray.Dataset&gt; Dimensions: (BINDEPTH: 50, INSTRDEPTH: 3, LATITUDE: 5, LONGITUDE: 5, TIME: 44106) Coordinates: * INSTRDEPTH (INSTRDEPTH) float64 100.0 280.0 600.0 * LATITUDE (LATITUDE) float64 -34.04 -33.8 -33.67 -33.56 -33.51 * LONGITUDE (LONGITUDE) float64 27.57 27.59 27.64 27.72 27.86 * TIME (TIME) datetime64[ns] 2015-04-11T15:00:00 ... Dimensions without coordinates: BINDEPTH Data variables: PRES (TIME, INSTRDEPTH) float32 dask.array&lt;shape=(44106, 3), chunksize=(44106, 3)&gt; VCUR (TIME, BINDEPTH) float32 dask.array&lt;shape=(44106, 50), chunksize=(44106, 50)&gt; UCUR (TIME, BINDEPTH) float32 dask.array&lt;shape=(44106, 50), chunksize=(44106, 50)&gt; WCUR (TIME, BINDEPTH) float32 dask.array&lt;shape=(44106, 50), chunksize=(44106, 50)&gt; ECUR (TIME, BINDEPTH) float32 dask.array&lt;shape=(44106, 50), chunksize=(44106, 50)&gt; I am trying to plot vertical sections of the data i.e plt.contourf(distance,BINDEPTH,VCUR) I am able to do this with specific timestamps but I am struggling with creating daily averages and plotting the results. Here is an example of what im expecting: To create daily averages I have tried: data2 = data.resample(TIME='1D').mean('TIME') data3 = data2.sel(TIME='2015-6-15') This produces: It seems to be averaging both over position and time, so how do I average over time only? Thanks in advance.
has comment: http://stackoverflow.com/comment/91638591
has comment: http://stackoverflow.com/comment/91609646
favorite count: 0
tagged with: python-xarray
has comment: http://stackoverflow.com/comment/91609997
has comment: http://stackoverflow.com/comment/91653733
tagged with: python
has comment: http://stackoverflow.com/comment/91647695
tagged with: python-3.x

http://stackoverflow.com/q/52296757
tagged with: python
downvote count: 0
has comment: http://stackoverflow.com/comment/91541709
has comment: http://stackoverflow.com/comment/91541489
tagged with: php
tagged with: laravel
score: 2
type: AnsweredQuestion
tagged with: dataframe
type: Question
upvote count: 2
answer count: 1
has body: I am using pandas on python 3.6.5, I desire to achieve similar result on a DataFrame instance as the Collection's "pluck" method in Laravel. For example: DataFrame one two 0 beer wine 1 beer tomato PHP Laravel code: $plucked = $collection-&gt;pluck('two')-&gt;toArray(); $print_r($plucked); &gt;&gt; ['wine', 'tomato'] Desired solution (Python equivalent): plucked = df.pluck('two') How do I achieve this?
favorite count: 0
has answer: http://stackoverflow.com/a/52296995
accepted answer: http://stackoverflow.com/a/52296995
tagged with: pandas
has title: Pandas DataFrame equivalent of laravel's 'pluck' on collections

http://stackoverflow.com/q/52339143
answer count: 1
accepted answer: http://stackoverflow.com/a/52339459
favorite count: 0
has answer: http://stackoverflow.com/a/52339459
tagged with: python
tagged with: selenium-webdriver
has body: I am dealing with drop-downs that were created with Angular JS. When I look at HTML, the drop-down options that I see have a tag and not a standard . So when I try to figure out the drop-down length, the following standard approach doesn't work select = drowser.find_element_by_id(elementID)) print len(select.options) How else can I try to find out how many options my drop-down has? EDITED: Below is an example of HTML:
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: selenium
has title: How to find length of drop-down with mat-options with Selenium Webdriver with Python?
type: Question
has comment: http://stackoverflow.com/comment/91625629
upvote count: 1

http://stackoverflow.com/comment/91656839
score: 1
comment on: http://stackoverflow.com/q/52356091
type: Comment
type: QuestionComment
has text: I've been testing with permutations([1,2,3,4], 3)

http://stackoverflow.com/q/52376025
type: UnansweredQuestion
type: Question
tagged with: qt
tagged with: anaconda
has title: Bug in Anaconda 5.2 for macOS Installer for Python 3.6? PySide and qt bindings not found after installing
score: 1
tagged with: pyside
upvote count: 1
favorite count: 0
has body: When trying to install Python 3.6 using the Anaconda 5.2 for macOS Installer I get the following errors: Traceback (most recent call last): File "/anaconda3/lib/python3.6/site-packages/qtpy/init.py", line 166, in from PySide import version as PYSIDE_VERSION # analysis:ignore ModuleNotFoundError: No module named 'PySide' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/anaconda3/bin/spyder", line 11, in sys.exit(main()) File "/anaconda3/lib/python3.6/site-packages/spyder/app/start.py", line 159, in main from spyder.app import mainwindow File "/anaconda3/lib/python3.6/site-packages/spyder/app/mainwindow.py", line 49, in requirements.check_qt() File "/anaconda3/lib/python3.6/site-packages/spyder/requirements.py", line 39, in check_qt import qtpy File "/anaconda3/lib/python3.6/site-packages/qtpy/init.py", line 172, in raise PythonQtError('No Qt bindings could be found') qtpy.PythonQtError: No Qt bindings could be found I've seen these errors for different situations, the most relevant being explained in this SO question. However, I wanted to post my question because the error occurs for the install using the latest version of anaconda for Mac, and I couldn't find a question related to that.
tagged with: python
linked to: http://stackoverflow.com/q/47362751
tagged with: python-3.x
answer count: 0
downvote count: 0

win32gui
type: Tag
tags question: http://stackoverflow.com/q/52308952
tag name: win32gui
tags question: http://stackoverflow.com/q/52335798

http://stackoverflow.com/comment/91656187
has text: @AJwr I didn't realize it was HW, answer updated, thank you.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52355567

http://stackoverflow.com/a/52315274
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52311583
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52311583
type: AcceptedAnswer
has body: I believe need extract columns names by difference and then use DataFrame.sub: cols = df1.columns.difference(['wave']) #is possible specify multiple columns #cols = df1.columns.difference(['wave','MeasredWave']) #df1[cols] = means in output are not touch columns from df1 df1[cols] = df1[cols].sub(df2[cols]) print (df1) wave num stlines fwhm EWs MeasredWave 0 4050.32 0.0 0.006340 -0.00412 -0.715440 0.000891 1 4208.98 0.0 -0.002455 0.00086 0.227375 -0.000851 2 4374.94 3.0 -0.001930 0.00274 1.853900 -0.000539 3 4379.74 8.0 0.014970 -0.00733 -0.882590 0.001262 4 4398.01 8.0 -0.004660 0.01392 7.048620 0.003309 5 4502.21 -1.0 -0.009540 0.00055 -0.692110 -0.000544 cols = df1.columns.difference(['wave']) #df2[cols] = means in output are not touch columns from df2 df2[cols] = df1[cols].sub(df2[cols]) print (df2) wave num stlines fwhm EWs MeasredWave 0 4050.32 0.0 0.006340 -0.00412 -0.715440 0.000891 1 4208.98 0.0 -0.002455 0.00086 0.227375 -0.000851 2 4374.94 3.0 -0.001930 0.00274 1.853900 -0.000539 3 4379.74 8.0 0.014970 -0.00733 -0.882590 0.001262 4 4398.01 8.0 -0.004660 0.01392 7.048620 0.003309 5 4502.21 -1.0 -0.009540 0.00055 -0.692110 -0.000544

http://stackoverflow.com/q/52359283
possible better answer: http://stackoverflow.com/a/52359322
has answer: http://stackoverflow.com/a/52359322
tagged with: python
has comment: http://stackoverflow.com/comment/91663107
favorite count: 0
has comment: http://stackoverflow.com/comment/91663031
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91663305
has comment: http://stackoverflow.com/comment/91663023
accepted answer: http://stackoverflow.com/a/52359351
has title: How can I define a variable as a dictionary in python 3.6
downvote count: 1
type: AnsweredQuestion
score: -1
type: Question
has comment: http://stackoverflow.com/comment/91663063
answer count: 2
has body: I'm trying to make a program that takes the contents of a text file and uses it as a dictionary. When I put in this code; A=open("dic.txt","r") print(A.read()) if "A" in A: print("spam") else: print("eggs") I get this output: {"A":1} eggs What I want is this: {"A":1} spam Any ideas on how to do that? I don't understand why its not working. These are the contents of the text file: {"A":1}
upvote count: 0
has comment: http://stackoverflow.com/comment/91663131
has answer: http://stackoverflow.com/a/52359351

http://stackoverflow.com/q/52359627
score: 2
has answer: http://stackoverflow.com/a/52359667
type: Question
has comment: http://stackoverflow.com/comment/91664174
tagged with: network-programming
downvote count: 0
has answer: http://stackoverflow.com/a/52359677
has answer: http://stackoverflow.com/a/59788845
has title: How to use argparse IP address and community string?
answer count: 3
tagged with: argparse
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: The title pretty much summarizes what I'd like to have happen. I want to execute a python script that does something with IP address and community string. I use the following command for parsing: import argparse def get_args(): '''This function parses and return arguments passed in''' # Assign description to the help doc parser = argparse.ArgumentParser( description='') # Add arguments parser.add_argument( '-i', '--ip-adress', type=str, help='ip address of the host', required=True) parser.add_argument( '-c', '--community', type=str, help='community string', required=True) # Array for all arguments passed to script args = parser.parse_args() # Assign args to variables IP = args.ip-adress COMMUNITY = args.community # Return all variable values return IP ,COMMUNITY # Run get_args() # get_args() # Match return values from get_arguments() # and assign to their respective variables IP , COMMUNITY = get_args() # Print the values print "\n ip address : [ %s ]\n" % IP print "\ncommunity: [ %s ]\n" % COMMUNITY However, no matter how I played with the argument I cannot figure out why I get this error. python arg.py -i 10.0.1.2 -c xxbsd Traceback (most recent call last): File "arg.py", line 30, in &lt;module&gt; IP , COMMUNITY = get_args() File "arg.py", line 20, in get_args IP = args.ip-adress AttributeError: 'Namespace' object has no attribute 'ip' Could anyone help?

http://stackoverflow.com/a/52343276
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91632625
type: Answer
accepted answer of: http://stackoverflow.com/q/52343181
has body: You can do that using re.split: import re def get_text_after_preposition_of_place(text): """Returns the texts before[0] and after[1] &lt;preposition of place&gt;""" prepositions_of_place = ["in front of","behind","in","on","under","near","next to","between","below","above","close to","beside"] preps_re = re.compile(r'\b(' + '|'.join(prepositions_of_place) + r')\b') split = preps_re.split(text, maxsplit=1) return split[0], split[1]+split[2] print(get_text_after_preposition_of_place('The cat in the box on the table')) # ('The cat ', 'in the box on the table') First, we create a regex that will look like (in|on|under). Note the parentheses: they will allow us to capture the strings on which we split the string in order to keep them in the output. Then, we split, allowing 1 split at most, and concatenate the last two parts: the preposition and the rest of the string.
has comment: http://stackoverflow.com/comment/91632682
score: 4
answers question: http://stackoverflow.com/q/52343181
upvote count: 4

http://stackoverflow.com/comment/91567342
type: QuestionComment
has text: Happy Ganesh Chaturthi sir.
type: Comment
comment on: http://stackoverflow.com/q/52290434
score: 0

http://stackoverflow.com/q/52359485
answer count: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/91663424
tagged with: python
has body: I was wondering if you could help me with a python programming issue? I'm currently trying to write a program that reads a text file and output "word 1 True" if the word had already occurred in that file before or "word 1 False" if this is the first time the word appeared. Here's what I came up with: fh = open(fname) lst = list () for line in fh: words = line.split() for word in words: if word in words: print("word 1 True", word) else: print("word 1 False", word) However, it only returns "word 1 True" Please advise. Thanks!
accepted answer: http://stackoverflow.com/a/52359527
type: AnsweredQuestion
score: 3
upvote count: 3
has title: Python - Locating Duplicate Words in a Text File
type: Question
has answer: http://stackoverflow.com/a/52359858
downvote count: 0
possible better answer: http://stackoverflow.com/a/52359515
has comment: http://stackoverflow.com/comment/91663472
has answer: http://stackoverflow.com/a/52359515
has answer: http://stackoverflow.com/a/52359527
has answer: http://stackoverflow.com/a/52359518

http://stackoverflow.com/q/52389290
answer count: 4
upvote count: 2
has answer: http://stackoverflow.com/a/52389431
type: Question
has answer: http://stackoverflow.com/a/52389530
has body: I have some data which looks as follows: Owner Label1 Label2 Label3 Bob Dog N/A N/A John Cat Mouse N/A Lee Dog Cat N/A Jane Hamster Rat Ferret And I want it reshaped to one-hot encoding. Something like this: Owner Dog Cat Mouse Hamster Rat Ferret Bob 1 0 0 0 0 0 John 0 1 1 0 0 0 Lee 1 1 0 0 0 0 Jane 0 0 0 1 1 1 I've looked around the documentation and stackoverflow, but haven't been able to determine the relevant functions to achieve this. get_dummies comes pretty close, but it creates a prefix for each category only when that category appears in a respective column.
has answer: http://stackoverflow.com/a/52389399
tagged with: pandas
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52389380
favorite count: 0
has title: Reshaping and encoding multi-column categorical variables to one hot encoding
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52425421
has comment: http://stackoverflow.com/comment/91796803
favorite count: 0
has comment: http://stackoverflow.com/comment/91794531
has comment: http://stackoverflow.com/comment/91796158
has comment: http://stackoverflow.com/comment/91796043
possible better answer: http://stackoverflow.com/a/52425573
tagged with: python
has title: Decoding message using dictionary on string in Python
has answer: http://stackoverflow.com/a/52425573
downvote count: 2
has comment: http://stackoverflow.com/comment/91794313
has answer: http://stackoverflow.com/a/52425566
type: AnsweredQuestion
has body: When I'm using a dictionary to replace values in a string for decoding of a message, how do I put it in such that the function doesn't read a replaced value as a key and replace a replaced value again? def decipher_message(translation_guide, message): t = read_translation_guide_into_dictionary(translation_guide) e = read_message(message) print(t) print(e) for key, value in t.items(): f = e e = f.replace(key, value) return e Output: {'a': 'm', 'b': 'a', 'c': 'c', 'd': 'y', 'e': 't', 'f': 'v', 'g': 'o', 'h': 'u', 'i': 'x', 'j': 'e', 'k': 'j', 'l': 'w', 'm': 'f', 'n': 'z', 'o': 'd', 'p': 'l', 'q': 'i', 'r': 'k', 's': 'h', 't': 'n', 'u': 'g', 'v': 'b', 'w': 'q', 'x': 's', 'y': 'p', 'z': 'r'} "qa mqtbppd vjqtu mghto! esbtr dgh mgz mqtoqtu aj gs rqto xezbtujz. q ahxe ejpp dgh, qex whqej vgzqtu sbfqtu bpp esj ljbpes qt esj lgzpo. qm dghzj pggrqtu mgz qe, q vhzqjo b aby eg qe bzghto lsjzj dghzj xebtoqtu tgl! zjajavjz esghus: ljbpes qxte jfjzdesqtu qt esj lgzpo!" '"if finallp being fdgnd! nhank pdg fdr finding fe dh kind snranger. i fgsn nell pdg, ins qgine bdring habing all nhe qealnh in nhe qdrld. if pdgre lddking fdr in, i bgried a fap nd in ardgnd qhere pdgre snanding ndq! refefber nhdggh: qealnh isnn eberpnhing in nhe qdrld!"'
type: Question
upvote count: 4
answer count: 2
score: 2
accepted answer: http://stackoverflow.com/a/52425566

http://stackoverflow.com/a/52296504
answers question: http://stackoverflow.com/q/52289107
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52289107
upvote count: 1
downvote count: 1
has body: I found the answer and I'm sharing it in case anyone else has the same problem in the future. The steps are the following. After having followed the procedure I mentioned in the question, without the final step, one needs to run the following command in the terminal: python -m pip install --upgrade pip setuptools wheel then open casa and import pip._internal and finally run pip._internal.main(['install', 'astropy', '--user']).
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91555348

http://stackoverflow.com/comment/91625400
type: Comment
type: QuestionComment
has text: [Is this the complete error message? No traceback, no line numbers?](http://idownvotedbecau.se/noexceptiondetails/)
comment on: http://stackoverflow.com/q/52337870
score: 0

http://stackoverflow.com/q/52359868
tagged with: python
score: 1
has body: "(n,p^n)" n=2 p=3 p.is_prime() n in ZZ list1=list(IntegerRange(0,(p^n)-1)) V1=vector(GF(3),list1) print V1 list1.digits(base=p,padto=n) Trying to get output: [(0, 0),(0, 1),(0, 2),(1, 0),(1, 1),(1, 2),(2, 0),(2, 1),(2, 2)] I cannot figure out how to use a list and convert it into a form where I can use the .digits function
type: Question
has title: Converting a list of numbers into q-ary representation in Sage
has answer: http://stackoverflow.com/a/52376879
tagged with: sage
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0
tagged with: binary
type: UnansweredQuestion

http://stackoverflow.com/q/52405554
accepted answer: http://stackoverflow.com/a/52406374
score: 1
type: Question
upvote count: 2
tagged with: wagtail
has answer: http://stackoverflow.com/a/52406374
has title: How to make pageurl return an absolute url
has comment: http://stackoverflow.com/comment/91755346
downvote count: 1
answer count: 1
has body: I need Twitter tweet button below every blog post. How do I make {% pageurl %} return an absolute URL of that specific blog post? Thanks
favorite count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/52370288
has title: disable wheel in QSpinBox
type: AnsweredQuestion
has body: I have a number of spinboxes in my PySide project and I would like to change the behavior so the so user is required to click in the field to change the value and then press the enter key. I would like to disable scroll wheel behavior for the spinboxes. I have tried setting the focus policy, but it is not taking effect. def light_label_event(self,text,checked): print("this is the pressed button's label", text) def populate_lights(self): for light in self.lights: light_label = QtWidgets.QSpinBox() light_label.setFocusPolicy(QtCore.Qt.StrongFocus)
downvote count: 0
tagged with: pyside2
has answer: http://stackoverflow.com/a/52412149
accepted answer: http://stackoverflow.com/a/52412149
has answer: http://stackoverflow.com/a/60479770
type: Question
score: 5
possible better answer: http://stackoverflow.com/a/60479770
answer count: 3
favorite count: 0
upvote count: 5
has answer: http://stackoverflow.com/a/62910411
tagged with: python

http://stackoverflow.com/comment/91636776
type: QuestionComment
has text: what you mean by around the block?
score: 0
comment on: http://stackoverflow.com/q/52345425
type: Comment

http://stackoverflow.com/comment/91799735
type: Comment
has text: Almost there! It is not working for the cases like this, with 2 words items: \nInhaltse / techn. Angaben*\n\nAQUA • COCO-GLUCOSIDE • COCO DISULFATE • NITRATE SODIUM\n\n\
comment on: http://stackoverflow.com/a/52427544
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91711865
type: Comment
comment on: http://stackoverflow.com/a/52383477
score: 1
type: AnswerComment
has text: Good find, I was peaking at the source myself, interesting that they decided to implement this at all really rather than raise a `TypeError`; I can't imagine it's a common use case

http://stackoverflow.com/comment/91572377
comment on: http://stackoverflow.com/q/52302853
score: 0
has text: Other users marked your question for low quality and need for improvement. I re-worded/formatted your input to make it easier to read/understand. Please review my changes to ensure they reflect your intentions. Feel free to drop me a comment in case you have further questions or feedback for me.
type: Comment
type: QuestionComment

dictionary
tags question: http://stackoverflow.com/q/52387295
tags question: http://stackoverflow.com/q/52356646
tags question: http://stackoverflow.com/q/52289808
tags question: http://stackoverflow.com/q/52377410
tags question: http://stackoverflow.com/q/52316072
tags question: http://stackoverflow.com/q/52408268
tags question: http://stackoverflow.com/q/52284823
tags question: http://stackoverflow.com/q/52404476
tags question: http://stackoverflow.com/q/52389918
tags question: http://stackoverflow.com/q/52373314
tags question: http://stackoverflow.com/q/52304949
tags question: http://stackoverflow.com/q/52309210
tags question: http://stackoverflow.com/q/52396819
tags question: http://stackoverflow.com/q/52407630
tags question: http://stackoverflow.com/q/52345444
tags question: http://stackoverflow.com/q/52355656
tags question: http://stackoverflow.com/q/52419831
tags question: http://stackoverflow.com/q/52310981
tags question: http://stackoverflow.com/q/52399520
tags question: http://stackoverflow.com/q/52273275
tags question: http://stackoverflow.com/q/52397709
tags question: http://stackoverflow.com/q/52358002
tags question: http://stackoverflow.com/q/52273543
tags question: http://stackoverflow.com/q/52402133
tags question: http://stackoverflow.com/q/52384645
tags question: http://stackoverflow.com/q/52323404
tags question: http://stackoverflow.com/q/52302645
tags question: http://stackoverflow.com/q/52347116
tags question: http://stackoverflow.com/q/52409432
tags question: http://stackoverflow.com/q/52320807
tags question: http://stackoverflow.com/q/52395570
tags question: http://stackoverflow.com/q/52424952
tags question: http://stackoverflow.com/q/52405726
tags question: http://stackoverflow.com/q/52319296
tags question: http://stackoverflow.com/q/52417812
tags question: http://stackoverflow.com/q/52272219
tags question: http://stackoverflow.com/q/52428811
tags question: http://stackoverflow.com/q/52285950
tags question: http://stackoverflow.com/q/52285212
tags question: http://stackoverflow.com/q/52371526
tags question: http://stackoverflow.com/q/52328018
tags question: http://stackoverflow.com/q/52298586
tags question: http://stackoverflow.com/q/52291697
tags question: http://stackoverflow.com/q/52371716
tags question: http://stackoverflow.com/q/52343065
tags question: http://stackoverflow.com/q/52418325
tag name: dictionary
tags question: http://stackoverflow.com/q/52360916
tags question: http://stackoverflow.com/q/52374935
tags question: http://stackoverflow.com/q/52309515
tags question: http://stackoverflow.com/q/52323521
tags question: http://stackoverflow.com/q/52286402
tags question: http://stackoverflow.com/q/52393119
tags question: http://stackoverflow.com/q/52379601
tags question: http://stackoverflow.com/q/52319120
tags question: http://stackoverflow.com/q/52410880
tags question: http://stackoverflow.com/q/52355635
tags question: http://stackoverflow.com/q/52276566
tags question: http://stackoverflow.com/q/52311560
tags question: http://stackoverflow.com/q/52313900
tags question: http://stackoverflow.com/q/52347737
tags question: http://stackoverflow.com/q/52401988
tags question: http://stackoverflow.com/q/52375354
tags question: http://stackoverflow.com/q/52419318
tags question: http://stackoverflow.com/q/52342176
tags question: http://stackoverflow.com/q/52330853
tags question: http://stackoverflow.com/q/52283618
tags question: http://stackoverflow.com/q/52293174
tags question: http://stackoverflow.com/q/52411944
tags question: http://stackoverflow.com/q/52380592
tags question: http://stackoverflow.com/q/52287883
tags question: http://stackoverflow.com/q/52275560
tags question: http://stackoverflow.com/q/52368027
tags question: http://stackoverflow.com/q/52313068
tags question: http://stackoverflow.com/q/52276859
tags question: http://stackoverflow.com/q/52322847
tags question: http://stackoverflow.com/q/52314186
tags question: http://stackoverflow.com/q/52425055
tags question: http://stackoverflow.com/q/52367258
tags question: http://stackoverflow.com/q/52273841

http://stackoverflow.com/comment/91704158
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52379924
type: Comment
has text: @jezrael editted the question with the data sample

http://stackoverflow.com/a/52290183
answers question: http://stackoverflow.com/q/52289930
score: 2
downvote count: 0
type: AcceptedAnswer
upvote count: 2
has body: You're right! You just need to tell cvxpy that p_cov is positive semidefinite. p_cov = cvx.Parameter((m, m), PSD=True) DCP can now compute the correct nature of this expression: cvx.quad_form(x, p_cov) Which is: Expression(CONVEX, NONNEGATIVE, (1, 1)) Instead of: Expression(UNKNOWN, UNKNOWN, (1, 1)) Find more documentation in Advanced Features.
type: Answer
accepted answer of: http://stackoverflow.com/q/52289930

http://stackoverflow.com/q/52315461
tagged with: cython
type: Question
tagged with: gcc
has comment: http://stackoverflow.com/comment/91583720
has answer: http://stackoverflow.com/a/52320160
answer count: 1
accepted answer: http://stackoverflow.com/a/52320160
tagged with: cross-compiling
tagged with: python
has title: Linker complains about missing -fPIC
type: AnsweredQuestion
score: 0
has body: I am trying to cross compile a freezed Cython program for use on an RPi. Link produces (for many object of the Python library) /usr/bin/arm-linux-gnueabihf-ld: /root/xxx_Build/usr/local/lib/python3.7/config-3.7m-arm-linux-gnueabihf/libpython3.7m.a(getopt.o): relocation R_ARM_THM_MOVW_ABS_NC against `a local symbol' can not be used when making a shared object; recompile with -fPIC The linker should create an executable (and not a shared object). Why? Compile (of my modules): cython_freeze.py -o main.c sub.py cython sub2.py {crossPrefix}gcc -fPIC -pthread -O2 -Wall -Wextra -fno-strict-aliasing -fwrapv -I{crossRoot}{pythonInclude} -c -o main.o main.c' {crossPrefix}gcc -fPIC -pthread -O2 -Wall -Wextra -fno-strict-aliasing -fwrapv -I{crossRoot}{pythonInclude} -c -o sub.o sub.c' Link: {crossPrefix}gcc -Xlinker -export-dynamic -L{crossRoot}/usr/local/lib/{pythonCommand}/config-{pythonVersion}m-{crossPrefixM} main.o sub.o -l{pythonCommand}m -lm -lpthread -ldl -lutil -o Versions: Python 3.7.0 (from python.org with default build) Cython 0.28.5 Host UBUNTU 18.04 x64 Target UBUNTU MATE 16.04 Raspberry Pi 3 B+ The above process worked with Python 3.6.4 Cython 0.23.3 Host UBUNTU 16.04 x64 Target UBUNTU MATE 16.04 Raspberry Pi 3 B+

http://stackoverflow.com/q/52307130
has comment: http://stackoverflow.com/comment/91561476
type: Question
has comment: http://stackoverflow.com/comment/91564391
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52323956
tagged with: sqlite
answer count: 1
has title: (ValueError: Couldn't parse date string) When trying to import sqlite table to pandas
has body: I am having trouble importing DATE and TIMESTAMP values from sqlite into pandas import pandas as pd import sqlaclchemy engine = sqlalchemy.create_engine('sqlite:///database.db') df = pd.read_sql_table('ephemeris', engine) print(df) ValueError: Couldn't parse date string: '1943 1 1' When I run another table which starts with a DATE value I get the following ValueError:Couldn't parse datetime string: '00:00:00' I'm having trouble finding information on this. I could convert the columns from DATE and TIMESTAMP to TEXT and I think it would solve the problem. But I Was wondering if there was a better way.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91562140
has comment: http://stackoverflow.com/comment/91562155

http://stackoverflow.com/comment/91650196
comment on: http://stackoverflow.com/q/52352524
has text: BTW for the parts where you compute random `startPositions` you could use something like [`random.shuffle`](https://docs.python.org/3/library/random.html#random.shuffle)
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/52396182
type: Answer
has body: You need to check for the case where the node is None (i.e the previous node was the last one) and treat that case differently, for instance: def reverse_str(node): if node is None: return None else: str_rep = str(node.val) # For str(node.val), there is a class function that returns # str(self.val) s = reverse_str(node.next) str_rep = s + ", " + str_rep if s else str_rep return str_rep three = LinkedNode(3, None) two = LinkedNode(2, three) one = LinkedNode(1, two) print(reverse_str(one)) Output 3, 2, 1
score: 0
answers question: http://stackoverflow.com/q/52395030

http://stackoverflow.com/a/52384235
type: Answer
has comment: http://stackoverflow.com/comment/91715148
has comment: http://stackoverflow.com/comment/91712504
upvote count: 1
has comment: http://stackoverflow.com/comment/91712751
has comment: http://stackoverflow.com/comment/91716051
has comment: http://stackoverflow.com/comment/91715341
score: 1
has comment: http://stackoverflow.com/comment/91715564
has comment: http://stackoverflow.com/comment/91713691
answers question: http://stackoverflow.com/q/52384084
has comment: http://stackoverflow.com/comment/91713971
downvote count: 0
has body: When you UPDATE, you need to add a condition, otherwise every row in the table is going to be updated with those values. In your code: c.execute('''UPDATE ahmed SET mth_friends = %s,mth_search = %s''', (mth_friends, mth_search)) Should have a condition, like this: c.execute('''UPDATE ahmed SET mth_friends = %s,mth_search = %s WHERE {ADD CONDITION HERE}''', (mth_friends, mth_search)) If you want to update or delete a single row, you want the condition to match a primary key or unique key column. Using a condition involving any other type of column will update or delete all rows matching that condition. (Thanks to Raymond Nijland)
has comment: http://stackoverflow.com/comment/91714783

http://stackoverflow.com/comment/92519597
score: 0
type: Comment
type: QuestionComment
has text: @ChristianWinther thats what I meant: The folders inside `/tmp/<username>/JModelica.org` are still there. They are not deleted.
comment on: http://stackoverflow.com/q/52420585

http://stackoverflow.com/comment/91626156
has text: The error command within the error stack trace `keyword_text_field.send_keys(keyword_text_field)` **doesn't matches** your code `keyword_text_field.send_keys('Ford')`
comment on: http://stackoverflow.com/q/52339411
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52389018
favorite count: 0
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/91722862
has answer: http://stackoverflow.com/a/52389120
upvote count: 3
has title: Pandas DataFrame Group and Rollup in one operation
downvote count: 0
accepted answer: http://stackoverflow.com/a/52389120
has body: I have a Pandas DataFrame with two columns "close_time" of a trade (DateTime format) and the "net_profit" from that trade. I have shared some sample data below. I need to find the count of total trades and count of profitable trades by day. So, for example, the output would look like +-----------------------------------------------------------+ | Close_day Total_Trades Total_Profitable_Trades | +-----------------------------------------------------------+ | 2014-11-03 5 4 | +-----------------------------------------------------------+ Can this be done using something like groupby? How? +------------------------------------+ | close_time net_profit | +------------------------------------+ | 0 2014-10-31 14:41:41 20.84 | | 1 2014-11-03 10:50:59 238.74 | | 2 2014-11-03 11:05:10 491.32 | | 3 2014-11-03 12:31:06 55.87 | | 4 2014-11-03 14:31:34 -402.29 | | 5 2014-11-03 20:33:29 164.18 | | 6 2014-11-04 16:30:24 -296.96 | | 7 2014-11-04 23:59:21 281.86 | | 8 2014-11-04 23:59:34 -296.37 | | 9 2014-11-05 10:14:42 517.55 | | 10 2014-11-05 20:38:49 350.35 | | 11 2014-11-07 11:23:31 710.13 | | 12 2014-11-07 11:23:38 137.55 | | 13 2014-11-11 19:00:01 201.97 | | 14 2014-11-11 19:00:15 -484.77 | | 15 2014-11-12 23:41:04 -1346.71 | | 16 2014-11-12 23:41:25 514.30 | | 17 2014-11-13 18:55:34 103.34 | | 18 2014-11-13 18:55:43 -180.37 | | 19 2014-11-26 17:10:59 -1756.69 | +------------------------------------+
tagged with: pandas-groupby
tagged with: pandas
type: AnsweredQuestion
score: 3
tagged with: python

http://stackoverflow.com/q/52274643
accepted answer: http://stackoverflow.com/a/52274849
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/91496769
tagged with: python
upvote count: 32
has comment: http://stackoverflow.com/comment/91496666
has title: figsize in matplotlib is not changing the figure size?
answer count: 2
has body: As you can see the code produces a barplot that is not as clear and I want to make the figure larger so the values can be seen better. This doesn't do it. What is the correct way? x is a dataframe and x['user'] is the x axis in the plot and x['number'] is the y. import matplotlib.pyplot as plt %matplotlib inline plt.bar(x['user'], x['number'], color="blue") plt.figure(figsize=(20,10)) The line with the plt.figure doesn't change the initial dimensions.
has answer: http://stackoverflow.com/a/52274849
tagged with: matplotlib
score: 32
linked to: http://stackoverflow.com/q/332289
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52274708
duplicate of: http://stackoverflow.com/q/332289
downvote count: 0
has answer: http://stackoverflow.com/a/52274708
favorite count: 0
has comment: http://stackoverflow.com/comment/91496580

http://stackoverflow.com/a/53978120
accepted answer of: http://stackoverflow.com/q/52358887
type: Answer
has body: Did you noticed you have this line in the image preparation. ## TODO: Rescale the detected face to be the expected square size for your CNN (224x224, suggested) roi = cv2.resize(roi, (244,244)) so you just resized it to 244x244 and not to 224x224.
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52358887

http://stackoverflow.com/comment/91790163
type: Comment
score: 0
type: AnswerComment
has text: not sure this will be significantly faster than a list comp.
comment on: http://stackoverflow.com/a/52423651

http://stackoverflow.com/comment/91703599
type: QuestionComment
has text: Do you mean that you get *empty output* or you get an Exception?
comment on: http://stackoverflow.com/q/52379582
score: 0
type: Comment

http://stackoverflow.com/a/52405829
downvote count: 0
has body: As @Umair said, you're passing those keys as URL query parameters, so you don't have to mention it in URLPATTERNS In your case, to get the data you're passing through the URL, follow the below code snippet #urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^api/foodfeed/', backend_views.FoodfeedList.as_view()), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) #views.py class FoodfeedList(APIView): # permission_classes = (permissions.IsAuthenticated,) def get(self, request): print(request.GET) # print all url params print(request.GET['keywords']) print(request.GET['mood']) # etc
score: 4
answers question: http://stackoverflow.com/q/52404081
type: Answer
upvote count: 4

http://stackoverflow.com/q/52396449
score: 0
tagged with: apache-spark
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91758870
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91739630
tagged with: python
has body: I have a spark job that performs some data analysis and there is a very long time between each job starting (1-2 hours). I know that some work isn't parallelized and doesn't count as a job so doesn't show up in the resource manager UI. I was hoping to find out what is taking so long? Here is my function: def analyse(df, columns): return reduce( lambda a, b: a.union(b), ( df.agg( F.count(F.when(F.isnull(c), c)).alias('NULL Count'), F.countDistinct(df[c]).alias('Distinct Values') ).select(F.lit(c).alias("Column Name"), "NULL Count", 'Distinct Values') for c in columns ) ) Any ideas?
has comment: http://stackoverflow.com/comment/91758669
type: Question
tagged with: hadoop
tagged with: pyspark
has title: Spark (Pyspark) - Long delay between jobs

http://stackoverflow.com/comment/91603609
type: Comment
comment on: http://stackoverflow.com/a/52328338
has text: You hardcode the variables: '_remainID1' to '_remainID4'... What happens, if someone has 1000 variables?
score: 2
type: AnswerComment

http://stackoverflow.com/comment/117952486
comment on: http://stackoverflow.com/a/52335971
type: AnswerComment
type: Comment
score: 7
has text: Escaping the backslash applies to regular expressions where you are escaping the dot. This is where it came up for me. See [my answer here to "Regular expression to match a dot"](https://stackoverflow.com/questions/13989640/regular-expression-to-match-a-dot/66666859#66666859). So, you must do `"\\."` or `r"\."` instead of `"\."`. Took me a while to figure out. Your answer helped. Thanks.

http://stackoverflow.com/comment/91490647
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52271543
has text: so I can't do the mean over them

http://stackoverflow.com/comment/91792639
comment on: http://stackoverflow.com/q/52424437
score: 0
has text: Does `all the squares involved` mean `all squares of the current piece of board`? That is the very first cut will always cost the sum of all cells of the board?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91559146
comment on: http://stackoverflow.com/a/52305865
score: 0
type: AnswerComment
type: Comment
has text: Wow. We are on a `nonzero` kick today.

http://stackoverflow.com/a/52351829
downvote count: 0
has comment: http://stackoverflow.com/comment/119175572
answers question: http://stackoverflow.com/q/52351756
has comment: http://stackoverflow.com/comment/115903765
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/99024673
score: 120
has comment: http://stackoverflow.com/comment/123247822
has body: When you are overriding model's save method in Django, you should also pass *args and **kwargs to overridden method. this code may work fine: def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height &gt; 300 or img.width &gt; 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path)'
type: Answer
accepted answer of: http://stackoverflow.com/q/52351756
upvote count: 120

http://stackoverflow.com/q/52317007
type: AnsweredQuestion
downvote count: 0
has body: I used Keras in Python to design a neural network calculating something like a noise-reducing-function. It works pretty good so far, and now I want to use this network to clean the data inside a Unity-Project of mine. I would not have thought that this could be so difficult. I could only find one python interpreter in the asset store, which does not support external python librarys. IronPython is not an option either, because I need to include the Keras Packages. I found a KerasSharp Project on GitHub, but there is no documentation on how to load an already trained network, and training it at the beginning is not an option. Furthermore it seems like there is no one working on the project anymore, due to the commit history and unanswered questions. Accessing the script via network APIs is probably not an good option either, due to the latency. I need the calculation for every frame. So my question is: Is there any way I can load a Keras/Tensorflow model in C# or Unity OR Can I somehow access the python script which is calculating the noise-reducing-function using the Keras model?
type: Question
tagged with: c#
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/52318176
accepted answer: http://stackoverflow.com/a/52318176
answer count: 1
tagged with: keras
favorite count: 0
tagged with: unity-game-engine
has title: Executing Python Script in C# or Unity
tagged with: python

http://stackoverflow.com/a/52401315
has comment: http://stackoverflow.com/comment/121683373
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/103213700
upvote count: 14
accepted answer of: http://stackoverflow.com/q/52400814
score: 13
answers question: http://stackoverflow.com/q/52400814
downvote count: 1
has body: You need to import src too and then reload(src.mymodule). from src import mymodule import src # Change in mymodule reload(src.mymodule)

http://stackoverflow.com/a/52429968
upvote count: 1
has comment: http://stackoverflow.com/comment/91805437
answers question: http://stackoverflow.com/q/52427926
downvote count: 0
score: 1
has body: This can be done in one line: z = [path +[i] for i in l if i not in path] (xenial)vash@localhost:~/python/stack_overflow$ python3.7 helping.py [['x', 'n1', 'y', 'z', 'n2', 'n3'], ['x', 'n1', 'y', 'z', 'n2', 'n4']]
has comment: http://stackoverflow.com/comment/91805444
type: Answer

http://stackoverflow.com/comment/91820283
type: Comment
type: QuestionComment
has text: I uninstalled Anaconda and then removed the .Jupyter directory through root access and it finally worked!
comment on: http://stackoverflow.com/q/52349503
score: 1

http://stackoverflow.com/q/52338163
type: Question
has answer: http://stackoverflow.com/a/52338827
tagged with: boolean
score: 0
has comment: http://stackoverflow.com/comment/91623625
has comment: http://stackoverflow.com/comment/91623713
answer count: 3
favorite count: 0
has comment: http://stackoverflow.com/comment/91628326
upvote count: 2
has comment: http://stackoverflow.com/comment/91623730
type: UnansweredQuestion
tagged with: python
has body: I am trying to solve this Boolean Input question but I can't figure out the answer. Here is what it says, We pass in 2 boolean inputs, cold and rainy. You should output a single string: ('cold' or 'warm') ' and ' ('rainy' or 'dry') based on these inputs. ('cold' or 'warm') means you should use on of the two words, depending on the input boolean value. for example False, True = 'warm and rainy' And here is my code: isCold= sys.argv[1] == 'True' isRainy= sys.argv[2] == 'True' if isCold: print('cold and rainy') elif isRainy: print('warm and rainy') else: print(cold and dry) I don't know what I can do to solve this.
has title: Boolean Inputs in Python
downvote count: 2
has answer: http://stackoverflow.com/a/52346632
has answer: http://stackoverflow.com/a/52338663

http://stackoverflow.com/a/52390459
type: Answer
has comment: http://stackoverflow.com/comment/91795523
downvote count: 0
answers question: http://stackoverflow.com/q/52389786
has body: You can use pandas.to_timedelta as shown in below code: # Input dataframe df = pd.DataFrame({'PXTIME': [40538.22, 131725.529]}) # Code to convert df['PXTIME'] = pd.to_timedelta(df['PXTIME'], unit='s') # Output dataframe PXTIME 0 0 days 11:15:38.220000 1 1 days 12:35:25.529000
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91729552
has comment: http://stackoverflow.com/comment/91730983

http://stackoverflow.com/comment/91722907
comment on: http://stackoverflow.com/q/52317084
score: 0
has text: OperationalError Traceback (most recent call last) <ipython-input-8-7afdcbb88c10> in <module>() 48 moudule text, 49 type text, ---> 50 desc text)''') 51 52 c.execute('''CREATE table function_table( OperationalError: table variable_table already exists
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91678246
type: QuestionComment
comment on: http://stackoverflow.com/q/52366314
type: Comment
has text: @MohammadZainAbbas, so if I understand that link correctly, I should create a venv for my project... and then just by copying the venv files into my deployment server it will run correctly, or do I have to configure something else?
score: 0

http://stackoverflow.com/q/52370910
type: Question
has body: I've recently moved into a company that has several testing tools/frameworks/languages, and I'm looking to consolidate these as efficiently as possible. Gauge is promising, but one question I'm already being asked is if Gauge will allow us to write implementation steps in Java for some tests and Ruby or Python for others. Does anyone have an example of Gauge working with several different languages?
tagged with: java
has title: Does the Guage test automation framework allow multiple languages to be used in the same repo?
tagged with: automated-tests
answer count: 1
has comment: http://stackoverflow.com/comment/91687434
score: 0
has answer: http://stackoverflow.com/a/52377661
tagged with: python
tagged with: ruby
type: UnansweredQuestion
tagged with: getgauge

http://stackoverflow.com/comment/91798302
comment on: http://stackoverflow.com/q/52426360
has text: Cherry picked an old script of mine, thats why lol. Sorry about that.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91656459
comment on: http://stackoverflow.com/q/52346297
has text: @user4815162342 I made another post that is a more clear on the issues. It also includes a node.js equivalent. https://stackoverflow.com/questions/52349205/aysnc-python-dragging-balls-compared-to-node-js
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91727667
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52385790
has text: @elias, For those pom.xml which are not include `<dependencyManagement>`, `find("*//{http://maven.apache.org/POM/4.0.0}dependencies")` will return None. Is it correct?

http://stackoverflow.com/comment/91578971
type: QuestionComment
comment on: http://stackoverflow.com/q/52315717
type: Comment
has text: The part I'm having problem is 'at least one letter' and 'not returning brackets'. Without those two requirements it's quite straightforward: `r'(>[A-Z0-9]{4}<)'` I'm not sure it's even possible with regex, is it?
score: 0

http://stackoverflow.com/comment/91651854
has text: I installed from an empty virtual environment, so no previous numpy install. I see for Anaconda, I just wondered why I have to "bother" installing Anaconda distribution...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52344889

http://stackoverflow.com/q/52398749
favorite count: 0
tagged with: word2vec
tagged with: python
has answer: http://stackoverflow.com/a/52399263
has title: Word2vec Skipgram codes
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52411127
has comment: http://stackoverflow.com/comment/91775386
accepted answer: http://stackoverflow.com/a/52411127
has comment: http://stackoverflow.com/comment/91742510
has comment: http://stackoverflow.com/comment/91742784
type: Question
has body: I build a program and a part of my program has a function to find the windowData with window_size = 2 My code: string = 'I', 'have', 'a', 'pen', 'to', 'use' window_size = 2 windowData = [] for lines in string: for index,word in enumerate(lines): for words in lines[max(index-window_size,0):min(index+window_size,len(string)+1)]: if words != word: windowData.append([word,words]) print(windowData) current output: [['I', 'have'], ['have', 'I'], ['a', 'I'], ['a', 'have'], ['pen', 'have']] From my understanding about the skip-gram it should be something like this, right? (Please correct me if I am wrong) Expected output: [['I', 'have'], ['I', 'a'], ['have', 'I'], ['have', 'a'], ['have', 'pen'], ['a', 'have'], ['a', 'I'], ['a', 'pen'],['a', 'to'], ['pen', 'a'], ['pen', 'have'], ['pen', 'to'], ['pen', 'use'], ['to', 'pen'], ['to', 'a'],['to', 'use'], ['use', 'pen'],['use', 'to']] I understand that learning only programming language alone is not enough but I should focus more on the problem solving. If possible, please suggest me some sites as well. Thank you.
possible better answer: http://stackoverflow.com/a/52399263
has comment: http://stackoverflow.com/comment/91742962
answer count: 2
upvote count: 1

http://stackoverflow.com/a/52372561
score: 1
has comment: http://stackoverflow.com/comment/91722205
has comment: http://stackoverflow.com/comment/91727423
upvote count: 1
has body: This is one way: It uses Python's textwrap module to "wrap" the text into maximum of 40 character lines, if you actually want to split words or whatever else it has those abilities too. from textwrap import wrap # File containing your text. with open("./Text Document.txt", 'r') as read_file: data = read_file.read() data_list = wrap(data, 40) # New file created with 40 + "+" per line. with open("./New Text Document.txt", 'w') as write_file: for data in data_list: write_file.write(data + "+\n") This will enforce a strict 40 character limit: # File containing your text. with open("./Text Document.txt", 'r') as read_file: data = read_file.read() data_list = [] b, e = 0, 40 while e &lt; len(data): data_list.append(data[b:e]) b += 40 e += 40 if e &gt; len(data): data_list.append(data[b:len(data)]) # New file created with 40 + "+" per line. with open("./New Text Document.txt", 'w') as write_file: for data in data_list: write_file.write(data + "+\n")
answers question: http://stackoverflow.com/q/52372428
type: Answer
has comment: http://stackoverflow.com/comment/91691768
has comment: http://stackoverflow.com/comment/91721726
downvote count: 0

http://stackoverflow.com/comment/91517452
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52284505
has text: I'm off my game today, try the general solution now, since that one is more useful than a hardcoded one :)

http://stackoverflow.com/q/52318311
has comment: http://stackoverflow.com/comment/91587914
has answer: http://stackoverflow.com/a/52329309
has comment: http://stackoverflow.com/comment/91586760
answer count: 3
has comment: http://stackoverflow.com/comment/91586462
has answer: http://stackoverflow.com/a/52328783
has title: Merging overlapping rectangle with OpenCV
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91593931
accepted answer: http://stackoverflow.com/a/52328783
upvote count: 2
has comment: http://stackoverflow.com/comment/91588973
tagged with: machine-learning
tagged with: computer-vision
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/91587189
has body: I'm using two Haar cascade algorithms (frontal and profile) with OpenCV at the same time to improve the face detection. Unfortunately, the detection is not working correctly and I don't know how to fix it. The return value is 2 (on a picture with 5 faces, normally detected) and all the rectangles have disappeared. This is the expected result (without the overlapping rectangles): This is the original picture (and also the result.jpg) if you want to make your own test. This is the code : import cv2 import numpy as np image=cv2.imread("/home/pi/Downloads/test.jpg") face_cascade=cv2.CascadeClassifier("/home/pi/opencv-3.4.0/data/haarcascades/haarcascade_frontalface_alt.xml") profil_cascade=cv2.CascadeClassifier("/home/pi/opencv-3.4.0/data/haarcascades/haarcascade_profileface_alt.xml") gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) face=face_cascade.detectMultiScale(gray, 1.06, 5) profil=profil_cascade.detectMultiScale(gray, 1.1, 5) combined_array=np.append(face, profil, axis=0) combined_list=combined_array.tolist() result=cv2.groupRectangles(combined_list,2) print("I've found "+str(len(result))+ " face(s)") for (x,y,w,h) in result[0]: cv2.rectangle(image,(x,y),(x+w,y+h),(0,0,255),2) cv2.imwrite("/home/pi/Download/result.jpg", image)
has comment: http://stackoverflow.com/comment/91604446
downvote count: 0
possible better answer: http://stackoverflow.com/a/54635568
favorite count: 0
has answer: http://stackoverflow.com/a/54635568

http://stackoverflow.com/comment/91701526
has text: @KhalilAlHooti data has a hourly resolution but it jumps from 13 to 20. I want to insert the missing rows ( 14, 15, 16,...) with Nan values for var1 and var 2 so that I can calculate Nans afterwards with simple techniques such as interpolatation.
comment on: http://stackoverflow.com/q/52378412
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52383577
linked to: http://stackoverflow.com/q/48541801
has comment: http://stackoverflow.com/comment/91711434
type: Question
has body: I am installing some python packages of an existed project and I am getting this error: error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ I found a solution to that by installing it using one of the visual studio's products here StackOverflow answer, however, want to know if there is another way without needing to install more than 1.7 gb. PS: I installed the standalone MSbuild tools and didn't work for me.
has answer: http://stackoverflow.com/a/65520606
has comment: http://stackoverflow.com/comment/91711448
answer count: 3
has answer: http://stackoverflow.com/a/52397318
downvote count: 0
tagged with: msbuild
has comment: http://stackoverflow.com/comment/91711308
favorite count: 0
has comment: http://stackoverflow.com/comment/91711510
linked to: http://stackoverflow.com/q/29846087
possible better answer: http://stackoverflow.com/a/64411115
has answer: http://stackoverflow.com/a/64411115
tagged with: python
upvote count: 13
tagged with: visual-studio
accepted answer: http://stackoverflow.com/a/52397318
type: AnsweredQuestion
has title: Installing MS C++ 14.0 for python without Visual Studio
score: 13

http://stackoverflow.com/a/52387425
downvote count: 0
type: Answer
has body: The canonical way of closing something no-matter-what-happens is to use context managers: with shelve.open(...) as myshelve: # ALL YOUR CODE HERE root.mainloop() This guarantees that shelve.close() will be called, even when you get any exceptions in the code. It is also the recommended way in the documentation: Do not rely on the shelf being closed automatically; always call close() explicitly when you don’t need it any more, or use shelve.open() as a context manager. Alternatively, since you're using tkinter, you can use the WM_DELETE_WINDOW event: import tkinter as tk root = tk.Tk() def when_window_is_closed(): myshelve.close() root.destroy() root.protocol("WM_DELETE_WINDOW", when_window_is_closed) root.mainloop() This method is worse because it depends on tk firing the event. Use the context manager method instead to cover all grounds.
has comment: http://stackoverflow.com/comment/91723055
score: 4
accepted answer of: http://stackoverflow.com/q/52387376
upvote count: 4
has comment: http://stackoverflow.com/comment/91720620
answers question: http://stackoverflow.com/q/52387376
type: AcceptedAnswer

http://stackoverflow.com/q/52392880
has body: I have a very large pandas dataframe. The dataframe looks like this: &gt;&gt; df "a_1" "a_2" "b_1" "c_2" ... "d_1" nan 0.2 nan nan "d_2" 0.1 nan nan 1 "e_1" nan 1 nan 0.2 "e_2" nan 0.05 0.1 0.7 "f_2" 0.2 0.5 0.3 0.9 ... Now I am trying to go through a list of tuples which contains some row and col names: t = [("d", "a"), ("d", "c") ...] For example, when i = ("d", "a"), I want to find out the values corresponded to a_1 and a_2, d_1 and d_2 and I used the following code to locate the values: s = df.loc[["d_1", "d_2" ], ["a_1", "a_2"]] # print(s) # "a_1" "a_2" # "d_1" nan 0.2 # "d_2 0.1 nan # convert to list and sort the values s = s.unstack().reset_index() s.columns = ["A","B", "Score"] scores = s.sort_values(by="Score", ascending=False).reset_index(drop=True) # pick the index(rank) I want and save the not-nan data to dictionary rank = 1 try: s = scores.loc[rank,:] except Exception: continue if str(s.Score) != "nan": d[(s.A, s.B)] = s.Score # output dictionary Now the above code works but takes too long, given len(t) = 28350 and I need to test 150+ sets of parameters. One iteration (one set of parameter) takes 3.5mins on the cluster. I am wondering if there is a better solution to this problem. Thanks in advance!
tagged with: bigdata
tagged with: python
score: 1
has title: locating values in (a very large) pandas dataframe and store to dictionaries
upvote count: 1
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/52393316
tagged with: optimization
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91662566
type: Comment
has text: Well I am sorry for that word but I stand by my answering rules. At least someone has to explain him/her what's wrong with his/her implementation and how to make it work. I chose to be that guy especially when OP's question and aim is crystal clear ;) Moreover providing a shorter solution without explaining how it works is no good
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52358882

http://stackoverflow.com/comment/91519434
type: AnswerComment
score: 0
type: Comment
has text: Thank you for the suggestion robinsax! I realized that I misled myself in presenting this question as I commented on user2357112's post - range doesn't always reset at 1000. Maybe it had to do with my working with strings. In any case, I will try out your suggestion and will comment back whether it solved my issue.
comment on: http://stackoverflow.com/a/52285545

http://stackoverflow.com/q/52348372
score: -3
answer count: 2
has comment: http://stackoverflow.com/comment/91642162
has body: I'm looking to write a function that can convert a string with a given base to a decimal number. Let's say the function is convert calling convert should give me the following output convert('3.14', base=10) ~= 3.14 convert('100.101', base=2) == 4.625
favorite count: 0
tagged with: python-3.x
has title: How to convert a string of a decimal number from any base to a decimal number?
tagged with: python
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52348648
type: Question
has comment: http://stackoverflow.com/comment/91642303
has answer: http://stackoverflow.com/a/52348641
downvote count: 5

http://stackoverflow.com/a/52323269
has body: If you convert this to a list, you can loop through it, and if it matches your criteria, add an extra version. For example: a = [1,2,1,2,1,1,2] long_a = [] for x in a: long_a.append(x) if x == 2: long_a.append(x)
answers question: http://stackoverflow.com/q/52323208
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/91594030
score: 1
downvote count: 0

http://stackoverflow.com/comment/91792497
type: Comment
comment on: http://stackoverflow.com/a/52424762
has text: but this will not work as required in question - from 2.17 it will give 2, but expected 3
type: AnswerComment
score: 0

http://stackoverflow.com/q/52408909
has title: Unable to display video from Youtube with Python and OpenCV
score: 0
has comment: http://stackoverflow.com/comment/91767602
linked to: http://stackoverflow.com/q/50185654
tagged with: pafy
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91764971
tagged with: python
tagged with: opencv
has comment: http://stackoverflow.com/comment/91772903
has body: I am trying to get video from Youtube using Python 3.5, OpenCV 3.4.3 and Pafy 0.5.4. The problem is that cv2.VideoCapture(video_from_url) does not see the video from url. I also have seen this topic previously. Here is the code that works well if video_from_url variable is replaced with a path to video on my local PC. import pafy import cv2 url = 'https://www.youtube.com/watch?v=iCSd0slqzcQ&amp;start_radio=1&amp;list=RDiCSd0slqzcQ' video_pafy = pafy.new(url) video_from_url = video_pafy.getbest().url cap = cv2.VideoCapture(video_from_url) while True: ret, frame = cap.read() print(ret) # False """ Further video processing """
type: Question
has comment: http://stackoverflow.com/comment/91785079
has comment: http://stackoverflow.com/comment/91772750

http://stackoverflow.com/comment/134831741
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52401546
type: AnswerComment
has text: If you want a static port e.g. `1433` then also verify: Right click `TCP/IP`, `Properties`, check `Listen All` is `Yes` and `IP Addresses` tab scroll to bottom and verify `IPAll` is [**blank**](https://learn.microsoft.com/en-us/sql/tools/configuration-manager/tcp-ip-properties-ip-addresses-tab?view=sql-server-ver16#static-vs-dynamic-ports) in `Dynamic Ports` and `1433` in `Port`.

http://stackoverflow.com/q/52386379
score: 0
has comment: http://stackoverflow.com/comment/91717539
has comment: http://stackoverflow.com/comment/91717680
has comment: http://stackoverflow.com/comment/91717450
type: UnansweredQuestion
has title: Allow automatic redirection of the browser using Django and Meraki Captive Portal API
tagged with: django
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/92585013
has comment: http://stackoverflow.com/comment/91717827
has comment: http://stackoverflow.com/comment/91717710
has body: I am working with the Meraki Captive Portal API. The flow is like this. Login form containing username and password. I collect the username and password from the form and I POST the details to a login URL provided which handles the authentication. Once authentication is successful, the API redirects the user to a new page. This is done automatically. Code for login is as below: def index(request): # if this is a POST request we need to process the form data if request.method == 'POST': username = request.POST['username'] code = request.POST['code'] login_url = request.session['login_url'] continue_url = 'http://' + request.get_host() + reverse('splash:home') login_params = {"username": username, "password": code, "continue_url": continue_url} r = requests.post(login_url, params=login_params) # if a GET (or any other method) we'll create a blank form else: login_url = request.GET['login_url'] continue_url = request.GET['continue_url'] ap_name = request.GET['ap_name'] ap_mac = request.GET['ap_mac'] ap_tags = request.GET['ap_tags'] client_ip = request.GET['client_ip'] client_mac = request.GET['client_mac'] request.session['login_url'] = login_url request.session['continue_url'] = continue_url request.session['ap_name'] = ap_name request.session['ap_mac'] = ap_mac request.session['ap_tags'] = ap_tags request.session['client_ip'] = client_ip request.session['client_mac'] = client_mac return render(request, 'splash/index.html') The problem is here: r = requests.post(login_url, params=login_params, allow_redirects=True) Everything goes fine. However, am not being redirect when the Meraki API does a GET request. Am still at the login page. What can I do to the view to allow the redirect being done by the API. On the console, I can see the page being called but the browser does not show the home page. [18/Sep/2018 14:56:20] "GET /splash/home/ HTTP/1.1" 200 1234 [18/Sep/2018 14:56:20] "POST /splash/ HTTP/1.1" 200 2333 Any help is much appreciated.
type: Question

http://stackoverflow.com/q/52306041
tagged with: python
has title: How to increase item in a tuple
has comment: http://stackoverflow.com/comment/91663722
has body: 6 and im trying to create sort of a loop to increase the item in a tuple example; list = [1,2,3] print (list[0]*&lt;----this is where im trying to create a loop*) (so the output shows this) out: 1 basically separate the integers and use them individually in a loop this is what i got so far list = [1, 2, 3] list2 = [11, 12, 13] i = (0) i = i+1 print ("tuples", list[0+i], list2[0+i]) but i got this as a result out: 2, 12 and im trying to get this as a result out: 1, 11 out: 2, 12 out: 3, 13
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52306067
has answer: http://stackoverflow.com/a/52306195
tagged with: loops
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/52306195
tagged with: tuples
has comment: http://stackoverflow.com/comment/91559406
score: 0
has answer: http://stackoverflow.com/a/52306067

http://stackoverflow.com/comment/91633338
has text: Your previous answer was deleted by a moderator due to not actually being an answer (originally), and can only be undeleted by a moderator. If you want to post your own solution, just create another answer, if possible.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52336317

http://stackoverflow.com/q/52395023
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52400463
has body: Info: I am a HS student who is learning how to code and I don't know of anyone who can check my logic for me, so I am using the kind souls of Stack Overflow to help check my thinking. Actual question: I am learning about sorting, and I want to know if I actually understand what is going on during the swapping proccess. my_list = [1, 2] my_list[0], my_list[1] = my_list[1], my_list[0] print(my_list) Output: [2, 1] Here is what I think this does. I set what ever is in the 0th position of my_list = to whatever is in the 1st position of my_list, which is basically saying, "Hey, trade values!". Then I do the same thing with the first position of my_list, accept I set it = what ever is in the 0th position of my list. What I think this does, and correct me if I'm wrong, is that is sets the value of the 0th position = to the value of the 1st position, and it sets the value of the 1st position = to the value of the 0th position. This in turn changes the values of the list elements, making it look as though they have traded places. Is this correct or am I overthinking this? I know this sounds like basic assignment, but I want to make sure I fully understand this concept of swapping.
tagged with: python
type: AnsweredQuestion
upvote count: 0
tagged with: list
has title: Am I swapping elements from a list correctly?
has answer: http://stackoverflow.com/a/52400463
type: Question
score: -1
tagged with: sorting
has comment: http://stackoverflow.com/comment/91735236
has comment: http://stackoverflow.com/comment/91735181
answer count: 1
downvote count: 1
tagged with: swap
favorite count: 0

http://stackoverflow.com/q/52368607
score: 1
has comment: http://stackoverflow.com/comment/91682434
has answer: http://stackoverflow.com/a/52370995
type: Question
has comment: http://stackoverflow.com/comment/91682359
has comment: http://stackoverflow.com/comment/91682027
has title: Django V2.1 reverse is not a valid view function or pattern name
has comment: http://stackoverflow.com/comment/91681824
answer count: 2
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91681943
type: UnansweredQuestion
has body: I am very new to Django and I have created two apps in my project one is login & server_status. I have used the namespace method to access my login and server_status across both apps. It is working fine when I tried to access index but when I tried to access dashboard in server_status it is not working. Reverse for 'server_status' not found. 'server_status' is not a valid view function or pattern name # server_status URL from django.urls import path from . import views urlpatterns = [ path('', include('server_status.urls', namespace='server_status')), path('', include('login.urls', namespace='login')), path('admin/', admin.site.urls), ] # login app URL app_name = 'login' urlpatterns = [ path('login', views.index, name='index') ] # project URL from django.contrib import admin from django.urls import include, path app_name = 'server_status' urlpatterns = [ path('', views.index, name='index'), path('dashboard/', views.dashboard, name='dashboard'), path('server_status/', views.server_status, name='server_status'), path('request_access/', views.request_access, name='request_access'), ] In server_status/templates/server_status/index.html Login I know this is very simple one, but it makes me very complicated.
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52380901
downvote count: 0

pipeline
type: Tag
tags question: http://stackoverflow.com/q/52310347
tags question: http://stackoverflow.com/q/52398849
tag name: pipeline
tags question: http://stackoverflow.com/q/52382517
tags question: http://stackoverflow.com/q/52357107

http://stackoverflow.com/a/52403355
score: 13
answers question: http://stackoverflow.com/q/52385299
upvote count: 13
has comment: http://stackoverflow.com/comment/91755761
accepted answer of: http://stackoverflow.com/q/52385299
has comment: http://stackoverflow.com/comment/117052806
has comment: http://stackoverflow.com/comment/91750468
has body: I finaly succeded in doing it. I am almost sure there is a better way to do it, but at leat it works: import numpy as np import numpy.random import matplotlib.pyplot as plt # To generate some test data x = np.random.randn(500) y = np.random.randn(500) XY = np.stack((x,y),axis=-1) def selection(XY, limitXY=[[-2,+2],[-2,+2]]): XY_select = [] for elt in XY: if elt[0] &gt; limitXY[0][0] and elt[0] &lt; limitXY[0][1] and elt[1] &gt; limitXY[1][0] and elt[1] &lt; limitXY[1][1]: XY_select.append(elt) return np.array(XY_select) XY_select = selection(XY, limitXY=[[-2,+2],[-2,+2]]) xAmplitudes = np.array(XY_select)[:,0]#your data here yAmplitudes = np.array(XY_select)[:,1]#your other data here fig = plt.figure() #create a canvas, tell matplotlib it's 3d ax = fig.add_subplot(111, projection='3d') hist, xedges, yedges = np.histogram2d(x, y, bins=(7,7), range = [[-2,+2],[-2,+2]]) # you can change your bins, and the range on which to take data # hist is a 7X7 matrix, with the populations for each of the subspace parts. xpos, ypos = np.meshgrid(xedges[:-1]+xedges[1:], yedges[:-1]+yedges[1:]) -(xedges[1]-xedges[0]) xpos = xpos.flatten()*1./2 ypos = ypos.flatten()*1./2 zpos = np.zeros_like (xpos) dx = xedges [1] - xedges [0] dy = yedges [1] - yedges [0] dz = hist.flatten() cmap = cm.get_cmap('jet') # Get desired colormap - you can change this! max_height = np.max(dz) # get range of colorbars so we can normalize min_height = np.min(dz) # scale each z to [0,1], and get their rgb values rgba = [cmap((k-min_height)/max_height) for k in dz] ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=rgba, zsort='average') plt.title("X vs. Y Amplitudes for ____ Data") plt.xlabel("My X data source") plt.ylabel("My Y data source") plt.savefig("Your_title_goes_here") plt.show() I use this example, but I modified it, because it introduced an offset. The result is this:
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/52344561
type: Answer
upvote count: 1
score: 1
has body: Kera's img_to_array() method takes a PIL.Image instance (as returned by load_img()) as its parameter, not the name of a file. So you will need to pass it the test_image you loaded in the first line: from keras.preprocessing import image test_image = image.load_img('dataset/kot/cat.1633.jpg', target_size=(64, 64)) test_image = image.img_to_array(test_image) Hth :) dtk PS As commented above, it's generally a good idea to paste the whole error message, including a stack trace, as - with some practice - that makes it much easier to understand what's going on. Also, showing the imports that are required to quickly reproduce the problem will make debugging way nicer
answers question: http://stackoverflow.com/q/52344347
accepted answer of: http://stackoverflow.com/q/52344347
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91554054
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52299007
score: 0
has text: I am still not able to get the desired result.

http://stackoverflow.com/a/52404292
answers question: http://stackoverflow.com/q/52404133
has comment: http://stackoverflow.com/comment/91752543
score: 0
has comment: http://stackoverflow.com/comment/91752445
accepted answer of: http://stackoverflow.com/q/52404133
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/91752356
has body: This will work: input1 = [4,6,8,10,12] out=[] for i in input1: phi=0.5+0.5*math.sqrt(5.0) a=phi*i out.append(i == 0 or abs(round(a) - a) &lt; 1.0 / i); To convert bool to int import numpy y=numpy.array(out) new_output = y*1

dataframe
tags question: http://stackoverflow.com/q/52306061
tags question: http://stackoverflow.com/q/52403400
tags question: http://stackoverflow.com/q/52406732
tags question: http://stackoverflow.com/q/52354246
tags question: http://stackoverflow.com/q/52426828
tags question: http://stackoverflow.com/q/52397468
tags question: http://stackoverflow.com/q/52405726
tags question: http://stackoverflow.com/q/52371457
tags question: http://stackoverflow.com/q/52423903
tags question: http://stackoverflow.com/q/52274857
tags question: http://stackoverflow.com/q/52273000
tags question: http://stackoverflow.com/q/52371894
tags question: http://stackoverflow.com/q/52395179
tags question: http://stackoverflow.com/q/52324657
tags question: http://stackoverflow.com/q/52335455
tags question: http://stackoverflow.com/q/52429216
tags question: http://stackoverflow.com/q/52386090
tags question: http://stackoverflow.com/q/52378412
tags question: http://stackoverflow.com/q/52370355
tags question: http://stackoverflow.com/q/52366558
tags question: http://stackoverflow.com/q/52386622
tags question: http://stackoverflow.com/q/52294471
tags question: http://stackoverflow.com/q/52396634
tags question: http://stackoverflow.com/q/52354832
tags question: http://stackoverflow.com/q/52388194
tags question: http://stackoverflow.com/q/52410684
tags question: http://stackoverflow.com/q/52353638
tags question: http://stackoverflow.com/q/52424603
tags question: http://stackoverflow.com/q/52311575
tags question: http://stackoverflow.com/q/52276658
tags question: http://stackoverflow.com/q/52324666
tags question: http://stackoverflow.com/q/52406918
tags question: http://stackoverflow.com/q/52395151
tags question: http://stackoverflow.com/q/52280524
tags question: http://stackoverflow.com/q/52413715
tags question: http://stackoverflow.com/q/52299032
tags question: http://stackoverflow.com/q/52314867
tags question: http://stackoverflow.com/q/52298586
tags question: http://stackoverflow.com/q/52388586
tags question: http://stackoverflow.com/q/52391664
tags question: http://stackoverflow.com/q/52420056
tags question: http://stackoverflow.com/q/52340045
tags question: http://stackoverflow.com/q/52312211
tags question: http://stackoverflow.com/q/52371329
tags question: http://stackoverflow.com/q/52306525
tags question: http://stackoverflow.com/q/52326479
tags question: http://stackoverflow.com/q/52373464
tags question: http://stackoverflow.com/q/52350833
tags question: http://stackoverflow.com/q/52336218
tags question: http://stackoverflow.com/q/52392880
tags question: http://stackoverflow.com/q/52355225
tags question: http://stackoverflow.com/q/52423654
tags question: http://stackoverflow.com/q/52386793
tags question: http://stackoverflow.com/q/52399725
tags question: http://stackoverflow.com/q/52319356
tags question: http://stackoverflow.com/q/52339140
tags question: http://stackoverflow.com/q/52346751
tags question: http://stackoverflow.com/q/52305974
tags question: http://stackoverflow.com/q/52293079
tags question: http://stackoverflow.com/q/52322000
tags question: http://stackoverflow.com/q/52323681
tags question: http://stackoverflow.com/q/52392992
tags question: http://stackoverflow.com/q/52344070
tags question: http://stackoverflow.com/q/52274223
tags question: http://stackoverflow.com/q/52321152
tags question: http://stackoverflow.com/q/52354800
tags question: http://stackoverflow.com/q/52350324
tags question: http://stackoverflow.com/q/52377432
tags question: http://stackoverflow.com/q/52296757
tags question: http://stackoverflow.com/q/52304546
tags question: http://stackoverflow.com/q/52349995
tags question: http://stackoverflow.com/q/52413106
tags question: http://stackoverflow.com/q/52392728
tags question: http://stackoverflow.com/q/52342176
tags question: http://stackoverflow.com/q/52331557
tags question: http://stackoverflow.com/q/52402886
tags question: http://stackoverflow.com/q/52287641
tags question: http://stackoverflow.com/q/52312128
tags question: http://stackoverflow.com/q/52347052
tags question: http://stackoverflow.com/q/52300894

http://stackoverflow.com/q/52403922
type: Question
score: 5
has comment: http://stackoverflow.com/comment/91784748
has comment: http://stackoverflow.com/comment/91783096
answer count: 1
tagged with: xattr
linked to: http://stackoverflow.com/q/11005303
favorite count: 0
has title: Python Module xattr has no attribute list
has comment: http://stackoverflow.com/comment/91774194
tagged with: python-3.x
upvote count: 5
has body: I wrote a script which sets extended attributes on some files, with the module xattr. I successfully tested it in Ubuntu in python3, but it won't work on my RasperryPi. I had to change a dozens of little errors, mostly like xattr not knowing its methods. For example the xattr.set(...) has to be changed to xattr.setattr(...). But I failed at listing them. So I tried the just the basics and get the error: import xattr xattr.list('files.py') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: module 'xattr' has no attribute 'list' I had the idea that maybe python is using the wrong module (for python 2.7 instead of 3?). So I tried to uninstall the 2.7 module but got this: ...$ pip uninstall xattr Traceback (most recent call last): File "/usr/local/bin/pip", line 7, in &lt;module&gt; from pip._internal import main ImportError: No module named _internal But I could successfully uninstall the python3 package. After that the "import xattr" still worked even in python3?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91784724
tagged with: python
tagged with: module
has answer: http://stackoverflow.com/a/57724756
downvote count: 0

http://stackoverflow.com/q/52297890
tagged with: python
tagged with: gradient
type: Question
has title: Finding max gradient of irregular data series from csv
has body: Python noob here, but I am attempting to find the max gradient of a dataset (reading from a csv file, with two columns: force and displacement, irregular intervals). I think I have done it correctly based on a simpler example I tested, but I want to check that I should be using diff or whether is there a better, more efficient function to use? import pandas as pd import csv import numpy as np df = pd.read_csv(r'C:\Data\Specimen_RawData_1.csv', header=10) blah = df[(df.Displacement &gt;= 0.05) &amp; (df.Displacement &lt;=0.6)] #crop dataset y = blah['Force'] dy = np.diff(y) max_dy = max(dy) x = blah['Displacement'] dx = np.diff(x) max_dx = max(dx) grad = 1. * max_dy/max_dx print grad
tagged with: numpy
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52298046
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/a/52367241
has comment: http://stackoverflow.com/comment/91678667
has body: Your question is not about python, it is about signal processing. There are many techniques and issues around phase estimation. For instance, in periodic signals (such as Cosine or a square wave) there are infinite correct answers since the real phase shift + integer times of the period will give the same result. On the other hand, even in non-periodic signals, such as one impulse, noise may effect the phase detection, in some cases more than others. This field is broad and the answer strongly depend on what you want to achieve and the data quality. Having said that, here is my output from your data (two components) using ACF as a first step for the inspection, I don't see a problem with it: EDIT: Added some corrections and changed signals to the real targets. ANOTHER EDIT: Regarding phase shift estimation, there are many ways to do so. Please research the traditional literature for answers and explore techniques oriented for your type of data. My suggestions: First peak of ACF can be a good answer. Projection on sine waves (partial Fourier series) and adjusting the phase at the largest coefficients. Phase detection based on fitting the same models and inspection of parameters (can be done automatic, depends on the model). Using an envelope detector (for this data) and detecting the phases between the two upper lines and the two bottom lines. You'll get two estimations, you can take the average. Use more preprocessing - trend and seasonality decomposition, and take the seasonality component for inspecting the phase. There are many ways, these just pop up right away. I'm sure that by playing with it a little you can find that suits your data in a reasonable computation time so it will be applicable for your product. Good luck! Here is the code: # just some imports import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.style.use('ggplot') # load data df = pd.read_csv('c:\\Temp\\curve_fitting_ahmed.csv') # normalization before ACF def normalize(data…
has comment: http://stackoverflow.com/comment/91681411
has comment: http://stackoverflow.com/comment/91680944
type: Answer
has comment: http://stackoverflow.com/comment/91681729
has comment: http://stackoverflow.com/comment/91680427
has comment: http://stackoverflow.com/comment/91679317
has comment: http://stackoverflow.com/comment/91678913
has comment: http://stackoverflow.com/comment/91679860
has comment: http://stackoverflow.com/comment/91680548
has comment: http://stackoverflow.com/comment/91679359
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52366673
answers question: http://stackoverflow.com/q/52366673
has comment: http://stackoverflow.com/comment/91681091
has comment: http://stackoverflow.com/comment/91679197
has comment: http://stackoverflow.com/comment/91680733
has comment: http://stackoverflow.com/comment/91679418
has comment: http://stackoverflow.com/comment/91680401
has comment: http://stackoverflow.com/comment/91679137
has comment: http://stackoverflow.com/comment/91855642
has comment: http://stackoverflow.com/comment/91679546
has comment: http://stackoverflow.com/comment/91679905
has comment: http://stackoverflow.com/comment/91678743
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91679178
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91679450

http://stackoverflow.com/comment/91786578
type: Comment
comment on: http://stackoverflow.com/a/52421459
has text: So basically I should have it where df_categories.parents == "0"?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91695341
has text: @user2357112: That edit wasn't actually necessary; `__builtins__` (with `s`) is a weird auto-imported CPython implementation detail that provides the same attributes as the official (but not auto-imported) `__builtin__` (without `s`) provides. I'll grant the distinction is confusing, so it doesn't hurt anything to use `__builtin__` consistently.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52375161

rfid
tag name: rfid
tags question: http://stackoverflow.com/q/52343386
type: Tag

http://stackoverflow.com/comment/91740052
score: 1
type: Comment
comment on: http://stackoverflow.com/q/52397832
type: QuestionComment
has text: Floats aren't good for working with currency. Better to use integer values in pennies.

http://stackoverflow.com/comment/91695320
score: 0
type: Comment
has text: In JSON, `[]` creates a list, you need to use numeric indicecs access its elements, `{}` creates a dictionary, it has string indices.
comment on: http://stackoverflow.com/a/52375122
type: AnswerComment

http://stackoverflow.com/q/52326223
tagged with: list
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
has answer: http://stackoverflow.com/a/52326257
has body: I'm a python newbie and I need to read and manipulate elements from a json file, but I keep getting errors and I have no idea how to move forward. This is my code: import json with open('file.txt', 'r') as json_data: d = json.load(json_data) An example of the dataset: [ { 'id': 1, 'name': 'a', 'city': 'Paris' }, { 'id': 2, 'name': 'b', 'city': 'Mons' }, { 'id': 3, 'name': 'c.', 'city': 'Leuven' } ] When I try to get only id or name, I get this error: city = d['city'] TypeError Traceback (most recent call last) in () ----> 1 city = d['city'] TypeError: list indices must be integers or slices, not str Then I tried this: city = d[:]['city'] TypeError Traceback (most recent call last) in () ----> 1 city = d[:]['city'] TypeError: list indices must be integers or slices, not str Any ideas? Thanks!
downvote count: 1
type: Question
score: 0
answer count: 3
has title: Reading and manipulating JSON elements on Python
has comment: http://stackoverflow.com/comment/91599470
has answer: http://stackoverflow.com/a/52326340
has answer: http://stackoverflow.com/a/52326599
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91599416
tagged with: python

http://stackoverflow.com/q/52385753
possible better answer: http://stackoverflow.com/a/52385835
has answer: http://stackoverflow.com/a/52385835
accepted answer: http://stackoverflow.com/a/52385858
score: -1
type: Question
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/91715969
has comment: http://stackoverflow.com/comment/91715668
favorite count: 0
has title: Selection of a letter in a text in a matrix
has answer: http://stackoverflow.com/a/52385858
has body: I am a total beginner in python. I need to autogenerate an email. I have the following info # following list in the order of Forname, familyname, birthyear info = [['Jens','Jensen',1993], ['Hans','Hansen',1992], ['John','Johnsen',1991], ['Anders','Andersen',1990], ['David','Davidsen',1989]] The condition of the email is the First letter in the first name, 5 first letter in the family name and the last two number in the birth year. An ex of an email: J.Jense.93@python.com So far I have the following code: for info_fn_fl, in info[0][0][0]: print info_fn_fl J Hope you can help.
tagged with: python
has comment: http://stackoverflow.com/comment/91743676
downvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/q/52373571
tagged with: pip
tagged with: python
tagged with: opencv
has comment: http://stackoverflow.com/comment/91692504
has answer: http://stackoverflow.com/a/59681326
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91693839
upvote count: 7
answer count: 1
has title: Could not find a version that satisfies the requirement cv2
has body: Obviously, I'm new to these problems, but I have a weird problem: I'm using MacOS and I'm using Mac Terminal. I installed opencv and even I saw its version and I was able to import cv2, but I wonder why I'm not able to install cv2 in pycharm? I tried, but pycharm gives me this error: (Could not find a version that satisfies the requirement cv2 (from versions: No matching distribution found for cv2) and it also says you are using pip version 10.0.1 however version 18.0 is available It's really ridiculous, because I updated pip to version 18, but apparently pycharm doesn't understand... Does anyone know how to fix these errors?
favorite count: 0
tagged with: pycharm
type: UnansweredQuestion
score: 6
has comment: http://stackoverflow.com/comment/91693583

http://stackoverflow.com/comment/91819440
type: Comment
has text: Answering there.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52315402

http://stackoverflow.com/comment/91774620
type: AnswerComment
score: 0
type: Comment
has text: This is extremely inefficient (a property common to most attempts to use dict comprehensions to perform aggregation). Every `count` call requires a complete pass over `arr`.
comment on: http://stackoverflow.com/a/52415556

http://stackoverflow.com/comment/91740647
has text: Thanks, liked and upvoted your answer. and the fact that you are 9th grader impressed me, keep up the good work :)
type: Comment
comment on: http://stackoverflow.com/a/52397970
score: 1
type: AnswerComment

http://stackoverflow.com/comment/91734875
has text: this answer wouldn't work.. the first line waits for the element to become stale, then it tries to find/click the stale element (which is impossible).
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52391462
type: AnswerComment

http://stackoverflow.com/a/52277403
has body: No need for five independent variables; just declare one list, and append to it as necessary. def MyFunction(params_to_opt): results = [] if 'a' in params_to_opt: results.append(...) if 'b' in params_to_opt: results.append(...) if 'c' in params_to_opt: results.append(...) if 'd' in params_to_opt: results.append(...) if 'e' in params_to_opt: results.append(...) return results
accepted answer of: http://stackoverflow.com/q/52277370
has comment: http://stackoverflow.com/comment/91503768
answers question: http://stackoverflow.com/q/52277370
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91503691
has comment: http://stackoverflow.com/comment/91506038
score: 5
type: Answer
has comment: http://stackoverflow.com/comment/91504166
has comment: http://stackoverflow.com/comment/91502890
has comment: http://stackoverflow.com/comment/91504488
has comment: http://stackoverflow.com/comment/91504120
upvote count: 5

http://stackoverflow.com/q/52291734
score: 4
accepted answer: http://stackoverflow.com/a/52292785
tagged with: user-interface
downvote count: 1
has answer: http://stackoverflow.com/a/52292785
favorite count: 0
tagged with: python-3.x
upvote count: 5
tagged with: python
type: AnsweredQuestion
tagged with: pyqt5
has title: PyQt5 mouse hover functions
type: Question
has body: Hi I'm new in Python and PyQt5. I want to make a GUI for DVR client. I am faced with a problem that I can't solve that I need to change a label pic by mouse hovering on that, how can I do that? from PyQt5 import QtCore, QtWidgets class Widget(QtWidgets.QWidget): def __init__(self, parent=None): super(Widget, self).__init__(parent) lay = QtWidgets.QVBoxLayout(self) self.btn = QtWidgets.QPushButton("Press me") self.btn.installEventFilter(self) lay.addWidget(self.btn) lay.addWidget(QtWidgets.QLineEdit()) def eventFilter(self, obj, event): if obj == self.btn and event.type() == QtCore.QEvent.HoverEnter: self.onHovered() return super(Widget, self).eventFilter(obj, event) def onHovered(self): print("hovered") if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) w = Widget() w.show() sys.exit(app.exec_())
answer count: 1

http://stackoverflow.com/comment/91737739
comment on: http://stackoverflow.com/q/52390449
score: 0
type: Comment
type: QuestionComment
has text: sorry for that. this is the first time i use stackoverflow. What you said cannot solve the problem. i change my model name to model1.h5. If i load model with wrong name, the Pycharm will raise an error with no found "model.h5", not TypeError.

http://stackoverflow.com/comment/91537435
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52294701
has text: @Mayur I thought of storing it in the database ... but .. will it follow the FIFO approach ?
score: 0

http://stackoverflow.com/a/52354544
score: 3
has comment: http://stackoverflow.com/comment/91654229
has comment: http://stackoverflow.com/comment/91653813
has comment: http://stackoverflow.com/comment/91654015
downvote count: 0
answers question: http://stackoverflow.com/q/52354491
has comment: http://stackoverflow.com/comment/91653983
type: Answer
has body: You should use prefetch_related for multiple relations. Also argument of prefetch_related should be related_name value, or audiolinks_set in your case: a_release = self.queryset.prefetch_related('audiolinks_set').get(pk=kwargs['release_id']) See docs: select_related is limited to single-valued relationships - foreign key and one-to-one.
has comment: http://stackoverflow.com/comment/91654296
upvote count: 3
has comment: http://stackoverflow.com/comment/91653925

http://stackoverflow.com/comment/91679670
type: Comment
comment on: http://stackoverflow.com/a/52367706
has text: How does this work when e.g. subclassing `CreateAPIView` and overwriting `self.post`? In the end of that method, `return self.create(request, *args, **kwargs)` is called. So I need to pass on the original request object. How do I deal with that?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91601595
score: 1
has text: `these are binary variables` is 1 > 0 and 0 < 1 for both x and y, or have you encoded two categories as 0 and 1? if the latter, you cannot perform correlation, but you can fit a classification algorithm of some sort and read its parameters after fitting.
comment on: http://stackoverflow.com/q/52326174
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52321063
has comment: http://stackoverflow.com/comment/91609780
has body: I think this is some sort of bug of TexSoup. Namely, if you remove the first line or comment out second line instead, the TexSoup is able to parse the file and print(soup) will give some output. In addition, if you terminate the first line by adding braces: %{\documentstyle[aps,epsf,rotate,epsfig,preprint]{revtex}} the TexSoup is also able to parse the file.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52316900
has comment: http://stackoverflow.com/comment/91594240

http://stackoverflow.com/comment/91498949
has text: Thanks for that - seems to do what I was after, indeed. Is there a chance to retain the values for DE and still keep the Product column? E.g. just change the data in the input DataFrame instead creating a separate one?
comment on: http://stackoverflow.com/a/52275491
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/52400473
tagged with: gitlab
tagged with: gitlab-api
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52405648
score: 1
has title: Add project avatar in gitlab using API
type: Question
has comment: http://stackoverflow.com/comment/91748065
has answer: http://stackoverflow.com/a/52405648
downvote count: 0
has comment: http://stackoverflow.com/comment/91748537
linked to: http://stackoverflow.com/q/40887151
has body: During a migration from gitswarm to gitlab we lost all of the projects avatar. I'm trying to restore them via a python script, but while it is clear how to set the path of the avatar via the project settings API, I do not understand how to upload the avatar. I searched the GitLab API documentation, but I was not able to find anything. Can someone help me please? PS: GitLab API: upload projects avatar is of no help, since nobody explained the upload command
answer count: 1

http://stackoverflow.com/q/52304373
type: Question
has title: reference of ARIMA in python
tagged with: arima
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52312015
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 0
tagged with: statsmodels
score: -1
has body: I used statsmodels.tsa.arima_model import ARIMA in Python to develop an ARIMA model. Recently I am writing the methodology of ARIMA, but I can not find any reference on the page. So here my question is where could I find the reference (or formula) used statsmodels.tsa.arima_model import ARIMA in Python? Thank you in advance.

http://stackoverflow.com/comment/91547808
type: AnswerComment
comment on: http://stackoverflow.com/a/52285432
type: Comment
has text: So there is no way of adding methods to a Mock object?
score: 0

http://stackoverflow.com/q/52395626
tagged with: google-cloud-platform
has body: I am deploying a Google Cloud Function based on code in a BitBucket repository. I have already linked up the BitBucket account to Google Cloud "Source Repositories" and the Google Function can find the repo, etc. The problem is that my main.py function needs to call several functions in other packages/modules within my repository. I have some simple import statements at the top of my main.py file like this: import base64 import json from datetime import datetime from competitor_scrape.headless import headless_browser ... The first several lines load fine, but the 4th line (the one that call the module/function within my BitBucket repository) causes this error in Google Functions when I try to define my Google Cloud Function with the main.py in my repository: message: "Function load error: Code in file main.py can't be loaded. Did you list all required modules in requirements.txt? Detailed stack trace: Traceback (most recent call last): File "/env/local/lib/python3.7/site-packages/google/cloud/functions_v1beta2/worker.py", line 211, in check_or_load_user_function _function_handler.load_user_function() File "/env/local/lib/python3.7/site-packages/google/cloud/functions_v1beta2/worker.py", line 140, in load_user_function spec.loader.exec_module(main) File "&lt;frozen importlib._bootstrap_external&gt;", line 728, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 219, in _call_with_frames_removed File "/user_code/main.py", line 4, in &lt;module&gt; from competitor_scrape.headless import headless_browser ModuleNotFoundError: No module named 'competitor_scrape.headless' It asks if I have "list[ed] all of the required modules in requirements.txt". Am I allowed to list the modules from my own repository? If so, how should I be doing that? I haven't been able to find any documentation on how to do this. My current requirements.txt file looks like this: google-cloud-pubsub numpy==1.14.5 pandas==0.22.0 psycopg2==2.7.4 selenium==3.4.3 geopy==1.11.0 googlemaps==2.5.…
downvote count: 0
favorite count: 0
tagged with: google-cloud-functions
tagged with: python
tagged with: requirements.txt
tagged with: git
has answer: http://stackoverflow.com/a/52432377
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52396301
upvote count: 3
has comment: http://stackoverflow.com/comment/91737267
has answer: http://stackoverflow.com/a/59312982
type: Question
has title: ModuleNotFoundError when setting up Google Cloud Function with Cloud Source repository
accepted answer: http://stackoverflow.com/a/52432377
possible better answer: http://stackoverflow.com/a/59312982
answer count: 3

http://stackoverflow.com/comment/91515375
comment on: http://stackoverflow.com/a/52283325
has text: @BobFromBilling in java there is a main class that must necessarily have the method public static void main (...), called main function, that is equivalent to `if __name__ ==" __main __ ":`, in the case of python you can have those functions in all the .py and many times it is used to test a component, but only the `if __name__ ==" __main __ ":` of the file that is launched, the others will be ignored. Python is not Java, python does not comply with java rules, I think you want to have a main.py file where only that function exists: am I right?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91723027
has text: I already mentioned how to get the associated pet_ids, and similar code could be used for cars
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52387322
type: QuestionComment

python-2.7
tags question: http://stackoverflow.com/q/52311738
tags question: http://stackoverflow.com/q/52398186
tags question: http://stackoverflow.com/q/52370396
tags question: http://stackoverflow.com/q/52317455
tags question: http://stackoverflow.com/q/52344126
tags question: http://stackoverflow.com/q/52357029
tags question: http://stackoverflow.com/q/52398039
tags question: http://stackoverflow.com/q/52316455
tags question: http://stackoverflow.com/q/52325901
tags question: http://stackoverflow.com/q/52301568
tags question: http://stackoverflow.com/q/52292196
tags question: http://stackoverflow.com/q/52313838
tags question: http://stackoverflow.com/q/52337901
tags question: http://stackoverflow.com/q/52421855
tags question: http://stackoverflow.com/q/52420291
tags question: http://stackoverflow.com/q/52379701
tags question: http://stackoverflow.com/q/52413906
tags question: http://stackoverflow.com/q/52277812
tags question: http://stackoverflow.com/q/52369293
tags question: http://stackoverflow.com/q/52414003
tags question: http://stackoverflow.com/q/52280584
tags question: http://stackoverflow.com/q/52293422
tags question: http://stackoverflow.com/q/52328134
tags question: http://stackoverflow.com/q/52323907
tags question: http://stackoverflow.com/q/52406175
tags question: http://stackoverflow.com/q/52428396
tags question: http://stackoverflow.com/q/52343946
tags question: http://stackoverflow.com/q/52285454
tags question: http://stackoverflow.com/q/52308498
tags question: http://stackoverflow.com/q/52295849
tags question: http://stackoverflow.com/q/52343201
tags question: http://stackoverflow.com/q/52406466
tags question: http://stackoverflow.com/q/52333190
tags question: http://stackoverflow.com/q/52424246
tags question: http://stackoverflow.com/q/52306584
tags question: http://stackoverflow.com/q/52411036
tags question: http://stackoverflow.com/q/52398022
tags question: http://stackoverflow.com/q/52313325
tags question: http://stackoverflow.com/q/52305532
tags question: http://stackoverflow.com/q/52356531
tags question: http://stackoverflow.com/q/52412177
tags question: http://stackoverflow.com/q/52281909
tags question: http://stackoverflow.com/q/52397563
tags question: http://stackoverflow.com/q/52311003
tags question: http://stackoverflow.com/q/52317544
tags question: http://stackoverflow.com/q/52323642
tags question: http://stackoverflow.com/q/52369509
tags question: http://stackoverflow.com/q/52425237
tags question: http://stackoverflow.com/q/52284072
tags question: http://stackoverflow.com/q/52317636
tags question: http://stackoverflow.com/q/52349692
tags question: http://stackoverflow.com/q/52350352
tags question: http://stackoverflow.com/q/52424437
tags question: http://stackoverflow.com/q/52316063
tags question: http://stackoverflow.com/q/52373807
tags question: http://stackoverflow.com/q/52311560
tags question: http://stackoverflow.com/q/52381909
tags question: http://stackoverflow.com/q/52319353
tags question: http://stackoverflow.com/q/52310217
tags question: http://stackoverflow.com/q/52294172
tags question: http://stackoverflow.com/q/52405726
tags question: http://stackoverflow.com/q/52334086
tags question: http://stackoverflow.com/q/52421166
tags question: http://stackoverflow.com/q/52404416
tags question: http://stackoverflow.com/q/52392046
tags question: http://stackoverflow.com/q/52347052
tags question: http://stackoverflow.com/q/52425735
tags question: http://stackoverflow.com/q/52307081
tags question: http://stackoverflow.com/q/52411944
tags question: http://stackoverflow.com/q/52281671
tags question: http://stackoverflow.com/q/52412297
tags question: http://stackoverflow.com/q/52332915
tags question: http://stackoverflow.com/q/52404849
tags question: http://stackoverflow.com/q/52298700
tags question: http://stackoverflow.com/q/52342123
tags question: http://stackoverflow.com/q/52336569
tags question: http://stackoverflow.com/q/52409724
tags question: http://stackoverflow.com/q/52425055
tags question: http://stackoverflow.com/q/52278610
tags question: http://stackoverflow.com/q/52411630

http://stackoverflow.com/a/52286134
type: Answer
has body: You can try elevate the exec function. index = [1,2,4,8,16,32,64] index2 = [100, 1000, 10000, 100000, 1000000] for i in index: for j in index2: exec("temp_variable = df_foo_{0}_{1}".format(i, j)) temp.append(temp_variable)
has comment: http://stackoverflow.com/comment/91520577
has comment: http://stackoverflow.com/comment/91520517
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52286085
score: 0
accepted answer of: http://stackoverflow.com/q/52286085

http://stackoverflow.com/a/52333233
downvote count: 0
has body: UPDATED: An API is now documented here: https://cloud.ibm.com/apidocs/metering-reporting OLD: I couldn't find a documented API but used the tracing to see how the above commands are executed. Using a valid access_token a program can call the metering host and obtain usage data for an account, resource group or all resource instances: A GET on the following URL with an account ID and month as YYYY-MM returns a JSON object with all resource usage and related cost: https://metering-reporting.ng.bluemix.net/v4/accounts/account_id/resource_instances/usage/?_limit=100&_names=true I coded up a small Python script that dumps that data or prints it as CSV. def processResourceInstanceUsage(account_id, billMonth): METERING_HOST="https://metering-reporting.ng.bluemix.net" USAGE_URL="/v4/accounts/"+account_id+"/resource_instances/usage/"+billMonth+"?_limit=100&_names=true" url=METERING_HOST+USAGE_URL headers = { "Authorization": "{}".format(iam_token), "Accept": "application/json", "Content-Type": "application/json" } response=requests.get(url, headers=headers) print ("\n\nResource instance usage for first 100 items") return response.json()
type: Answer
accepted answer of: http://stackoverflow.com/q/52333121
answers question: http://stackoverflow.com/q/52333121
upvote count: 3
score: 3
type: AcceptedAnswer

http://stackoverflow.com/a/52300848
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52300690
has body: Try df['greater'] = (df.iloc[:, 1:4].values &gt; df'Mean'.values).sum(axis=1) df['less'] = (df.iloc[:, 1:4].values &lt; df'Mean'.values).sum(axis=1) df['count'] = df.iloc[:, 1:4].count(1) APPL Std_1 Std_2 Std_3 Mean greater less count 0 ACCMGR 106.8754 130.1600 107.1861 114.750510 1 2 3 1 ACCOUNTS 121.7034 113.4927 114.5482 116.581458 1 2 3 2 AUTH 116.8585 112.4487 115.2700 114.859050 2 1 3
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52300690
upvote count: 1

http://stackoverflow.com/q/52413881
has comment: http://stackoverflow.com/comment/91771533
tagged with: python
has comment: http://stackoverflow.com/comment/91771532
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91771534
tagged with: list
linked to: http://stackoverflow.com/q/6294179
has body: Let me have a long list: l = ['a', 'b', 'c', 'a', 'b', 'a', 'c', ...] I want to get the indices of all 'a'. Unfortunately, l.index('a') will only output the index of 'a''s first occurrence. I can get them by doing: [idx for idx,i in enumerate(l) if i == 'a'] Is that the common way, or there is a built-in function? I am thinking when to use .index if it only outputs the index of the first occurrence.
has title: How to get index of multiple elements of list in python?
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91771800
duplicate of: http://stackoverflow.com/q/6294179

http://stackoverflow.com/comment/91642282
type: QuestionComment
comment on: http://stackoverflow.com/q/52348199
has text: BTW, `if x < self.width and x >= 0:` looks nicer like this: `if 0 <= x < self.width:`
score: 1
type: Comment

http://stackoverflow.com/comment/92592924
type: Comment
comment on: http://stackoverflow.com/a/52363018
score: 0
type: AnswerComment
has text: Can you please help with this: https://stackoverflow.com/questions/52829141/query-tangled-array-in-pymongo

http://stackoverflow.com/a/52384933
upvote count: 1
answers question: http://stackoverflow.com/q/52379437
score: 1
has body: requests does not support asyncio. If you want to go for true asynchronous execution, you will have to look at libs like aiohttp or asks Your set should be built before offloading to the tasks, so you don't even execute for duplicates, instead of streamlining the result. With requests itself, you can fall back to run_in_executor which will execute your requests inside a ThreadPoolExecutor, so not really asynchronous I/O: import asyncio import time from requests import exceptions, get def _url_exists(url): try: r = get(url, timeout=10) except (exceptions.ConnectionError, exceptions.ConnectTimeout): return False else: return r.status_code is 200 async def _remove_unexisting_urls(l, r): # making a set from the list before passing it to the futures # so we just have three tasks instead of nine futures = [l.run_in_executor(None, _url_exists, url) for url in set(r)] return [await f for f in futures] rows = [ # added some dupes 'http://example.com/', 'http://example.com/', 'http://example.com/', 'http://example.org/', 'http://example.org/', 'http://example.org/', 'http://foo.org/', 'http://foo.org/', 'http://foo.org/', ] loop = asyncio.get_event_loop() print(time.time()) result = loop.run_until_complete(_remove_unexisting_urls(loop, rows)) print(time.time()) print(result) Output 1537266974.403686 1537266986.6789136 [False, False, False] As you can see, there is a penalty from initializing the thread pool, ~2.3 seconds in this case. However, given that fact that each of the three tasks runs for ten seconds until timeout on my box (my IDE is not allowed through the proxy), an overall of twelve seconds execution time looks quite concurrent.
downvote count: 0
type: Answer

http://stackoverflow.com/comment/130230164
has text: I do like this solution, `class MsgType(str, Enum):`
type: Comment
comment on: http://stackoverflow.com/a/52335501
score: 0
type: AnswerComment

http://stackoverflow.com/q/52310791
tagged with: keyboard
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
has title: Catching a keyboard hit is not reliable / Python
type: Question
has body: The background is to design a program, which is running in an endless loop, to read live data from somewhere. I want this program to be controlled by interactions through keyboard (without 'Enter'). For this purpose I came across the following snippet. import msvcrt def keypress(): try: if msvcrt.kbhit(): #Keyboard hit? key = msvcrt.getch().decode("utf-8").lower() return key except UnicodeDecodeError: pass while not False: print('rainy rainy rain rain') if keypress() == "e": #e: exit exit() if keypress() == "w": # w: wait waiting = True while waiting == True: print("waiting waiting waiting") if keypress() == "w": waiting = False I know its frivolous to call a new endless loop just for waiting, but the crazy thing is the hit of "e" seems to be more often succesful than the hit of the "w". But in every case some few hits aren't even registered by no means at all. -> Is there way this issue can be solved? Windows as well is able to catch every keyboard hit!
tagged with: keypress
tagged with: msvcrt
has answer: http://stackoverflow.com/a/52313235

annotate
tags question: http://stackoverflow.com/q/52286497
tag name: annotate
type: Tag

http://stackoverflow.com/a/52338841
type: Answer
has comment: http://stackoverflow.com/comment/91635905
has body: Have you enabled the Text-To-Speech API for your project? Or if you're just running it locally, have you set application default credentials? It's possible that you doesn't have the correct permissions and the request to the Text-To-Speech API is timing out. I was able to get this working on App Engine as follows: In app.yaml: runtime: python37 In requirements.txt: flask google-cloud-texttospeech In main.py: from flask import Flask, Response from google.cloud import texttospeech app = Flask(__name__) @app.route("/") def hello(): client = texttospeech.TextToSpeechClient() input_text = texttospeech.types.SynthesisInput(text="Hi, what's up") voice = texttospeech.types.VoiceSelectionParams( language_code="en-US", ssml_gender=texttospeech.enums.SsmlVoiceGender.MALE, ) audio_config = texttospeech.types.AudioConfig( audio_encoding=texttospeech.enums.AudioEncoding.MP3 ) response = client.synthesize_speech(input_text, voice, audio_config) return Response(response.audio_content, mimetype='audio/mp3')
has comment: http://stackoverflow.com/comment/91644818
score: 0
answers question: http://stackoverflow.com/q/52336941

http://stackoverflow.com/comment/91616592
type: AnswerComment
comment on: http://stackoverflow.com/a/52334227
type: Comment
has text: Thanks very much, but this is only a small example on a bigger Problem. Actually there are 15 Columns and 50.000 Rows and Sub-Frames.
score: 0

http://stackoverflow.com/q/52424401
tagged with: google-app-engine
has comment: http://stackoverflow.com/comment/91821583
tagged with: python
has title: Google App Engine - Python - Task Queue - How can i add a list of tasks?
score: 2
has comment: http://stackoverflow.com/comment/91795244
type: AnsweredQuestion
has body: I have this code that works fine: taskqueue.add(url = MY_URL, params={'id': 42}, queue_name='random-message') In this official document it says: "Adds a task or list of tasks into this queue." But I can't understand how. I already tried this: tasks = [] tasks.append(taskqueue.Task(url = MY_URL, params={'id': 42})) taskqueue.add(tasks, queue_name='random-message') but It raises an error that I don't understand: 'Task payloads must be strings; invalid payload: %r' % payload) I tried many others little variants that weren't working anyway.
downvote count: 0
type: Question
linked to: http://stackoverflow.com/q/34456738
upvote count: 2
has answer: http://stackoverflow.com/a/52428815
accepted answer: http://stackoverflow.com/a/52439507
answer count: 2
tagged with: task-queue
possible better answer: http://stackoverflow.com/a/52428815
favorite count: 0
has answer: http://stackoverflow.com/a/52439507

http://stackoverflow.com/comment/91724148
comment on: http://stackoverflow.com/q/52389205
type: QuestionComment
type: Comment
score: 1
has text: I am sure it needs to be `multiprocessing.Process(target=show_cam)` without the `()`

http://stackoverflow.com/a/52348005
has body: You made an wrong which is in there total = total + math.sqrt(x) the wrong is that you should find the squared x Not square root of x so try my fixed code:- def rms(): print("This program will calculate the RMS of your values.\n") n = int(input("Please enter the number of values you want calculated: ")) total = 0.0 for i in range(n): x = float(input("Enter a desired values:")) total += x ** 2 #it means x powered by two print("\nThe Root Mean Square is:", math.sqrt(total/n))
answers question: http://stackoverflow.com/q/52347671
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52347671
type: Answer

http://stackoverflow.com/comment/91807631
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52411321
type: Comment
has text: I see. Well, I'm not trying to be a PITA, but I think if you better define what "interpolation" means here, how you should connect them will directly fall out of that. As it stands, there are a bunch of ways you could connect the two (for instance, getting the distance from each pixel in mask 1 to mask 2, and only drawing ones under a certain "close enough" distance). But this is currently ill-posed as it stands. Also, can you show the code you used for your `minAreaRect()`? I've never seen one that far off before, perhaps you're drawing it with some thickness on the borders?

http://stackoverflow.com/comment/91570904
comment on: http://stackoverflow.com/a/52311847
type: Comment
has text: what shortcut keys?
score: 0
type: AnswerComment

http://stackoverflow.com/q/52335797
tagged with: database
score: 0
has comment: http://stackoverflow.com/comment/91619284
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91618795
tagged with: python
answer count: 0
has body: It is the science fair and for this year I want to make something that could actually be used (and maybe get me to the next round). I thought of an online backpack. I have tried to learn a little bit of Python and thought this would be a good language to start with. Basically I want to let pictures of assignments be put into folders organized by classes so you can access work from a mobile device. How can I start on this?
has title: Using Python Open Source to Create an Organized Picture Library
type: Question

http://stackoverflow.com/q/52416191
score: 2
has comment: http://stackoverflow.com/comment/91916917
downvote count: 0
has title: pd.to_datetime doesn't respect the format
has body: I have the following dataframe: month value 0 1949-01 3 1 1949-02 4 2 1949-03 5 df['month'] = pd.to_datetime(df['month'], format= '%Y/%m') I would like to obtain the month in the following format: 1949/01 But the output is always this: month value 0 1949-01-01 3 1 1949-02-01 4 2 1949-03-01 5 Why does it automatically add the day and doesn't respect the format?
type: Question
has answer: http://stackoverflow.com/a/52421717
tagged with: time-series
upvote count: 2
answer count: 2
accepted answer: http://stackoverflow.com/a/52416428
favorite count: 0
possible better answer: http://stackoverflow.com/a/52421717
has answer: http://stackoverflow.com/a/52416428
tagged with: datetime
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/91802479
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52378262
type: Comment
has text: One more question, if I may. I see that using the sym function takes up considerable memory. I was under the impression that making a matrix symmetric would require at most twice as much memory as the original matrix (since the upper triangle already includes the diagonal). But using sym, the memory taken up by the matrix increases by more than 4 folds. Do you know why this happens? Perhaps because Python lists allocate extra space with append. Is there a way to avoid this problem?

http://stackoverflow.com/q/52306858
accepted answer: http://stackoverflow.com/a/52339527
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91565053
has comment: http://stackoverflow.com/comment/91561814
score: 0
has comment: http://stackoverflow.com/comment/91624266
has title: KNN ValueError: Input contains NaN, infinity or a value too large for dtype('float64')
type: Question
has comment: http://stackoverflow.com/comment/91560952
has comment: http://stackoverflow.com/comment/91564985
has answer: http://stackoverflow.com/a/52339527
answer count: 1
tagged with: nan
has comment: http://stackoverflow.com/comment/91626282
has body: here is my code, it's supposed to be a simple regression algorithm. The data set has about 500 samples, each of them have 12 factors. I received this error though: ValueError: Input contains NaN, infinity or a value too large for dtype('float64'). Code: dataset = pd.read_csv('/Users/chrisrivas/Documents/Andrew Haines/Datasets/GRD.csv', header=None, sep=',') #coverts dataset into 2d array of values and seperates target column #[1st to: last rows, and 1st to: 12th columns ] samples = dataset.loc[:, 1:12].values targets = dataset[13].values print(samples) print(targets) #training and testing of dataset X_train, X_test, y_train, y_test = cross_validation.train_test_split( samples, targets, test_size=0.35, random_state=0) knn = KNeighborsClassifier(n_neighbors=1) knn.fit(X_train, y_train) y_pred = knn.predict(X_test) #calculates accuracy of algorithm print("Test set score: {:.2f}%".format(np.mean(y_pred == y_test)*100)) #opens new data for algorithm to make classification predictions dataset2 = pd.read_csv('/Users/chrisrivas/Documents/Datasets/GoldRushDataset-41.csv', header=None, sep=',').values #continues to loop for each sample and their classification prediction for sample in dataset2: prediction = knn.predict([sample]) print("Prediction: {}".format(prediction)) print(' ') #other format for predictions: all at a time in array prediction = knn.predict(dataset2) print("Prediction: {}".format(prediction))
tagged with: python

http://stackoverflow.com/a/52319603
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52319567
has body: Your problem is in this expression: len(cards - 1) cards appears to be a list; you can't subtract 1 from a list. I suspect that you mean len(cards) - 1
score: 3
answers question: http://stackoverflow.com/q/52319567
type: AcceptedAnswer
upvote count: 3
type: Answer

http://stackoverflow.com/comment/91516387
type: Comment
comment on: http://stackoverflow.com/a/52283830
score: 1
type: AnswerComment
has text: Thanks so much! You're right I was doing ('False',) == "False". Once I changed that it worked! Thank you again

http://stackoverflow.com/q/52385888
has body: I would like to search a customfield and it's ID, after a field name. In Jira there can be some customfields and every has a name, which can't be seen in a log file. For example I have the name: Markets, and I want to search which customfield (customfield_xxxxx) refers to this name. Thank you for your answers! :)
possible better answer: http://stackoverflow.com/a/52386001
has comment: http://stackoverflow.com/comment/91746676
downvote count: 1
tagged with: jira
has answer: http://stackoverflow.com/a/52404129
upvote count: 0
has title: Searching customfield after a field name
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91715944
accepted answer: http://stackoverflow.com/a/52404129
score: -1
favorite count: 0
type: Question
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52386001

http://stackoverflow.com/a/52383362
has body: So here's my take :D I expect you'd want to have the numbers parsed as well? def generate_kv(fileName): with open(fileName, 'r') as file: # ignore first line file.readline() for line in file: if '' == line.strip(): # empty line continue values = line.split(' ') try: yield values[0], [float(x) for x in values[1:]] except ValueError: print(f'one of the elements was not a float: {line}') if __name__ == '__main__': x = [] y = [] for key, value in generate_kv('sample.txt'): x.append(key) y.append(value) print(x) print(y) assumes that the values in sample.txt look like this: % cat sample.txt 29 16 A 1.2595034 0.82587254 0.7375044 1.1270138 -0.35065323 0.55985355 0.7200067 -0.889543 0.2300735 0.56767654 0.2789483 0.32296127 -0.6423197 0.26456305 -0.07363393 -1.0788593 B 1.2467299 0.78651106 0.4702038 1.204216 -0.5282698 0.13987103 0.5911153 -0.6729466 0.377103 0.34090135 0.3052503 0.028784657 -0.39129165 0.079238065 -0.29310825 -0.99383247 and the output: % python sample.py ['A', 'B'] [[1.2595034, 0.82587254, 0.7375044, 1.1270138, -0.35065323, 0.55985355, 0.7200067, -0.889543, 0.2300735, 0.56767654, 0.2789483, 0.32296127, -0.6423197, 0.26456305, -0.07363393, -1.0788593], [1.2467299, 0.78651106, 0.4702038, 1.204216, -0.5282698, 0.13987103, 0.5911153, -0.6729466, 0.377103, 0.34090135, 0.3052503, 0.028784657, -0.39129165, 0.079238065, -0.29310825, -0.99383247]] Alternatively, if you'd wanted to have a dictionary, do: if __name__ == '__main__': print(dict(generate_kv('sample.txt'))) That will convert the list into a dictionary and output: {'A': [1.2595034, 0.82587254, 0.7375044, 1.1270138, -0.35065323, 0.55985355, 0.7200067, -0.889543, 0.2300735, 0.56767654, 0.2789483, 0.32296127, -0.6423197, 0.26456305, -0.07363393, -1.0788593], 'B': [1.2467299, 0.78651106, 0.4702038, 1.204216, -0.5282698, 0.13987103, 0.5911153, -0.6729466, 0.377103, 0.34090135, 0.3052503, 0.028784657, -0.39129165, 0.079238065, -0.29310825, -0.99383247]}
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52382780
answers question: http://stackoverflow.com/q/52382780
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/91617335
type: Comment
has text: what do you expect other than what you already have?
score: 1
comment on: http://stackoverflow.com/q/52335033
type: QuestionComment

http://stackoverflow.com/q/52294663
score: 0
accepted answer: http://stackoverflow.com/a/52294970
downvote count: 2
has comment: http://stackoverflow.com/comment/91668795
has comment: http://stackoverflow.com/comment/91536958
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52294970
tagged with: python
type: AnsweredQuestion
tagged with: machine-learning
tagged with: text-classification
has title: Classifying data into 3 classes with a binary classifier model
type: Question
has comment: http://stackoverflow.com/comment/91537188
has body: Hi I am new to Machine Learning. I have a task of classifying data into 3 classes. I have data for only 2 classes. I have used SVM Linear Classifier for the classes for which I have data (2 classes say A and B). Now there is another third class C for which I don't have any data. is there a way that I can use this binary classifier and predict if a sample doesn't belong to any of the 2 classes(A and B) then it must belong to C ?
has comment: http://stackoverflow.com/comment/91668758
tagged with: svm
upvote count: 2

http://stackoverflow.com/comment/91622391
has text: the order is not important. I've tried the first solution, and it seems to give me the results that I wanted. But can you please explain to me in the normal for-loop, instead of list comprehension. Because I will be dealing with more for-loops in my actual data (standford parser) , hence i wish to understand more of your solution. I'm weak in list comprehension. @DYZ
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52337285

http://stackoverflow.com/comment/92056250
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52513729
has text: True: indeed, you can’t read a pcap as text but as binary with its own format. You’ll have to implement magic handling and lots of stuff if not using an already existing API
score: 0

http://stackoverflow.com/comment/91669470
type: Comment
has text: try `conda remove opencv` then `pip install opencv`. from your conda terminal.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52362389

http://stackoverflow.com/a/52370638
downvote count: 0
answers question: http://stackoverflow.com/q/52370380
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/91686831
score: 2
has body: Seems like they are list , then we using set set(df1)-set(df2) Out[398]: {4, 5}
has comment: http://stackoverflow.com/comment/91686258

http://stackoverflow.com/comment/91712763
has text: If you are learning Python in 2018, you should definitely be targeting the currently recommended and supported version of the language, which is Python 3. Version 2 was originally slated to be end-of-lifed already, although it got a couple of miserable extra years in terminal care.
type: QuestionComment
comment on: http://stackoverflow.com/q/52384142
type: Comment
score: 1

http://stackoverflow.com/a/52339612
accepted answer of: http://stackoverflow.com/q/52339274
downvote count: 0
has comment: http://stackoverflow.com/comment/91627142
score: 1
answers question: http://stackoverflow.com/q/52339274
has comment: http://stackoverflow.com/comment/91626552
has body: You need to move the input (where the user enters a binary number) outside the loop that's processing it. Then you have string containing ones (1) and zeros (0) which you can loop through. Starting at the right-hand end of the string, multiply that number (1 or 0) by 1 (let's call this multiplier the ordinal) and save the result as total. Multiply the ordinal by 2. Grab the next number (from the right) from the input string and multiply it by the ordinal, add the result to total. Keep going, multiplying the ordinal and using that to multiply the next number from the input string, until you run out of "numbers" in the input string. Print total
has comment: http://stackoverflow.com/comment/91627073
upvote count: 1
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/91627221

http://stackoverflow.com/a/52384849
has body: This code will insert 3 columns; It keeps the background color but not all of the borders. merged_cells_range = ws.merged_cells.ranges for merged_cell in merged_cells_range: merged_cell.shift(3,0) ws.insert_cols(1,3)
answers question: http://stackoverflow.com/q/52310732
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91713800
upvote count: 1
type: Answer

http://stackoverflow.com/comment/91784998
score: 0
type: Comment
has text: @MTTI Ok thanks, anyways o gave two solutions then maybe one will work for him
type: AnswerComment
comment on: http://stackoverflow.com/a/52420785

http://stackoverflow.com/comment/91704165
type: Comment
comment on: http://stackoverflow.com/a/52361601
type: AnswerComment
has text: Hi @GordThompson - Are you able to connect to unicode named database? If yes, can you please share the code you run? I tried everything but I haven't got any luck in connecting to the database with unicode chars.
score: 0

http://stackoverflow.com/comment/91717924
score: 0
has text: It looks like tweepy is not currently updated to support the new endpoints. There are some [open Github issues with some workarounds](https://github.com/tweepy/tweepy/issues/1081) that may help you, but until the library is updated it will not be very straightforward.
comment on: http://stackoverflow.com/q/52377403
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52278019
has comment: http://stackoverflow.com/comment/91722018
type: Question
has body: I am using Python 2.7 and pexpect 4.6.0 As per pexpect docs: If you wish to read up to the end of the child’s output without generating an EOF exception then use the expect(pexpect.EOF) method. But when I try that, it raises EOF exception. How can I expect EOF and get all output returned by the child? child = pexpect.spawn("ssh user@server") child.expect("[pP]assword") child.sendline("password") child.expect("\$") print child.before + child.after child.sendline("ifconfig") child.expect(pexpect.EOF) # this throws Exception The docs also say this: Some UNIX platforms will throw an exception when you try to read from a file descriptor in the EOF state. Other UNIX platforms instead quietly return an empty string to indicate that the EOF state has been reached. How can we know if this is the issue? And what could be a workaround for it?
tagged with: pexpect
score: 0
has title: pexpect expect(pexpect.EOF) throws exception and not output
has comment: http://stackoverflow.com/comment/91722286
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91541577
tagged with: python
answer count: 0

http://stackoverflow.com/q/52328595
has title: How to pass plt object function of matplotlib to another method in python?
has answer: http://stackoverflow.com/a/52328681
tagged with: numpy
has body: Say I have a figure which I am able to generate using plt.show. Now I wish to pass off this plt object to a generic function like this - generate_figs(plt): frmt = ['jpg','png'] for i in frmt: plt.savefig('name.{}'.format(i)) generate_figs(plt) Can something like this be done?
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/52328681
has comment: http://stackoverflow.com/comment/91604054
tagged with: jupyter-notebook
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/91604005
type: Question
tagged with: matplotlib

http://stackoverflow.com/comment/91752161
type: QuestionComment
comment on: http://stackoverflow.com/q/52403018
score: 0
has text: I wasn't clear sorry. Yes, in Oracle target table definition, ID1 and ID2 are not NULLABLE
type: Comment

http://stackoverflow.com/comment/91573652
score: 0
has text: well that should have been the first comment. Not a condescending message followed by a down vote. I would have gladly updated the snippet.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52311958

http://stackoverflow.com/q/52336816
has comment: http://stackoverflow.com/comment/91621161
type: Question
has answer: http://stackoverflow.com/a/52337258
has body: I'm new at programming, and my first attempt at a program is a program that can add players to a file named whitelist.txt. I have a menu where the user can choose options and I want it to repeat after an option is chosen. However, the input does not work. This is my code: stuck_forever = True home_input = input('What you like to do?' + '\n 1) add a user to the whitelist' + '\n 2) list users in whitelist' + '\n&gt; : ') # appends the input to the whitelist text file if home_input == '1': a_whitelist = open ('whitelist.txt','a') input_username = input('Please enter the username you would like to whitelist: ') append_username = input_username + '\n' a_whitelist.write(append_username) a_whitelist.close() print('User added to the whitelist!\n') while stuck_forever == True: home_input = input('What you like to do?' + '\n 1) add a user to the whitelist' + '\n 2) list users in whitelist' + '\n&gt; : ') # prints the whitelist and counts the amount of players in the list if home_input == '2': open_whitelist = open('whitelist.txt','r') r_whitelist = open_whitelist.read() number_users = len(r_whitelist.split()) print(f'\nThere are {number_users} players whitelisted at the moment..' + '\n') print(r_whitelist) open_whitelist.close() while stuck_forever == True: home_input = input('What you like to do?' + '\n 1) add a user to the whitelist' + '\n 2) list users in whitelist' + '\n&gt; : ') it would be awesome if someone could help me out! thanks!
has answer: http://stackoverflow.com/a/52337019
upvote count: 0
has title: Repeat input after choice
favorite count: 0
tagged with: python-3.x
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/91621003
accepted answer: http://stackoverflow.com/a/52337019
has comment: http://stackoverflow.com/comment/91621053
has comment: http://stackoverflow.com/comment/91620845
downvote count: 2
has answer: http://stackoverflow.com/a/52337066
type: AnsweredQuestion
score: -2
possible better answer: http://stackoverflow.com/a/52337066

http://stackoverflow.com/comment/91567888
score: 4
comment on: http://stackoverflow.com/a/52310156
has text: So, you can see that the request is coming from Firefox, so the reference frame for the request is the browser, which means that you need to refer to the service from outside docker.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/52397145
tagged with: django
upvote count: 1
tagged with: python
downvote count: 1
type: AnsweredQuestion
has body: I'm trying to make simple form run but I have cost, I'm not using the forms.forms of django, I'm doing the forms from HTML directly. Well, my form simply has 1 file field and a post button, in the field I want to add an .xlsx and get data from that file and register it in a specific model but it gives me the following error: django.utils.datastructures.MultiValueDictKeyError: "'ar'" acontinuacion I want to show you how I have structured my code and I do not understand why I get an error, I would also like to give me an idea of ​​how to obtain the excel data that I select in the input file and register it in bd: View: from django.views.generic import View from django.shortcuts import render,redirect from condominio.models import * class TestExcel(View): def post (self, request, *args, **kwargs): print (request.FILES) file = request.FILES['ar'] return HttpResponse('this is post') def get(self, request, *args, **kwargs): return render(request ,'testing.html' ,{}) template : {% extends 'base.html' %} {% load staticfiles %} {% load static %} {% block content %} {% csrf_token %} File Submit send {% endblock %}
has answer: http://stackoverflow.com/a/52397183
type: Question
answer count: 1
has title: MultiValueDictKeyError Django
favorite count: 0
score: 0
accepted answer: http://stackoverflow.com/a/52397183
has comment: http://stackoverflow.com/comment/91738906

http://stackoverflow.com/comment/91623674
score: 0
type: AnswerComment
has text: @SuperGeo: I don't think so. The [`locals()` docs](https://docs.python.org/3/library/functions.html#locals) sort of vaguely allude to some of it, but the details are undocumented. Reading the [source](https://github.com/python/cpython/blob/v3.7.0/Python/bltinmodule.c#L1594) is frequently the best option.
type: Comment
comment on: http://stackoverflow.com/a/52337538

http://stackoverflow.com/q/52305685
has answer: http://stackoverflow.com/a/52305749
linked to: http://stackoverflow.com/q/24666602
tagged with: python
accepted answer: http://stackoverflow.com/a/52305746
answer count: 4
type: AnsweredQuestion
score: 2
tagged with: list
upvote count: 2
has answer: http://stackoverflow.com/a/52306731
type: Question
has body: What is the most efficient way to extract to a list the indices corresponding to the n highest values of another list, while preserving the list we're extracting the indices from? For example, let's say we have the following list of indices: foo = [107,6,34,12,82] If we requested the indices of the 2 highest values of the list foo, it should return us the following list: bar = [0,4] Here's what I'm running right now, it's really inefficient and not elegant at all and I don't really know how to improve it: foo = [107, 6, 34, 12, 82] tmp = list(foo) bar = [] no_of_indices_wanted = int(input()) for n in range(no_of_indices_wanted): bar.append(foo.index(max(foo))) foo.pop(foo.index(max(foo))) foo = tmp
has answer: http://stackoverflow.com/a/52305836
has answer: http://stackoverflow.com/a/52305746
possible better answer: http://stackoverflow.com/a/52305836
downvote count: 0
has title: Extract the indices of the n highest values in a list
favorite count: 0

http://stackoverflow.com/a/52290545
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91529233
type: Answer
has comment: http://stackoverflow.com/comment/91529067
has body: You should call the constructor of Popen with the command and arguments directly. Calling os.system would execute the command and return the exit code, which is not what you want to pass to Popen: output = subprocess.Popen('you-get -o videos ' + element, shell=True, stdout=subprocess.PIPE).communicate()[0]
has comment: http://stackoverflow.com/comment/91528861
accepted answer of: http://stackoverflow.com/q/52290482
has comment: http://stackoverflow.com/comment/91528968
answers question: http://stackoverflow.com/q/52290482
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/52400909
accepted answer: http://stackoverflow.com/a/52404773
type: Question
tagged with: mocking
downvote count: 0
answer count: 1
has title: Not able to mock a method
favorite count: 0
has answer: http://stackoverflow.com/a/52404773
tagged with: python
has body: I have this code i want to test in isolation in some_module.py import tarfile def function_to_test(path_to_tar): tar_file = tarfile.open(path_to_tar) for tar_info in tar_file.getmembers(): #some logic to test pass And i can't get to effectively mock tarfile methods so i can mimic a tar file without having to read from actual file, my current attempt looks as follows from unittest.mock import patch, Mock def test_DeepLabModel_unexistent_error(): tar_path = "/path/to/nowhere" import tarfile with patch.object(tarfile, 'open', autospec=True) as open_mock: open_mock.getmembers = Mock() open_mock.getmembers.return_value = ['a','b'] from some_module import function_to_test function_to_test(tar_path) pass This doesn't work, the call to "getmembers" in the test method just returns another MagicMock object and not the list of strings i'm providing, thus not iterating as it should. I've achieved my purpose using similar behavior in the past, but i can't understand why that doesn't work here.
upvote count: 3
tagged with: unit-testing
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/52428670
tagged with: scrapy
type: Question
has title: Can't send an email with Scrapy(1.5.1) in Python
has body: I am new to Python and Scrapy. All I want to achieve, is send a simple email, using only Scrapy. I have read the documentation from the creators' webpage and I must be missing something, but I can't quite put my finger on it. Here is the code: from scrapy import mail mailer = mail.MailSender(smtphost='smtp-mail.outlook.com', mailfrom='someone@hotmail.com', smtpuser='someone@hotmail.com', smtppass='mypassword', smtpport=587, smtptls=True, ) def send_mail(mail_sender): return mail_sender.send(to=["receiver@hotmail.com"], subject="Hello", body="Hello receiver", mimetype='text/plain') send_mail(mailer) Update: I am running this script with pycharm instead of using scrapy.cmdline. Does this have anything to do as to why my code is not working? This is the output I get: Process finished with exit code 0
accepted answer: http://stackoverflow.com/a/52428863
answer count: 1
tagged with: email
downvote count: 0
has comment: http://stackoverflow.com/comment/91801951
favorite count: 0
has answer: http://stackoverflow.com/a/52428863
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/comment/91733139
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52392993
has text: @chepner The output is a single number. How do you get O(n**2) from that?

http://stackoverflow.com/q/52350619
favorite count: 0
has answer: http://stackoverflow.com/a/52399332
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/52350639
tagged with: python
tagged with: ocr
possible better answer: http://stackoverflow.com/a/52399332
tagged with: python-tesseract
upvote count: 3
tagged with: tesseract
has body: I have a multiple page .tif file, I am trying to extract text from it using Tesseract OCR but I am getting this error TypeError: Unsupported image object Code from PIL import Image import pytesseract img = Image.open('Group 1/1_CHE_MDC_1.tif') text = pytesseract.image_to_string(img.seek(0)) # OCR on 1st Page text = ' '.join(text.split()) print(text) ERROR Any idea why its happening
type: AnsweredQuestion
score: 3
has title: Tesseract OCR fails on TIFF files
downvote count: 0
has answer: http://stackoverflow.com/a/52350639

minimax
type: Tag
tags question: http://stackoverflow.com/q/52419756
tag name: minimax

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

http://stackoverflow.com/q/52425163
upvote count: 2
has answer: http://stackoverflow.com/a/52425251
tagged with: django
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: django-views
tagged with: django-models
has comment: http://stackoverflow.com/comment/91793030
type: Question
has title: Django: how to process flat queryset to nested dictionary?
accepted answer: http://stackoverflow.com/a/52425251
downvote count: 0
has body: I have a table with data looking like this: |Country|State|City |Street| |-------|-----|-----|------| | USA | AZ |city1| str1 | | USA | AZ |city1| str2 | | USA | AZ |city2| str1 | | USA | AZ |city2| str3 | | USA | MN |city3| str4 | | MEX | CH |city4| str5 | | MEX | CH |city4| str6 | What is a proper way to convert this into nested dictionary? I expect the result looking like this: nested_dict = { 'USA':{ 'AZ':{ 'city1':['str1','str2'], 'city2':['str1','str3'], }, 'MN':{ 'city3':['str3','str4'], }, }, 'MEX':{ 'CH':{ 'city4':['str5','str6'], }, }, }
linked to: http://stackoverflow.com/q/26496831
answer count: 1
favorite count: 0

http://stackoverflow.com/a/52528601
answers question: http://stackoverflow.com/q/52420373
has body: We had a similar usecase and used a flow library which would capture the entire worflow based on a condition driven flow. You can look into Viewflow: https://github.com/viewflow/viewflow Basically it's like setting a flow and utilizing the condition to direct and redirect to different mechanism. Their simple quickstart page tells you how you can achive it: http://docs.viewflow.io/viewflow_quickstart.html I just tried some sample flow in your case: class CustomerProcessFlow(Flow): process_class = CustomerProcess start = ( flow.Start( views.CustomerOnBoardView # Let's say this is your customer onboard view fields=["customer_name", "customer_address", "customer_phone"] ).Permission( auto_create=True ).Next(this.validate_customer) ) validate_customer = ( flow.View( views.ValidateCustomerDataView # Validation for customer data, fields=["approved"] ).Permission( auto_create=True ).Next(this.loan_amount) ) loan_amount = ( flow.View( views.LoanView # Provide Loan fields=["loan_amount"] ).Permission( auto_create=True ).Next(this.check_customer_association) ) check_customer_association = ( flow.If(lambda customer_association: ! customer.type.normal) .Then(this.step_4_6) .Else(this.step_6_4) ) step_4_6 = ( flow.Handler ( this.check_load_credibility_data ) .Next( this.provide_bank_details_data ) ) step_6_4 = ( flow.Handler( this.provide_bank_details_data ) .Next(this.check_load_credibility) ) this.check_load_credibility = ( flow.Handler( this.check_load_credibility_data ) .Next( this.end ) ) this.provide_bank_details_data = ( flow.Handler( this.provide_bank_details_data ) .Next(this.end) ) end = flow.End() def check_load_credibility_data(self, customer): # Load credibility def provide_bank_details_data(self, customer): # Bank Details An example can be seen here
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/91506999
score: 0
type: AnswerComment
has text: so if i have HI-Hello. it would go to Hihello and not just Hi-Hello. I want to only remove it if the first character is alpha numeric like -Hi = Hi
type: Comment
comment on: http://stackoverflow.com/a/52279253

http://stackoverflow.com/q/52342124
downvote count: 0
type: UnansweredQuestion
type: Question
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91633791
has title: How to display multiple table/chart in jupyter cells using panda?
has body: Emphasis : I am looking for a way to display multiple tables or charts from a cell. I have the following code where I have a table and a chart (and a few more) that I would like to display all those visuals in the out put shell after running it. I tried importing matplotlib and plt.show() but they don't seem to work. import pandas as pd import matplotlib.pyplot as plt %matplotlib inline tab = [[49.0,35.5,26.7,17.5], [46.7,34.0,26.0,17.1]] tab = list(map(list, zip(*tab))) tab_DataFrame = pd.DataFrame(tab, columns=["Mass(g)", "Volume(mL)"]) tab_DataFrame.head() plt.show() ax1 = tab_DataFrame.plot.line(x="Mass(g)", y="Volume(mL)",style='-o') plt.show() Thanks in advance.
has comment: http://stackoverflow.com/comment/91918762
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91630779
tagged with: pandas
tagged with: python
tagged with: jupyter-notebook
answer count: 0

http://stackoverflow.com/comment/91629548
comment on: http://stackoverflow.com/q/52341182
type: Comment
type: QuestionComment
has text: It is simply inheritance, an "is-a" relationship in the parlance of OOP. If you hover over the containers tag, you'll see that: "A container is a class, a data structure, or an abstract data type whose instances are collections of other objects.". So like a `list` or a `dict`. Here, a `BasicIntContainer` instance isn't a collection of other objects, it *is a specialized kind of `int` object*. I don't want to distract from an interesting question with more terminology nitpicking. Anyway, I would just rephrase as "how to create a type that is closed under inherited operations"
score: 2

http://stackoverflow.com/q/52385299
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91719970
has title: Plot a 3D bar histogram
linked to: http://stackoverflow.com/q/8437788
accepted answer: http://stackoverflow.com/a/52403355
answer count: 3
downvote count: 0
tagged with: histogram
score: 6
has comment: http://stackoverflow.com/comment/91715048
favorite count: 0
has comment: http://stackoverflow.com/comment/91715183
has body: I have some x and y data, with which I would like to generate a 3D histogram, with a color gradient (bwr or whatever). I have written a script which plot the interesting values, in between -2 and 2 for both x and y abscesses: import numpy as np import numpy.random import matplotlib.pyplot as plt # To generate some test data x = np.random.randn(500) y = np.random.randn(500) XY = np.stack((x,y),axis=-1) def selection(XY, limitXY=[[-2,+2],[-2,+2]]): XY_select = [] for elt in XY: if elt[0] &gt; limitXY[0][0] and elt[0] &lt; limitXY[0][1] and elt[1] &gt; limitXY[1][0] and elt[1] &lt; limitXY[1][1]: XY_select.append(elt) return np.array(XY_select) XY_select = selection(XY, limitXY=[[-2,+2],[-2,+2]]) heatmap, xedges, yedges = np.histogram2d(XY_select[:,0], XY_select[:,1], bins = 7, range = [[-2,2],[-2,2]]) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] plt.figure("Histogram") #plt.clf() plt.imshow(heatmap.T, extent=extent, origin='lower') plt.show() And give this correct result: Now, I would like to turn this into a 3D histogram. Unfortunatly I don't success to plot it correctly with bar3d because it takes by default the length of x and y for abscisse. I am quite sure that there is a very easy way to plot this in 3D with imshow. Like an unknow option...
has comment: http://stackoverflow.com/comment/91719861
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/77458761
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52386012
has answer: http://stackoverflow.com/a/52403355
has answer: http://stackoverflow.com/a/52386012
tagged with: matplotlib-3d
type: Question
has comment: http://stackoverflow.com/comment/91720280
has comment: http://stackoverflow.com/comment/91715286

http://stackoverflow.com/a/52343239
type: AcceptedAnswer
type: Answer
has body: Unit tests are written to confirm that the expected output is obtained from a range of inputs for any function or method that carries out some computations and returns a value. If you had a function to calculate the sum of two number: def calc(first,second): return first + second To confirm that the correct result is obtained you would do the following: self.assertEqual(calc(5,5), 10) You expect 10 to be the result from 5 and 5 so if it is something else it will produce an error. I have also noticed this is a question from the Andela Interview questions scheduled for next week. Please review the documentation you were given for more clarity on how to write tests for different cases.
accepted answer of: http://stackoverflow.com/q/52343073
answers question: http://stackoverflow.com/q/52343073
score: 0

http://stackoverflow.com/q/52279296
score: 1
tagged with: python-dateutil
has answer: http://stackoverflow.com/a/52280734
type: Question
answer count: 1
downvote count: 0
has title: Convert csv timestamp from UTC to Hawaiian timezone
tagged with: http://stackoverflow.com/tag/csv
tagged with: datetime
tagged with: python
favorite count: 0
has body: I have a csv of data which is time-stamped to UTC, but needs to have the local time from Hawaii (UTC-10). Ideally I'd add a new column to the csv with the Hawaiian time alongside the UTC time, followed by the data. Here is the csv file format, with the date-time on the first column. The format is a little odd as it has "year-month-date hour/minute/second" as normal but is then followed by "UTC" which I think might be causing me a problem. I've got some simple code to extract the time column, assign it to UTC time (as timestamps are of unknown timezone) and then convert it to UTC-10. import pandas as pd import os from datetime import datetime from dateutil import tz # read the file in csv K = pd.read_csv("kona_python.csv") # time series data selection UTCtime = K.iloc[:,0] # access timezones: utc_timezome = tz.gettz('UTC') hawaii_timezone = tz.gettz('US/Hawaii') # feeding in the csv column data utc = UTCtime # set the datetime object to the UTC timezone utc = utc.replace(tzinfo = utc_timezome) # convert time zone to Hawaii hawaii = utc.astimezone(hawaii_timezone) However it runs with this error, where tzinfo is not expected. Am I using dateutil correctly? Or is there a simpler way to do this? Any help much appreciated! Update - csv sample: UTC timestamp A B C D E F 2018-07-20 22:22:06 UTC 1.27 21.64 1.11 0.37 22.31 0.33 2018-07-20 22:23:25 UTC 1.4 21.82 0.33 0.75 22.59 0.33 2018-07-20 22:24:45 UTC 2.09 20.31 0.93 1.55 21.05 0.4 2018-07-20 22:26:05 UTC 0.8 21.34 0.93 1.36 20.89 0.4 2018-07-20 22:27:24 UTC 0.4 19.93 0.93 1.37 22.58 0.24
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/q/52347737
answer count: 1
has comment: http://stackoverflow.com/comment/91640976
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91641004
tagged with: dictionary
downvote count: 1
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52351115
has comment: http://stackoverflow.com/comment/91641033
score: -1
tagged with: list-comprehension
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/91640946
accepted answer: http://stackoverflow.com/a/52351115
tagged with: postgresql
has comment: http://stackoverflow.com/comment/91640823
has body: I'm trying to push data into the postgres using list comprehension and morgify but i' getting the error. actually, the sort is the dictionary in the following format: sort = {'forecast': [{'name': some_value, 'search_volume': some_int_value, 'competition': some_float_value}]} data_text = ','.join(c.mogrify( "(%(k)s,%(l['name'])s,l['search_volume'],l['competition'])", l) for l in [v for k,v in sort.items()]) Error: Traceback (most recent call last): File "/Users/lonewolf/PycharmProjects/seo_keyword_research_tools-master/keyword_expansion_tool.py", line 137, in get_lsi expand(current_word) File "/Users/lonewolf/PycharmProjects/seo_keyword_research_tools-master/keyword_expansion_tool.py", line 121, in expand sorted_data = write_to_file(current_results, current_word) File "/Users/lonewolf/PycharmProjects/seo_keyword_research_tools-master/keyword_expansion_tool.py", line 107, in write_to_file l) for l in [v for k,v in sort.items()]) File "/Users/lonewolf/PycharmProjects/seo_keyword_research_tools-master/keyword_expansion_tool.py", line 107, in &lt;genexpr&gt; l) for l in [v for k,v in sort.items()]) TypeError: list indices must be integers or slices, not str
has title: getting TypeError: list indices must be integers or slices, not string while inserting data into postgres

http://stackoverflow.com/q/52336308
type: Question
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52336632
has title: What am I doing wrong here? (Python 3) (Beginner)
answer count: 3
has comment: http://stackoverflow.com/comment/91619736
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52336452
downvote count: 4
upvote count: 0
score: -4
has body: I'm new to python and I'm trying to create a program that lets the user send words to the program and it will add them to a list then make the list a string and print it. class joinString(): op_list = [] # this is what i was told to do to initialize a list def init(self): # idk what this is used for to be honest print("Hello") def main(self): string_in = "" # string input print("Enter strings, to stop enter a '0'") while string_in != '0': #while loop checks if string equals '0', stop string_in = input("String: ") #asks user for inputs joinString().op_list.append(string_in) final_string = ''.join(joinString().op_list) # makes final string print("Final Product: " + final_string) # prints final string if __name__ == "__main__": #idk what a name is test = joinString() test.main() # I took AP computer science A (coding in java) and scored pretty well but I # didn't know where to go from there so I'm trying to learn java.
has comment: http://stackoverflow.com/comment/91619739
favorite count: 0
has answer: http://stackoverflow.com/a/52336501

http://stackoverflow.com/comment/91671759
type: Comment
score: 0
has text: self.get_serializer(data={**request.data,**request.FILES}) looks highly suspicious. With Django REST framework, you should only use request.data which includes POST data and files as well.
comment on: http://stackoverflow.com/q/52361130
type: QuestionComment

http://stackoverflow.com/a/52412778
upvote count: 8
has body: I think the solution is quite simple (assuming I understood your issue correctly): # for repeatability: import numpy as np np.random.seed(0) from scipy.stats import poisson, uniform sample_size = 20 maxval = 5 mu = 2.5 cutoff = poisson.cdf(maxval, mu) # generate uniform distribution [0, cutoff): u = uniform.rvs(scale=cutoff, size=sample_size) # convert to Poisson: truncated_poisson = poisson.ppf(u, mu) Then print(truncated_poisson): [2. 3. 3. 2. 2. 3. 2. 4. 5. 2. 4. 2. 3. 4. 0. 1. 0. 4. 3. 4.]
has comment: http://stackoverflow.com/comment/128406917
type: Answer
has comment: http://stackoverflow.com/comment/130418721
score: 8
has comment: http://stackoverflow.com/comment/91886161
has comment: http://stackoverflow.com/comment/128406663
answers question: http://stackoverflow.com/q/52398903
downvote count: 0

http://stackoverflow.com/a/52427847
has body: Featuretools works for relational datasets with or without datetimes and in answer to your question, Featuretools can make features for a single table without a datetime. For the iris dataset, there is only a single table and no immediate features on which to normalize (make a new table from an existing table), so you would use transform primitives to make new features. Make an EntitySet Add a single entity Run Deep Feature Synthesis using whichever transform primitives you want. Here is a complete working example: from sklearn.datasets import load_iris import pandas as pd import featuretools as ft # Load data and put into dataframe iris = load_iris() df = pd.DataFrame(iris.data, columns = iris.feature_names) df['species'] = iris.target df['species'] = df['species'].map({0: 'setosa', 1: 'versicolor', 2: 'virginica'}) # Make an entityset and add the entity es = ft.EntitySet(id = 'iris') es = es.add_dataframe( dataframe_name="data", dataframe=df, index="index", ) # Run deep feature synthesis with transformation primitives feature_matrix, feature_defs = ft.dfs(entityset = es, target_dataframe_name = 'data', trans_primitives = ['add_numeric', 'multiply_numeric']) feature_matrix.head() First five rows of feature matrix: sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) species petal width (cm) + sepal width (cm) petal length (cm) + petal width (cm) petal length (cm) + sepal length (cm) petal length (cm) + sepal width (cm) sepal length (cm) + sepal width (cm) petal width (cm) + sepal length (cm) petal length (cm) * sepal width (cm) sepal length (cm) * sepal width (cm) petal width (cm) * sepal length (cm) petal width (cm) * sepal width (cm) petal length (cm) * sepal length (cm) petal length (cm) * petal width (cm) petal width (cm) + sepal width (cm) * sepal length (cm) + sepal width (cm) petal width (cm) + sepal width (cm) * sepal length (cm) petal length (cm) + petal width (cm) * petal width (cm) petal width (cm) + sepal length (cm) * sepal length (cm)…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/99697548
score: 38
has comment: http://stackoverflow.com/comment/91817607
accepted answer of: http://stackoverflow.com/q/52418152
has comment: http://stackoverflow.com/comment/114627638
type: Answer
answers question: http://stackoverflow.com/q/52418152
has comment: http://stackoverflow.com/comment/91833706
upvote count: 38
has comment: http://stackoverflow.com/comment/116697502
downvote count: 0
has comment: http://stackoverflow.com/comment/132413464

http://stackoverflow.com/q/52279810
has body: Edit: Quick Summary so far: I use the watershed algorithm but I have probably a problem with threshold. It didn't detect the brighter circles. New: Fast radial symmetry transform approach which didn't quite work eiter (Edit 6). I want to detect circles with different sizes. The use case is to detect coins on an image and to extract them solely. -> Get the single coins as single image files. For this I used the Hough Circle Transform of open-cv: (https://docs.opencv.org/2.4/doc/tutorials/imgproc/imgtrans/hough_circle/hough_circle.html) import sys import cv2 as cv import numpy as np def main(argv): ## [load] default_file = "data/newcommon_1euro.jpg" filename = argv[0] if len(argv) &gt; 0 else default_file # Loads an image src = cv.imread(filename, cv.IMREAD_COLOR) # Check if image is loaded fine if src is None: print ('Error opening image!') print ('Usage: hough_circle.py [image_name -- default ' + default_file + '] \n') return -1 ## [load] ## [convert_to_gray] # Convert it to gray gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY) ## [convert_to_gray] ## [reduce_noise] # Reduce the noise to avoid false circle detection gray = cv.medianBlur(gray, 5) ## [reduce_noise] ## [houghcircles] rows = gray.shape[0] circles = cv.HoughCircles(gray, cv.HOUGH_GRADIENT, 1, rows / 8, param1=100, param2=30, minRadius=0, maxRadius=120) ## [houghcircles] ## [draw] if circles is not None: circles = np.uint16(np.around(circles)) for i in circles[0, :]: center = (i[0], i[1]) # circle center cv.circle(src, center, 1, (0, 100, 100), 3) # circle outline radius = i[2] cv.circle(src, center, radius, (255, 0, 255), 3) ## [draw] ## [display] cv.imshow("detected circles", src) cv.waitKey(0) ## [display] return 0 if __name__ == "__main__": main(sys.argv[1:]) I tried all parameters (rows, param1, param2, minRadius, and maxRadius) to optimize the results. This worked very well for one specific image but other images with different sized coins didn't work. Examples: Parameters circles = cv.HoughCircles(gray, …
has comment: http://stackoverflow.com/comment/91514946
has comment: http://stackoverflow.com/comment/91511824
tagged with: watershed
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
upvote count: 4
has comment: http://stackoverflow.com/comment/91516441
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/91548255
has comment: http://stackoverflow.com/comment/91772557
has comment: http://stackoverflow.com/comment/91515399
has comment: http://stackoverflow.com/comment/91782873
type: Question
has comment: http://stackoverflow.com/comment/91771486
tagged with: opencv
has comment: http://stackoverflow.com/comment/91511882
has title: Writing robust (size invariant) circle detection (Watershed)
score: 4
linked to: http://stackoverflow.com/q/9860667
linked to: http://stackoverflow.com/q/45968617
has comment: http://stackoverflow.com/comment/92101958
tagged with: threshold
favorite count: 0

http://stackoverflow.com/comment/91673297
has text: Thanks for your help and the explanation. Its a horrible mistake that i couldnt identifiy.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52363880

http://stackoverflow.com/comment/91706370
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52381020
type: Comment
has text: What language is the file?

http://stackoverflow.com/comment/115608956
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52426031
type: Comment
has text: Is browser the name of your driver, or what? Having hard times trying understand it. Thanks!

http://stackoverflow.com/comment/91761540
score: 0
has text: Im just saying, lead with fixing `Cat`. Don't assume it's some horribly broken 3rd-party client that must be used no matter the cost; it's just as likely the OP wrote `Cat` as well.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52408809

http://stackoverflow.com/comment/91498861
comment on: http://stackoverflow.com/q/52272402
score: 0
type: Comment
type: QuestionComment
has text: @Simmant 27 is the total number of different swaps which can be done for a list of length 3. For any i, j can be (0 to n-1), even i (in which case there will be no swap)

http://stackoverflow.com/a/52273643
has comment: http://stackoverflow.com/comment/135129082
answers question: http://stackoverflow.com/q/52273076
score: 4
downvote count: 1
has body: ok as stated here To search for already installed packages: $ pacman -Qs string1 string2 ... Pacman can search for packages in the database, searching both in packages' names and descriptions: $ pacman -Ss string1 string2 ...
has comment: http://stackoverflow.com/comment/135143898
upvote count: 5
type: Answer

http://stackoverflow.com/comment/91655322
comment on: http://stackoverflow.com/a/52353994
score: 0
type: Comment
has text: that should work! you can just click on the elements that need clicking... with selenium!
type: AnswerComment

http://stackoverflow.com/a/52404214
has comment: http://stackoverflow.com/comment/91752246
has comment: http://stackoverflow.com/comment/91752178
has comment: http://stackoverflow.com/comment/91752399
downvote count: 0
upvote count: 2
has body: Since classes are objects in Python, you could assign the class you want to a variable, at module level. if 'graphics' in sys.modules: Point = graphics.Point Rectangle = graphics.Rectangle else Point = Pt Rectangle = R
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52403954

http://stackoverflow.com/a/52285026
downvote count: 1
answers question: http://stackoverflow.com/q/52272811
has body: When using super to call a superclass method, you would normally need the current class and the current instance as parameters: super(Centaur, self).__init__(...) Now, the problem comes with the way Python handles walking the superclasses. If the __init__ methods don't have matching signatures, then the calls will probably cause problems. From the linked example: class First(object): def __init__(self): print "first prologue" super(First, self).__init__() print "first epilogue" class Second(First): def __init__(self): print "second prologue" super(Second, self).__init__() print "second epilogue" class Third(First): def __init__(self): print "third prologue" super(Third, self).__init__() print "third epilogue" class Fourth(Second, Third): def __init__(self): super(Fourth, self).__init__() print "that's it" Fourth() The output is: $ python2 super.py second prologue third prologue first prologue first epilogue third epilogue second epilogue that's it This shows the order the constructors are called. Also note that the subclass constructors all have compatible signatures because they were written with each other in mind.
type: Answer
upvote count: 0
has comment: http://stackoverflow.com/comment/91518559
score: -1
has comment: http://stackoverflow.com/comment/91518524

http://stackoverflow.com/comment/91685338
type: QuestionComment
comment on: http://stackoverflow.com/q/52366207
score: 0
has text: A proper [mcve] wouldn't hurt. IMHO all the OpenCV code is irrevant to the problem you're facing. | I think the issue is that the desktop script only writes to serial if there is some data waiting in the input buffer (the `if (ser.inWaiting() > 0): ser.write(b'3')`. At the same time, Arduino only writes to serial after it received something. In the beginning, neither writes anything, so both sides are stuck waiting to receive something... which of course never happens.
type: Comment

http://stackoverflow.com/q/52279258
has comment: http://stackoverflow.com/comment/91507412
has body: what are the exact steps i need to execute in order to enable error logging to browser so i don't check the error_log via console any more? I'am using Flask under Apache + mod_wsgi. If i place app.debug = True within my app it does not do anything. from flask import Flask, request, redirect, render_template, url_for application = Flask(__name__) app = application app.config['TESTING'] = True
upvote count: 1
has title: Enable error logging to browser for flask under Apache + mod_wsgi
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
downvote count: 0
tagged with: mod-wsgi
score: 1
has comment: http://stackoverflow.com/comment/91506895
type: Question
has comment: http://stackoverflow.com/comment/91734427

http://stackoverflow.com/comment/91550308
type: QuestionComment
type: Comment
has text: https://stackoverflow.com/search
score: 0
comment on: http://stackoverflow.com/q/52300265

http://stackoverflow.com/comment/91627723
has text: https://stackoverflow.com/questions/50120806/how-to-write-a-csv-file-in-binary-mode seems to suggest that using `csv` in `Python3` is troublesome.
type: Comment
comment on: http://stackoverflow.com/a/52337251
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91771099
score: 0
type: Comment
type: QuestionComment
has text: the json file will be read as text, i don't think it inherently knows to translate the dictionary object to text
comment on: http://stackoverflow.com/q/52413568

http://stackoverflow.com/comment/91910128
score: 0
type: Comment
has text: Awesome, thank you very much for all of your support. I really appreciate it!
type: AnswerComment
comment on: http://stackoverflow.com/a/52371492

http://stackoverflow.com/comment/91639929
type: Comment
has text: That's all is boring ;) sorry, also I need to set values as well.
type: AnswerComment
comment on: http://stackoverflow.com/a/52347199
score: 0

http://stackoverflow.com/comment/91539032
has text: this is generating for only the first row and not for all the rows.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52294889
type: AnswerComment

http://stackoverflow.com/comment/91545377
type: AnswerComment
comment on: http://stackoverflow.com/a/52294098
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/179921/discussion-between---and-vineeth-sai).
score: 0

http://stackoverflow.com/comment/91763391
has text: If you want to output to a file, use the `file=...` keyword argument in the print function.
comment on: http://stackoverflow.com/q/52409774
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91675171
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52365202
score: 1
has text: I had to remove `center = 0` from your heatmap to make it work. I don't see any change in the x or y axis labels if I include `center=0` or not.

http://stackoverflow.com/q/52389503
tagged with: python
score: -1
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 1
type: Question
has body: I have this main class def main(args): if type == train_pipeline_type: strategy = TrainPipelineStrategy() else: strategy = TestPipelineStrategy() for table in fetch_table_information_by_region(region): split_required = DataUtils.load_from_dict(table, "split_required") if split_required: strategy.split(spark=spark, table_name=table_name, data_loc=filtered_data_location, partition_column=partition_column, split_output_dir= split_output_dir) logger.info("Data Split for table : {} completed".format(table_name)) My TrainPipelineStrategy, and TestPipelineStrategy looks like this - class PipelineTypeStrategy(object): def partition_data(self, x): # Something def prepare_split_data(self, y): # Something def write_split_data(self, z): # Something def split(self, p): # Something class TrainPipelineStrategy(PipelineTypeStrategy): """""" class TestPipelineStrategy(PipelineTypeStrategy): def write_split_data(self, y): # Something else My test case - I need to test how many times split is called by mocking split functionality in main method. Here is what i have tried - @patch('module.PipelineTypeStrategy.TrainPipelineStrategy') def test_split_data_main_split_data_call_count(self, fake_train): fake_train_functions = mock.Mock() fake_train_functions.split.return_value = None fake_train.return_value = fake_train_functions test_args = ["", "--x=6"] SplitData.main(args=test_args) assert fake_train_functions.split.call_count == 10 When i try to run my test, it creates the mock but ultimately ends up calling the actual split function. What am i doing wrong ?
tagged with: python-unittest
has answer: http://stackoverflow.com/a/52400045
upvote count: 0
answer count: 1
has title: Python - Unable to mock call for Inherited class
favorite count: 0
has comment: http://stackoverflow.com/comment/91745306

http://stackoverflow.com/comment/91548052
score: 2
has text: Please take the time to prepare sample data and show us what you want the result to look like. This takes effort to answer, we'd at least like to see that you've put in effort to ask. This isn't meant to be an admonition, but friendly advice. I'd like to see you edit this so that someone can answer it. Also, read [mcve] to get a good idea of what I'm talking about.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52300135

http://stackoverflow.com/q/52382590
score: 3
has title: Can not import mongo object in other file
has comment: http://stackoverflow.com/comment/91710168
tagged with: flask-restful
type: Question
tagged with: flask-pymongo
has comment: http://stackoverflow.com/comment/91709818
has body: Using flask-restful, i can not import the object mongo = PyMongo() from the file app/__init__.py into app/common/db.py. My folder structure looks like this: myproject/ run.py app/ __init__.py config.py common/ __init__.py db.py auth/ __init__.py resources.py app/__init__.py contains: from flask import Flask, Blueprint from flask_pymongo import PyMongo from flask_restful import Api from app.config import Config from app.auth.resources import Foo mongo = PyMongo() bp_auth = Blueprint('auth', __name__) api_auth = Api(bp_auth) api_auth.add_resource(Foo, '/foo/&lt;string:name&gt;') def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) mongo.init_app(app) app.register_blueprint(bp_auth) return app app/common/db.py contains: from app import mongo the application itself is run from the root via run.py which contains: from app import create_app app = create_app() if __name__ == '__main__': app.run(debug=True) Problem: Running the application i get an ImportError: from app import mongo ImportError: cannot import name 'mongo' Why this is not working? Thanks for your help! EDIT: Full Traceback: Traceback (most recent call last): File "run.py", line 1, in &lt;module&gt; from app import create_app File "/home/bt/Dropbox/dev/flask/test_api/app/__init__.py", line 13, in &lt;module&gt; from app.auth.resources import SignIn, Users, User, Foo File "/home/bt/Dropbox/dev/flask/test_api/app/auth/resources.py", line 8, in &lt;module&gt; from app.common.resources import AuthResource File "/home/bt/Dropbox/dev/flask/test_api/app/common/resources.py", line 3, in &lt;module&gt; from app.auth.decorators import token_required File "/home/bt/Dropbox/dev/flask/test_api/app/auth/decorators.py", line 6, in &lt;module&gt; from app.common.database import users File "/home/bt/Dropbox/dev/flask/test_api/app/common/database.py", line 1, in &lt;module&gt; from app import mongo ImportError: cannot import name 'mongo'
accepted answer: http://stackoverflow.com/a/52383418
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/52568304
tagged with: flask
favorite count: 0
tagged with: python-3.x
tagged with: python
upvote count: 3
has answer: http://stackoverflow.com/a/52383418
type: AnsweredQuestion

http://stackoverflow.com/q/52399776
type: AnsweredQuestion
has body: I'm using a poorman's method to provide translated content. For this I've added translation fields for each language in the model. These field's are onetoone field's since for each content there can be only one translation per language. How could I limit the choices of these fields in the admin? The point is to provide content (model instances) with lang attribute set to ceartain language i.e. en for translations_en field. Django documentation doesn't state onetoonefield at https://docs.djangoproject.com/en/2.0/ref/contrib/admin/
tagged with: django-models
tagged with: forms
type: Question
has answer: http://stackoverflow.com/a/52400069
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52400069
tagged with: python
tagged with: admin
has title: (Django/Python) How to limit onetoonefield's choices?
tagged with: django

http://stackoverflow.com/a/52423172
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52420315
accepted answer of: http://stackoverflow.com/q/52420315
upvote count: 5
type: Answer
has body: According to the docs you can use def_readwrite: py::class_&lt;Struct_Sample&gt;(m, "Struct_Sample") .def_readwrite("time_ms", &amp;Struct_Sample::time_ms);
downvote count: 0
score: 5

http://stackoverflow.com/comment/91677043
has text: The basic idea is that you get your values in a 0-1 range and then multiply it with the scale factor (255) in this case ... there's ample info on google, try looking for "scale to byte", "scale uint16 to uint8", ... etc. I'm sure there's questions here on SO on that, if not you can always ask yourself ;)
comment on: http://stackoverflow.com/a/52343443
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52400803
downvote count: 0
has comment: http://stackoverflow.com/comment/91748663
has comment: http://stackoverflow.com/comment/91745744
type: Answer
answers question: http://stackoverflow.com/q/52399990
score: 23
has comment: http://stackoverflow.com/comment/91745569
upvote count: 23
accepted answer of: http://stackoverflow.com/q/52399990
has body: You can use the following code: corr = np.corrcoef(np.random.randn(10, 200)) mask = np.zeros_like(corr) mask[np.triu_indices_from(mask)] = True g = sns.heatmap(corr, mask=mask, vmax=.3, square=True) g.set_facecolor('xkcd:salmon') You need to use set_facecolor on the plot object. Change to any colour you want. Resulting in this graph:
type: AcceptedAnswer

http://stackoverflow.com/q/52324820
has answer: http://stackoverflow.com/a/52356579
accepted answer: http://stackoverflow.com/a/52356579
upvote count: 1
answer count: 1
has title: How to control a Thread via input()?
favorite count: 0
tagged with: python-multithreading
tagged with: multithreading
linked to: http://stackoverflow.com/q/576169
linked to: http://stackoverflow.com/q/52048655
tagged with: input
tagged with: python
has body: I want to run a code with process parallel to my main code but also want to access its parameters or start/stop the process via command prompt. my machine is win7 64bit. Something in mind is: from multiprocessing import Process class dllapi(): ... def apiloop(params, args): apiclient = dllapi(**args) while True: apiclient.cycle() params = [....] def mainloop(args): p = Process(target = apiloop, args=(params, args, )) while True: cmd = input() if cmd == 'kill': p.terminate() if cmd == 'stop': pass # no idea if cmd == 'resume': pass # no idea if cmd == 'report': print (params) I wish to make it simple. I did tried to make apiloop as thread yet input() could freeze the program and stopped apiloop working until i pressed enter... To share the parameters from apiloop process, i did try queue and pipe, but, seem to me, queue needs .join to wait until apiloop is done and pipe has buffer limit. (actually i can make apiclient.cycle runs every 1s but i wish to keep apiclient alive) I wish to know if it's worth to dig deeper with multiprocessing (e.g. will try manager as well...) or there are other approaches which is more suitable for my case. Thanks in advance... * UPDATED: 201809170953* Some progress with manager as below: from multiprocessing import Process, Manager class dllapi(): ... class webclientapi(): ... def apiloop(args, cmd, params): apiclient = dllapi(**args) status = True while True: # command from main if cmd == 'stop': status = False elif cmd == 'start': status = True cmd = None # stop or run if status == True: apiclient.cycle() # update parameters params['status'] = status def uploadloop(cmds, params): uploadclient = webclientapi() status = True while True: # command from main if cmd == 'stop': status = False elif cmd == 'start': status = True cmd = None # stop or run if status == True: # upload 'status' from apiclient to somewhere uploadclient.cycle(params['status']) def mainloop(args): manager = Manager() mpcmds = {} mpparams = {} mps = {} mpcmds ['apiloop'…
linked to: http://stackoverflow.com/q/30418886
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91645502
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/91625494
has comment: http://stackoverflow.com/comment/91655514
has comment: http://stackoverflow.com/comment/91646488

http://stackoverflow.com/q/52396612
has answer: http://stackoverflow.com/a/52396782
has answer: http://stackoverflow.com/a/52396662
has title: How do I convert county names to fips codes? (map county names to their fips)
has body: I have a table where one column are the county names and the other columns are various attributes. I want to convert this column of county names to fips codes. I have an intermediary table that shows the fips code for each county. Here is an example of what data i have (initial, and intermediate) and the data i want (final). initial_df = { 'county': ['REAGAN', 'UPTON', 'HARDEMAN', 'UPTON'], 'values': [508, 364, 26, 870] } intermediate_df = { 'county': ['REAGAN', 'HARDEMAN', 'UPTON'], 'fips': [48383, 47069, 48461] } final_df = { 'county': ['REAGAN', 'UPTON', 'HARDEMAN', 'UPTON'], 'fips': [48383, 48461, 47069, 48461], 'values': [508, 364, 26, 870] }
possible better answer: http://stackoverflow.com/a/52396662
score: 0
answer count: 3
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52396686
tagged with: python-3.x
tagged with: mapping
tagged with: python
type: AnsweredQuestion
tagged with: dataframe
has answer: http://stackoverflow.com/a/52396686
type: Question

http://stackoverflow.com/comment/91721871
comment on: http://stackoverflow.com/q/52388348
score: 2
type: Comment
type: QuestionComment
has text: Your `raw` string isn't valid JSON (missing commas between objects). Is this the case with your real data or just a typo in the question?

http://stackoverflow.com/q/52315520
accepted answer: http://stackoverflow.com/a/52335914
has comment: http://stackoverflow.com/comment/91581637
has comment: http://stackoverflow.com/comment/91581413
has comment: http://stackoverflow.com/comment/91618162
score: 0
has comment: http://stackoverflow.com/comment/91581462
tagged with: pyqt
has comment: http://stackoverflow.com/comment/91581257
answer count: 1
tagged with: qtreewidget
has title: Dynamically fill QTreeView so that app doesn't crash
has comment: http://stackoverflow.com/comment/91618238
tagged with: python
has comment: http://stackoverflow.com/comment/91618067
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91581214
tagged with: treeview
has comment: http://stackoverflow.com/comment/91618297
has body: I want to show a tree view of how nodes in an OPC server are organized. I'm using PyQt5 and opcua to achieve this. To try the code, I used Prosys OPC UA Simulation Server, and it works fine. It looks like this: However, when I tried to use the code with real publicly available servers, the app crashes. I believe this is happening because in real servers the amount of existing nodes is huge, and the app has a lot to process then. So I was wondering if there is a way to fill the tree 'on-demand'. Namely, look up the children nodes only when the user clicks on a node, so that only nodes that should be on screen are present as items in the QTreeWidget object. I don't know if this is possible, as currently I'm filling the tree completely in one go, not just when the user demands to see some node's children. This is my current code: import sys from opcua import Client from PyQt5 import QtWidgets, QtGui class Window(QtWidgets.QWidget): def __init__(self, parent=None): super(Window, self).__init__(parent) self.node_tree = QtWidgets.QTreeWidget() layout = QtWidgets.QVBoxLayout() layout.addWidget(self.node_tree) self.setLayout(layout) self.client = Client('opc.tcp://127.0.0.1:53530/UA/Sim') self.client.connect() self.root = self.client.get_root_node() self.fill_tree(self.node_tree, self.root) def fill_tree(self, group, node): item = QtWidgets.QTreeWidgetItem(group, [str(node)]) children = node.get_children() variables = node.get_variables() for child in children: if child in variables: QtWidgets.QTreeWidgetItem(item, [str(child) + ' (variable)']) else: self.fill_tree(item, child) def closeEvent(self,event): self.client.disconnect() sys.exit(0) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) ex = Window() ex.show() sys.exit(app.exec_())
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/91581511
has answer: http://stackoverflow.com/a/52335914

http://stackoverflow.com/q/52284603
has answer: http://stackoverflow.com/a/52284805
favorite count: 0
type: Question
has body: How can I do a very explicit sort on a list in Python? What I mean is, items are supposed to be sorted a very specific way and not just alphabetically or numerically. The input I would be receiving looks something list this: h43948fh4349f84 ./.file.html dsfj940j90f94jf ./abcd.ppt f9j3049fj349f0j ./abcd_FF_000000001.jpg f0f9049jf043930 ./abcd_FF_000000002.jpg j909jdsa094jf49 ./abcd_FF_000000003.jpg jf4398fj9348fjj ./abcd_FFinit.jpg 9834jf9483fj43f ./abcd_MM_000000001.jpg fj09jw93fj930fj ./abcd_MM_000000002.jpg fjdsjfd89s8hs9h ./abcd_MM_000000003.jpg vyr89r8y898r839 ./abcd_MMinit.jpg The list should be sorted: html file first ppt file second FFinit file third MMinit file fourth The rest of the numbered files in the order of FF/MM Example output for this would look like: h43948fh4349f84 ./.file.html dsfj940j90f94jf ./abcd.ppt jf4398fj9348fjj ./abcd_FFinit.jpg vyr89r8y898r839 ./abcd_MMinit.jpg f9j3049fj349f0j ./abcd_FF_000000001.jpg 9834jf9483fj43f ./abcd_MM_000000001.jpg f0f9049jf043930 ./abcd_FF_000000002.jpg fj09jw93fj930fj ./abcd_MM_000000002.jpg j909jdsa094jf49 ./abcd_FF_000000003.jpg fjdsjfd89s8hs9h ./abcd_MM_000000003.jpg
has answer: http://stackoverflow.com/a/52284855
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/91517536
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52284763
accepted answer: http://stackoverflow.com/a/52284763
possible better answer: http://stackoverflow.com/a/52284659
has comment: http://stackoverflow.com/comment/91517507
has answer: http://stackoverflow.com/a/52284659
answer count: 4
has title: How to sort a list in a very specific way in Python?
type: AnsweredQuestion

http://stackoverflow.com/q/52291509
has comment: http://stackoverflow.com/comment/91532373
has comment: http://stackoverflow.com/comment/91532614
answer count: 1
has comment: http://stackoverflow.com/comment/91532650
has title: Typeerror occours when I tried to get a graphic from CSV file in python
has comment: http://stackoverflow.com/comment/91531046
linked to: http://stackoverflow.com/q/52295418
has comment: http://stackoverflow.com/comment/91537087
has comment: http://stackoverflow.com/comment/91535232
tagged with: python
has comment: http://stackoverflow.com/comment/91531249
type: AnsweredQuestion
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52293478
has comment: http://stackoverflow.com/comment/91538967
has comment: http://stackoverflow.com/comment/91531767
type: Question
has comment: http://stackoverflow.com/comment/91532424
tagged with: graphics
tagged with: matplotlib
linked to: http://stackoverflow.com/q/52223419
has comment: http://stackoverflow.com/comment/91531605
has body: import os from matplotlib import pyplot as pyplot from collections import defaultdict import csv import numpy as np path = r'C:\Users\AK6PRAKT\Desktop\6daten' dirs = os.listdir(path) s = [] x = [] y = [] names = [] fig = pyplot.figure() for i in dirs: if os.path.splitext(i)[1] == ".csv": f = open(path+"/"+i) iter_f = iter(f); str = "" for line in iter_f: str = str + line s.append(str) with open(path+"/"+i,'r') as r: lines=r.readlines() with open(path+"/"+i,'w') as w: for row in lines: if 'Date' not in row: w.write(row) columns = defaultdict(list) with open(path+"/"+i) as f: reader = csv.reader(f) for row in reader: for (i,v) in enumerate(row): columns[i].append(v) list_temp1 = columns[0] list_temp1 = np.array(list_temp1) list_temp2 = columns[2] list_temp2 = np.array(list_temp2) print(list_temp1,list_temp2) y.append(float(list_temp2)) names.append(list_temp1) x = range(len(names)) pyplot.ylim((0, 40)) my_y_ticks = np.arange(0, 40, 10) pyplot.plot(x,y, linewidth=2) pyplot.xticks(x,names,rotation = 90) fig = pyplot.figure(figsize=(10,10)) pyplot.show() This code works very good if there are only several csv files. BUT i want to apply this code in practice, i need to analyse more than 200000 csv file and make a graphic so that I can see the fluctuation of these datas obviously, but when i want to import these magnificent files, the following Error occours: File "C:/Users/AK6PRAKT/headerremover.py", line 44, in &lt;module&gt; y.append(float(list_temp2)) TypeError: only size-1 arrays can be converted to Python scalars I really have no idea about solving that, if anyone can help me, thanks a lot!!!!!!
has comment: http://stackoverflow.com/comment/91540688
has answer: http://stackoverflow.com/a/52293478
has comment: http://stackoverflow.com/comment/91532293
has comment: http://stackoverflow.com/comment/91535548
score: 0

http://stackoverflow.com/a/52415653
has body: Don't. It seems like using dict comprehensions for this should be a good idea, but it's actually a horrible trap. Use collections.Counter: import counts seen_dict = collections.Counter(ar) or if you don't want to do that, then stick with the loop. The problem with trying to use a dict comprehension is that a dict comprehension has no good way to maintain state or interleave the computation of the values of each key. Each value must be computed in a single expression. In contrast, the best way to solve your counting problem is to make a single pass over ar and update each element's count as you go. The restrictions of a comprehension lead to horribly inefficient attempts like seen_dict = {val: ar.count(val) for val in ar} which makes a number of passes over ar equal to the length of ar, or the slightly more efficient but still horribly suboptimal seen_dict = {val: ar.count(val) for val in set(ar)} which only needs to make len(set(ar)) passes, or for people a bit more familiar with the standard library, from itertools import groupby seen_dict = {val: sum(1 for _ in group) for val, group in groupby(sorted(ar))} which at least isn't quadratic time, but is still O(nlogn) for a length-n ar. If we run a timing of these four snippets with input list(range(10000)): from collections import Counter from itertools import groupby from timeit import timeit ar = list(range(10000)) print(timeit('Counter(ar)', number=1, globals=globals())) print(timeit('{val: ar.count(val) for val in ar}', number=1, globals=globals())) print(timeit('{val: ar.count(val) for val in set(ar)}', number=1, globals=globals())) print(timeit('{val: sum(1 for _ in group) for val, group in groupby(sorted(ar))}', number=1, globals=globals())) We get the following output: 0.0005530156195163727 1.0503493696451187 1.0463058911263943 0.00422721728682518 Counter finishes in half a millisecond, while the count snippets both take over a second. (The set version seems to have a lower runtime due to some sort of first-r…
has comment: http://stackoverflow.com/comment/91774998
has comment: http://stackoverflow.com/comment/91775018
answers question: http://stackoverflow.com/q/52415446
accepted answer of: http://stackoverflow.com/q/52415446
type: AcceptedAnswer
upvote count: 7
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91774877
has comment: http://stackoverflow.com/comment/91775160
score: 6

http://stackoverflow.com/comment/93209742
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52420515
has text: Does that work for you? https://stackoverflow.com/questions/36362624/how-to-plot-multiple-histograms-on-same-plot-with-seaborn

plotly
tags question: http://stackoverflow.com/q/52296964
tags question: http://stackoverflow.com/q/52304003
tags question: http://stackoverflow.com/q/52384429
type: Tag
tags question: http://stackoverflow.com/q/52409641
tags question: http://stackoverflow.com/q/52428311
tags question: http://stackoverflow.com/q/52380997
tags question: http://stackoverflow.com/q/52412901
tag name: plotly
tags question: http://stackoverflow.com/q/52378791
tags question: http://stackoverflow.com/q/52339903
tags question: http://stackoverflow.com/q/52418358
tags question: http://stackoverflow.com/q/52274271
tags question: http://stackoverflow.com/q/52391451
tags question: http://stackoverflow.com/q/52338272

http://stackoverflow.com/comment/91634227
comment on: http://stackoverflow.com/q/52344137
score: 2
type: QuestionComment
type: Comment
has text: Your `while` loop containing a `return` is in fact an `if`: it will never be executed more than once. So you do exactly the same, you just inverted the condition.

file
tags question: http://stackoverflow.com/q/52304057
type: Tag
tags question: http://stackoverflow.com/q/52378386
tags question: http://stackoverflow.com/q/52310450
tags question: http://stackoverflow.com/q/52335920
tags question: http://stackoverflow.com/q/52369398
tags question: http://stackoverflow.com/q/52388728
tags question: http://stackoverflow.com/q/52337479
tags question: http://stackoverflow.com/q/52346653
tags question: http://stackoverflow.com/q/52345587
tag name: file
tags question: http://stackoverflow.com/q/52428537
tags question: http://stackoverflow.com/q/52407669
tags question: http://stackoverflow.com/q/52384645
tags question: http://stackoverflow.com/q/52349921
tags question: http://stackoverflow.com/q/52301211
tags question: http://stackoverflow.com/q/52324838
tags question: http://stackoverflow.com/q/52312736
tags question: http://stackoverflow.com/q/52330853
tags question: http://stackoverflow.com/q/52319398
tags question: http://stackoverflow.com/q/52404849
tags question: http://stackoverflow.com/q/52410921
tags question: http://stackoverflow.com/q/52406104
tags question: http://stackoverflow.com/q/52347927
tags question: http://stackoverflow.com/q/52416604

http://stackoverflow.com/comment/91588303
score: 1
comment on: http://stackoverflow.com/a/52319783
type: AnswerComment
has text: @winteralfs I do not understand what causes your problem, as you should know unfortunately without a [mcve] I will not be able to help you.
type: Comment

http://stackoverflow.com/q/52283924
tagged with: image-recognition
has comment: http://stackoverflow.com/comment/91516818
tagged with: arrays
has comment: http://stackoverflow.com/comment/91516746
has comment: http://stackoverflow.com/comment/91517223
has answer: http://stackoverflow.com/a/52284569
accepted answer: http://stackoverflow.com/a/52284569
has comment: http://stackoverflow.com/comment/91517027
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91516165
favorite count: 0
has comment: http://stackoverflow.com/comment/91516801
has comment: http://stackoverflow.com/comment/91517286
has body: Wanna know if two numpy arrays are close to each other... like if we had 2 (2-d) numpy arrays of 2 images I wanna know if they close to each other (are they similar or not) not equal also, there is anyway to know if the probability of similarity are close to 1? like any classifier would do but I just wanted it without machine learning. let's assume we have 2 pixel: a = [255, 250, 3] b = [255, 255, 3] err = [(bb-aa)/max(aa,bb) for aa, bb in a, b] then the probability p = 1 - np.mean(np.array(err))
has title: get probability how two numpy arrays are close to each other python
tagged with: python
tagged with: computer-vision
tagged with: opencv
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/91516362
score: -1
has comment: http://stackoverflow.com/comment/91516690
has comment: http://stackoverflow.com/comment/91516495
type: Question
tagged with: numpy

http://stackoverflow.com/comment/91643828
type: Comment
comment on: http://stackoverflow.com/a/52349230
score: 0
type: AnswerComment
has text: Does the function depend on the values in the loop or the index of the values?

http://stackoverflow.com/comment/91662424
type: AnswerComment
score: 0
type: Comment
has text: @DYZ: I know, but I just wanted to help the OP by telling him/her problems in the code. There are much less verbose solutions but read what the OP stated **I am struggling to understand why my code is not working.**.
comment on: http://stackoverflow.com/a/52358882

http://stackoverflow.com/a/52430119
answers question: http://stackoverflow.com/q/52430001
type: Answer
score: 1
upvote count: 1
has body: What you could do is pass the condition in as an argument as shown below def result(cond): if cond: print('Correct') else: print('Wrong') what this does, it keeps your function standalone i.e, you don't need to care about the condition you pass, just what the condition evaluates to, probably letting you later reuse the function. Sample Usage would include, just invoking the function with the condition; something like - result(answer == 'answer placehoder')
downvote count: 0

http://stackoverflow.com/comment/91718013
type: QuestionComment
comment on: http://stackoverflow.com/q/52386793
score: 1
has text: Can you clarify that values in hobbies column are list or string?
type: Comment

http://stackoverflow.com/q/52288745
has body: Pylint complains about cyclic import with R0401 error code for a specific file of the NLTK package, e.g. nltk/nltk/ccg/lexicon.py:1: [R0401(cyclic-import), ] Cyclic import (nltk -&gt; nltk.internals) nltk/nltk/ccg/lexicon.py:1: [R0401(cyclic-import), ] Cyclic import (nltk.corpus -&gt; nltk.tokenize -&gt; nltk.tokenize.punkt -&gt; nltk.probability) nltk/nltk/ccg/lexicon.py:1: [R0401(cyclic-import), ] Cyclic import (nltk.corpus -&gt; nltk.tokenize -&gt; nltk.tokenize.texttiling) nltk/nltk/ccg/lexicon.py:1: [R0401(cyclic-import), ] Cyclic import (nltk.draw.tree -&gt; nltk.tree) nltk/nltk/ccg/lexicon.py:1: [R0401(cyclic-import), ] Cyclic import (nltk.tree -&gt; nltk.treeprettyprinter) nltk/nltk/ccg/lexicon.py:1: [R0401(cyclic-import), ] Cyclic import (nltk.grammar -&gt; nltk.parse.pchart) nltk/nltk/ccg/lexicon.py:1: [R0401(cyclic-import), ] Cyclic import (nltk.stem -&gt; nltk.stem.porter) nltk/nltk/ccg/lexicon.py:1: [R0401(cyclic-import), ] Cyclic import (nltk.classify.maxent -&gt; nltk.classify.tadm) The full list is on https://github.com/nltk/nltk/issues/2113 But looking at the imports: from __future__ import unicode_literals from import re from collections import defaultdict from nltk.ccg.api import PrimitiveCategory, Direction, CCGVar, FunctionalCategory from nltk.compat import python_2_unicode_compatible from nltk.internals import deprecated from nltk.sem.logic import * But look at the nltk.internals https://github.com/nltk/nltk/blob/develop/nltk/internals.py , there isn't any cyclic imports that points to nltk.ccg.lexicon: from __future__ import print_function import subprocess import os import fnmatch import re import warnings import textwrap import types import sys import stat import locale # Use the c version of ElementTree, which is faster, if possible: try: from xml.etree import cElementTree as ElementTree except ImportError: from xml.etree import ElementTree from six import string_types from nltk import __file__ from nltk import compat What does the R0401(cy…
tagged with: nltk
downvote count: 0
score: 13
has title: Cyclic Imports to fix R0401 from pylint
type: AnsweredQuestion
favorite count: 0
tagged with: cyclic-dependency
has answer: http://stackoverflow.com/a/52362110
type: Question
tagged with: pylint
tagged with: python
answer count: 1
upvote count: 13
accepted answer: http://stackoverflow.com/a/52362110

http://stackoverflow.com/q/52376617
accepted answer: http://stackoverflow.com/a/52427679
has comment: http://stackoverflow.com/comment/91736077
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52427679
has title: Conditional test not working using pythonanywhere with python and flask
linked to: http://stackoverflow.com/q/1070398
type: Question
has comment: http://stackoverflow.com/comment/91736115
has body: My simple conditional test is not working. Here is the flask_app.py code: testing_conditional_args = [] testing_conditional_args.append("a") testing_conditional_args.append("b") testing_conditional_args.append("c") @app.route("/testing_conditional/", methods=['POST']) def testing_conditional(): if request.method == "POST": return render_template("testing_conditional.html", testing_conditional_args=testing_conditional_args) return redirect(url_for('testing_conditional')) Here is the html template (testing_conditional.html): var0 = {{testing_conditional_args[0]}} &lt;br&gt; var1 = {{testing_conditional_args[1]}} &lt;br&gt; var2 = {{testing_conditional_args[2]}} &lt;br&gt; {% if var1 == "b" %} args var1 and "b" are equal&lt;br&gt; {% endif %} {% if var1 != "b" %} args var1 and "b" are not equal&lt;br&gt; {% endif %} {% if "a" != "b" %} args "a" and "b" are not equal&lt;br&gt; {% endif %} {% if "a" == "a" %} args "a" and "a" are equal&lt;br&gt; {% endif %} The output in the web browser shows that var1 is "b", but the conditional test does not work. var0 = a var1 = b var2 = c args var1 and "b" are not equal args "a" and "b" are not equal args "a" and "a" are equal It says that var1 and "b" are not equal when it seems they should be. Why is var1 not recognized as "b"?
score: -1
tagged with: flask
has comment: http://stackoverflow.com/comment/91697971
answer count: 1
downvote count: 1
tagged with: pythonanywhere
favorite count: 0
upvote count: 0

http://stackoverflow.com/q/52404467
type: Question
has answer: http://stackoverflow.com/a/52405013
tagged with: matplotlib
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52405013
has title: Changing the interval argument in animation.FuncAnimation in the matplotlib library has unexpected effects
tagged with: python-3.x
tagged with: animation
tagged with: python
type: AnsweredQuestion
has body: I am having a little trouble working with the FuncAnimation function. The most pressing issue is that changing the interval argument from 1 to any value less than one seems to have no effect on the animation at all, meaning that there is a limit to how fast I can run my animation. For example: ani = animation.FuncAnimation(fig, animate, np.arange(1, len(y[0])), interval=1, blit=True, init_func=init) runs the same as ani = animation.FuncAnimation(fig, animate, np.arange(1, len(y[0])), interval=0.01, blit=True, init_func=init) Does anyone have any ideas for a workaround using this function? Another, possibly related problem, is that the function is not acting as I expect it to anyway. Since the docs say that interval gives "Delay between frames in milliseconds. Defaults to 200.", why does doubling the interval from 1 to 2 have very little effect on the speed it runs at? Surely this should cause the animation to take twice as long to play? Thanks for any help. Edit: In order to reproduce this, you could use the example code found here: https://matplotlib.org/examples/animation/double_pendulum_animated.html Set dt = 0.02 and play around with the interval to see the problem. The only cause I can think of is that the function does not accept values less than 1, though this does not explain the second issue I have.

http://stackoverflow.com/q/52273857
tagged with: time-series
has comment: http://stackoverflow.com/comment/91495281
answer count: 2
tagged with: pandas
downvote count: 0
possible better answer: http://stackoverflow.com/a/52273953
accepted answer: http://stackoverflow.com/a/52274306
has body: I have a dataframe that uses binary indicators to reflect whether a customer is live during a particular month. If the customer is live, there is a 1, if not there is a 0. The dataframe looks like the below: Customer A B C D E F G H I J 11/30/2015 1 0 1 0 0 1 1 0 0 0 12/31/2015 0 1 0 1 0 1 1 0 0 1 1/31/2016 0 0 0 0 0 1 1 0 0 1 2/29/2016 1 1 1 1 1 1 0 1 1 1 3/31/2016 1 1 0 1 1 0 1 1 0 1 4/30/2016 0 1 1 1 0 1 1 1 0 1 5/31/2016 1 1 1 1 1 1 0 1 0 1 When a customer first becomes live, they get a 1 for the particular month. Therefore when a particular customer has their first 1, this is the month in which they are "new". I want to add a column at the end of the dataframe which counts the number of "new" customers. I think the most efficient method of doing this would be to sum the values from row 0 to row i, and count the number of times the sum equals 1. When this sum is greater than 1, then the customer will have been live for 2 months and is not a new customer in the given month. I have calculated this in excel using this method but I am not clear on how to go about this in Python. The resulting dataframe would look like this: Customer A B C D E F G H I J New_Customers 11/30/2015 1 0 1 0 0 1 1 0 0 0 4 12/31/2015 0 1 0 1 0 1 1 0 0 1 3 1/31/2016 0 0 0 0 0 1 1 0 0 1 0 2/29/2016 1 1 1 1 1 1 0 1 1 1 3 3/31/2016 1 1 0 1 1 0 1 1 0 1 0 4/30/2016 0 1 1 1 0 1 1 1 0 1 0 5/31/2016 1 1 1 1 1 1 0 1 0 1 0
favorite count: 0
has answer: http://stackoverflow.com/a/52273953
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52274306
has title: Counting number of first time binary indicators in a time series
type: Question

http://stackoverflow.com/q/52356838
has answer: http://stackoverflow.com/a/52356871
upvote count: 2
answer count: 1
favorite count: 0
has body: I'm having an issue crawling pages on Amazon. I've tried using: Executing JS Script Action Chains Explicit Waits Nothing seems to work. Everything throws one exception or error or another. Base Script ff = create_webdriver_instance() ff.get('https://www.amazon.ca/gp/goldbox/ref=gbps_ftr_s-3_4bc8_dct_10-?gb_f_c2xvdC0z=sortOrder:BY_SCORE,discountRanges:10-25%252C25-50%252C50-70%252C70-&amp;pf_rd_p=f5836aee-0969-4c39-9720-4f0cacf64bc8&amp;pf_rd_s=slot-3&amp;pf_rd_t=701&amp;pf_rd_i=gb_main&amp;pf_rd_m=A3DWYIK6Y9EEQB&amp;pf_rd_r=CQ7KBNXT36G95190QJB1&amp;ie=UTF8') next_button = ff.find_element_by_xpath('(//li/a[contains(text(), "Next")])[1]') Attempt #1: Executing JS Script ff.execute_script('arguments[0].scrollIntoView()', next_button) Error Element could not be scrolled into view Attempt #2: Action Chain Script actions = ActionChains(ff) actions.move_to_element(next_button) actions.click(next_button) actions.perform() Error TypeError: rect is undefined Attempt #3: Explicit Wait next_button = WebDriverWait(ff, 60).until( EC.visibility_of_element_located((By.XPATH, '(//li/a[contains(text(), "Next")])[1]')) ) I've also tried using element_to_be_clickable. Both of these end up timing out.
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/52356871
tagged with: screen-scraping
tagged with: selenium
tagged with: web-scraping
has title: Issue Crawling Amazon, Element Cannot Be Scrolled into View
tagged with: web-crawler
type: Question

http://stackoverflow.com/q/52359612
accepted answer: http://stackoverflow.com/a/52359777
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52359653
has answer: http://stackoverflow.com/a/52359653
has answer: http://stackoverflow.com/a/52359777
has title: Numpy: swap positions of 2D array based on a separate vector
type: Question
tagged with: numpy
answer count: 2
has body: Let's say I have a 3x3 numpy array: [[0, 1, 2], [2, 0, 1], [1, 2, 0]] And an additional vector: [2, 1, 1] For each row in the matrix, I want to swap the number at the 0th index with the number at the corresponding index from the vector. In this example, after the swap, the final output would be: [[2, 1, 0], # the 0th and 2nd positions have been swapped [0, 2, 1], # the 0th and 1st positions have been swapped [2, 1, 0]] # the 0th and 1st positions have been swapped How can you do this?
tagged with: matrix
upvote count: 1
tagged with: arrays
favorite count: 0
has comment: http://stackoverflow.com/comment/91663781
tagged with: python
downvote count: 0
score: 1

http://stackoverflow.com/comment/91583479
comment on: http://stackoverflow.com/a/52316877
type: Comment
has text: What keeps you from using conda to install your package?
score: 0
type: AnswerComment

http://stackoverflow.com/q/52387376
possible better answer: http://stackoverflow.com/a/52390013
upvote count: 0
has comment: http://stackoverflow.com/comment/91720541
has comment: http://stackoverflow.com/comment/91720741
has answer: http://stackoverflow.com/a/52387425
favorite count: 0
tagged with: python-3.x
has body: I have a simple gui(tkinter) program that writes data to a file. Uses shelve. How to run shelve.close () when I want to disable the program?
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91720323
tagged with: tkinter
downvote count: 2
accepted answer: http://stackoverflow.com/a/52387425
tagged with: shelve
has title: Python, Tkinter - How to run 'shelve.close ()' when exiting the gui program?
type: Question
has comment: http://stackoverflow.com/comment/91719261
score: -2
has answer: http://stackoverflow.com/a/52390013
answer count: 2

http://stackoverflow.com/comment/91620917
type: Comment
has text: Did you use in python Notebook or something else ?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52327211

http://stackoverflow.com/a/52330112
has comment: http://stackoverflow.com/comment/91606829
has body: The problem is that if (guess == secret_word): will always be False since guess is a single letter and it gets replaced by a new input every iteration guess = input().upper(). So your loop will never quit in case of correct guess, it will quit only when you finish the lives.
has comment: http://stackoverflow.com/comment/91607083
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91607188
answers question: http://stackoverflow.com/q/52329835
has comment: http://stackoverflow.com/comment/91607233
score: 0
type: Answer

http://stackoverflow.com/q/52349359
tagged with: matplotlib
has title: Latex not working with matplotlib since it can't find kpsewhich
upvote count: 1
has comment: http://stackoverflow.com/comment/91644100
type: Question
has answer: http://stackoverflow.com/a/64990637
has comment: http://stackoverflow.com/comment/91644427
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91646728
score: 1
has body: Whenever I try to use latex with matplotlib I get the error: FileNotFoundError: [Errno 2] No such file or directory: 'kpsewhich': 'kpsewhich' A minimal working example is import numpy as np import matplotlib.pyplot as plt from matplotlib import rc rc("text", usetex = True) plt.plot(1,2) plt.show() I am currently running python 3.6.4 and miktex 2.9.6600. Any help is much appreciated!
favorite count: 0
tagged with: latex
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91644380
has comment: http://stackoverflow.com/comment/91644225
has comment: http://stackoverflow.com/comment/91644169

http://stackoverflow.com/q/52401172
has body: In this code: import pandas as pd myj='{"columns":["tablename","alias_tablename","real_tablename","dbname","finalcost","columns","pri_col"],"index":[0,1],"data":[["b","b","vip_banners","openx","",["id","name","adlink","wap_link","ipad_link","iphone_link","android_link","pictitle","target","starttime","endtime","weight_limit","weight","introduct","isbutton","sex","tag","gomethod","showtype","version","warehouse","areaid","textpic","smallpicture","group","service_provider","channels","chstarttime","chendtime","tzstarttime","tzendtime","status","editetime","shownum","wap_version","ipad_version","iphone_version","android_version","showtime","template_id","app_name","acid","ab_test","ratio","ab_tset_type","acid_type","key_name","phone_models","androidpad_version","is_delete","ugep_group","author","content","rule_id","application_id","is_default","district","racing_id","public_field","editor","usp_expression","usp_group","usp_php_expression","is_pic_category","is_custom_finance","midwhitelist","is_freeshipping","resource_id","usp_property","always_display","pushtime","is_pmc","version_type","is_plan","loop_pic_frame_id","plan_personal_id","personal_id","is_img_auto","banner_type","ext_content"],"id"],["a","a","vip_adzoneassoc","openx","",["id","zone_id","ad_id","weight"],"id"]]}' df=pd.read_json(myj, orient='split') bl=['is_delete,status,author', 'endtime', 'banner_type', 'id', 'starttime', 'status,endtime','weight'] al= ['zone_id,ad_id', 'zone_id,ad_id,id', 'ad_id', 'id', 'zone_id'] # #bl=['add_time', 'allot_time', 'create_time', 'end_pay_time', 'start_pay_time', 'order_status,update_time', 'order_type,order_status,add_time', 'order_type,order_status,end_pay_time', 'wms_flag,order_status,is_first,order_date', 'last_update_time', 'order_code', 'order_date', 'order_sn', 'parent_sn', 'id', 'user_id', 'wms_flag,order_date'] #al=['area_id', 'last_update_time', 'mobile', 'parent_sn', 'id', 'transport_number', 'parent_sn'] def get_index(row): print(row) if row.tablename=='b': r…
score: 1
type: Question
has comment: http://stackoverflow.com/comment/91780063
has title: ValueError: could not broadcast input array from shape (5) into shape (7)
has comment: http://stackoverflow.com/comment/91776936
upvote count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/91777195
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91752767
has comment: http://stackoverflow.com/comment/91776918
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52421131

http://stackoverflow.com/a/52383401
upvote count: 7
downvote count: 1
answers question: http://stackoverflow.com/q/52383287
score: 6
type: Answer
has body: You can create a list of dataframes and keep appending new dataframes for each year's data into that list. Once you are done scraping the data you can concat them into one dataframe like this: dfs = [] for year in recent_years : PBC = Event_Scraper("italy", year, outputt_path) df = PBC._read_html_() dfs.append(df) final_df = pd.concat(dfs) Appending or doing concat on the dataframe is an expensive operation as Pandas needs to allocate memory for the new dataframe and copy all the data over, so doing it multiple times in a loop will be expensive. Doing it this way saves that overhead as you will only do it once.

http://stackoverflow.com/q/52295425
tagged with: django
tagged with: python
has title: Django; adapt same validator with multiple fileds
accepted answer: http://stackoverflow.com/a/52296432
answer count: 1
score: 0
tagged with: django-models
has body: Objective : I want to override first_name and last_name from AbstractUser model. What I want exactly : I want to create validator that tells if either first_name or last_name is filled. So I want to adapt the same validator with the two parameters. How can I create?
has answer: http://stackoverflow.com/a/52296432
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/91506221
score: 0
comment on: http://stackoverflow.com/q/52279068
has text: @mpm how does a node solution help when OP using python?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52290746
has comment: http://stackoverflow.com/comment/91567082
score: 0
has comment: http://stackoverflow.com/comment/91559970
type: Answer
has comment: http://stackoverflow.com/comment/91567606
answers question: http://stackoverflow.com/q/52289385
has body: You don't want to access serializer1.data once it's been validated. It should be done through serializer1.validated_data instead and you'll find your file there.

python-itertools
tags question: http://stackoverflow.com/q/52310383
tags question: http://stackoverflow.com/q/52415167
tags question: http://stackoverflow.com/q/52397940
tag name: python-itertools
type: Tag
tags question: http://stackoverflow.com/q/52411230
tags question: http://stackoverflow.com/q/52373652
tags question: http://stackoverflow.com/q/52354664

http://stackoverflow.com/a/52307493
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52307347
answers question: http://stackoverflow.com/q/52307347
has comment: http://stackoverflow.com/comment/91562872
has body: Unlike bubble sort, Insertion sort does not merely swap numbers (conceptually). First, it stores the value at current index j in a variable key. Then it starts at just previous index i of current index (i = j - 1), and traverses backwards (i = i - 1) towards the beginning. For each index, it compares value with key (while i &gt;= 0 and A[i] &gt; key). If value at i is more than key, it shifts the value one index forward (A[i + 1] = A[i]), until it finds a value equal or lower than key. When such value is found, key should come just after that in sorted array, so it places key at next index i+1 (A[i + 1] = key). It repeats the same process for all elements and result is sorted array. This will help more https://visualgo.net/bn/sorting?slide=8.
score: 0

http://stackoverflow.com/q/52294562
has title: umap-project can't find vendor libraries
tagged with: django
tagged with: python
tagged with: leaflet
upvote count: 1
has body: I am trying to extend umap (https://github.com/umap-project/umap), I used git clone to get the latest version of umap code and imported it into eclipse. I have PyDev Django environment set up. According to the installation guide I created configuration file (/etc/umap/umap.conf), created database, run manage.py migrate and collectstatic. Everything went ok. Home page is displayed also ok, but when I try to do anything (login, create map) I get stack of errors. Please find below log from eclipse console. I am looking at github repo and also cannot find this folder /static/umap/vendors. I just started to work with umap so maybe I am missing something. Loaded local config from /etc/umap/umap.conf /home/svranic/.local/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: &lt;http://initd.org/psycopg/docs/install.html#binary-install-from-pypi&gt;. """) Loaded local config from /etc/umap/umap.conf /home/svranic/.local/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: &lt;http://initd.org/psycopg/docs/install.html#binary-install-from-pypi&gt;. """) Performing system checks... System check identified no issues (0 silenced). September 12, 2018 - 11:32:32 Django version 2.1.1, using settings 'umap.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [12/Sep/2018 11:32:38] "GET /en/ HTTP/1.1" 200 10859 [12/Sep/2018 11:32:38] "GET /static/umap/vendors/leaflet/leaflet.css HTTP/1.1" 404 1834 [12/Sep/2018 11:32:38] "GET /static/umap/vendors/contextmenu/leaflet.contextmenu.css HTTP/1.1" 404 1882 [12/Sep/2018 11:32:38] "GET /static/umap/vendors/markercluster/MarkerCluster.css HTTP/…
downvote count: 1
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52295043
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/52338372
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91625326
accepted answer of: http://stackoverflow.com/q/52336916
has comment: http://stackoverflow.com/comment/91626098
has comment: http://stackoverflow.com/comment/91626493
upvote count: 2
has comment: http://stackoverflow.com/comment/91626101
has comment: http://stackoverflow.com/comment/91627613
type: Answer
has comment: http://stackoverflow.com/comment/91626079
has comment: http://stackoverflow.com/comment/91625397
has comment: http://stackoverflow.com/comment/91625237
score: 2
has body: Consider re-factoring your code for several issues: try/except is usually used for handling runtime exceptions and errors, not application logic. Use the if/else for these situations. Remove the unneeded for loop as you are not deleting row by row since no unique identifier is being passed into DELETE statements. In actuality, you are running the deletion process across whole table if the logic passes that current row not filtered to that one row. Use pure SQL with one DELETE statement and avoid the Python handling of time elements which as you see maintains conversion issues from the database. MS Access SQL does have date functions such as Date() (current date) and DatePart() for month/day extractions. Additionally, MS Access can run complex subquery logic in DELETE. SQL Using IN subquery for both date conditions. NOTE: ID should be replaced with unique identifier of table. Check SELECT version of query prior to DELETE version. DELETE FROM RELEASES r WHERE r.ID IN (SELECT sub.ID FROM RELEASES sub WHERE sub.RELEASED_BY = ? AND ( ( DatePart('m', sub.RELEASED_DATE) = DatePart('m', Date()) - 1 AND DatePart('yyyy', sub.RELEASED_DATE) = DatePart('yyyy', Date()) AND DatePart('d', sub.RELEASED_DATE) = 1 ) OR ( DatePart('m', sub.RELEASED_DATE) = DatePart('m', Date()) AND DatePart('yyyy', sub.RELEASED_DATE) = DatePart('yyyy', Date()) AND DatePart('d', sub.RELEASED_DATE) &gt; 1 ) ) ) Python Passing parameters with dates handled in Access engine. conn = pyodbc.connect(r'...') insights_dbcurs = conn.cursor() sql = """DELETE FROM RELEASES r WHERE r.ID IN (SELECT sub.ID FROM RELEASES sub WHERE sub.RELEASED_BY = ? AND ( ( DatePart('m', sub.RELEASED_DATE) = DatePart('m', Date()) - 1 AND DatePart('yyyy', sub.RELEASED_DATE) = DatePart('yyyy', Date()) AND DatePart('d', sub.RELEASED_DATE) = 1 ) OR ( DatePart('m', sub.RELEASED_DATE) = DatePart('m', Date()) AND DatePart('yyyy', sub.RELEASED_DATE) = DatePart('yyyy', Date()) AND DatePart('d', sub.RELEASED_DATE) &gt; 1 ) ) )""" insights_dbc…
has comment: http://stackoverflow.com/comment/91627476
answers question: http://stackoverflow.com/q/52336916
has comment: http://stackoverflow.com/comment/91624347
has comment: http://stackoverflow.com/comment/91627709
has comment: http://stackoverflow.com/comment/91626121

http://stackoverflow.com/a/52339459
accepted answer of: http://stackoverflow.com/q/52339143
type: Answer
upvote count: 1
has body: Your element is not a HTML select tag and it's not possible to use Selenium's Select class on it. Instead get all elements with tag mat-option under div.mat-select-content: selectOptions = drowser.find_elements_by_css_selector("div.mat-select-content mat-option") print len(selectOptions)
score: 1
answers question: http://stackoverflow.com/q/52339143
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52424786
upvote count: 1
has answer: http://stackoverflow.com/a/52424988
accepted answer: http://stackoverflow.com/a/52425134
has title: Replacing one character with two (\n by \r\n ) replaces also one of the replacing characters
possible better answer: http://stackoverflow.com/a/52424988
type: AnsweredQuestion
has body: I'm trying to convert large number of files to a common line endings with this script. The script is called in git-shell using for loop. After running all line endings have only CR as line ending. I suppose because replace(contents, '\n', '\r\n' ) replaces also \n after \r. Is there a may to prevent it? Should I replace linewise? import sys import string import os.path for file in sys.argv[1:]: if not os.path.exists(file): continue contents = open(file, 'rb').read() cont1 = string.replace(contents, '\n', '\r\n' ) open(file, 'wb').write(cont1)
downvote count: 0
has comment: http://stackoverflow.com/comment/91792286
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/91792970
tagged with: python
has answer: http://stackoverflow.com/a/52425134
has comment: http://stackoverflow.com/comment/91792440
answer count: 2

pygobject
type: Tag
tags question: http://stackoverflow.com/q/52304262
tag name: pygobject
tags question: http://stackoverflow.com/q/52295072

http://stackoverflow.com/comment/91590049
comment on: http://stackoverflow.com/q/52321208
score: 0
type: Comment
has text: Can you please explain what you expect to happen, and what happens instead?
type: QuestionComment

http://stackoverflow.com/a/52325270
downvote count: 0
score: 2
upvote count: 2
has body: To Further help I would ask you the following. Error Checking After your import using any of your three ways, are there any results from running this after each run? SELECT @@GLOBAL.SQL_WARNINGS; (if so this should show you the errors, as it might be silently failing.) What is your SQL_MODE? SELECT @@GLOBAL.SQL_MODE; Check the file and make sure you have an even number of "'s for one. Check the data for extra " or ,'s or anything that may get caught in translation of bash/python/mysql? Data Request Can you provide the data for the 1st row that was missing? Can you provide the exact script you are using? Versions You said your using python 2.7 What version of mysql client? SELECT @@GLOBAL.VERSION; What version of MySQLdb? Internationalization Are you dealing with internationalization (汉语 Hànyǔ or русский etc. languages)? What is the database/schema collation? Query: SELECT DISTINCT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE ( SCHEMA_NAME &lt;&gt; 'sys' AND SCHEMA_NAME &lt;&gt; 'mysql' AND SCHEMA_NAME &lt;&gt; 'information_schema' AND SCHEMA_NAME &lt;&gt; '.mysqlworkbench' AND SCHEMA_NAME &lt;&gt; 'performance_schema' ); What is the Table collation? Query: SELECT DISTINCT ENGINE, TABLE_COLLATION FROM INFORMATION_SCHEMA.TABLES WHERE ( TABLE_SCHEMA &lt;&gt; 'sys' AND TABLE_SCHEMA &lt;&gt; 'mysql' AND TABLE_SCHEMA &lt;&gt; 'information_schema' AND TABLE_SCHEMA &lt;&gt; '.mysqlworkbench' AND TABLE_SCHEMA &lt;&gt; 'performance_schema' ); What is the column collation? Query: SELECT DISTINCT CHARACTER_SET_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE ( TABLE_SCHEMA &lt;&gt; 'sys' AND TABLE_SCHEMA &lt;&gt; 'mysql' AND TABLE_SCHEMA &lt;&gt; 'information_schema' AND TABLE_SCHEMA &lt;&gt; '.mysqlworkbench' AND TABLE_SCHEMA &lt;&gt; 'performance_schema' ); Lastly Check the Database For connection collation/character_set SHOW VARIABLES WHERE VARIABLE_NAME LIKE 'CHARACTER\_SET\_%' OR VARIABLE_NAME LIKE 'COLLATION%'; If the…
has comment: http://stackoverflow.com/comment/91597715
has comment: http://stackoverflow.com/comment/91600629
answers question: http://stackoverflow.com/q/52323278
type: Answer

http://stackoverflow.com/comment/91617909
score: 1
has text: Presumably you get a 2D matrix in your code. `if results[0] == True:` would then be equivalent to something like `if [0, 0, False, 0] == True`. In that case, the array _as a whole_ is truthy, but the only actual `bool` in the list is `False`. You might get away with truthy-ness in Python, but `numpy` is asking you to be specific about what it's supposed to be comparing since it uses array programming.
comment on: http://stackoverflow.com/q/52335291
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91530562
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52290175
has text: What classes do you inherit from? Only `BaseEstimator` and `TransformerMixin`, or another one?

http://stackoverflow.com/a/52359229
answers question: http://stackoverflow.com/q/52356645
type: Answer
downvote count: 1
upvote count: 5
score: 4
has body: Gunicorn can help you: gunicorn module:app --bind 0.0.0.0:8080 --worker-class aiohttp.GunicornWebWorker --workers 4
has comment: http://stackoverflow.com/comment/91813918

http://stackoverflow.com/comment/91694087
comment on: http://stackoverflow.com/a/52374588
score: 1
has text: OP is using Python 2.7. I think unpacking within a list isn't going to fly. ;-)
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91668030
score: 0
type: Comment
has text: read the [documentation](https://docs.opencv.org/2.4/modules/core/doc/operations_on_arrays.html#void%20subtract(InputArray%20src1,%20InputArray%20src2,%20OutputArray%20dst,%20InputArray%20mask,%20int%20dtype)) for `subtract` function. It says: `subtract` calculates Difference between two arrays, when both input arrays have the same size and the same number of channels
comment on: http://stackoverflow.com/a/52361555
type: AnswerComment

http://stackoverflow.com/a/52369136
has body: You can try the following: split the input, reverse the tokens using the [::-1] slice, and join them back together. input = 'john doe garry' rev = ' '.join(input.split()[::-1]) print(rev) # garry doe john
answers question: http://stackoverflow.com/q/52369089
score: 3
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/91682780
downvote count: 0

http://stackoverflow.com/comment/91671627
has text: If the the input images are 10x10 then why the `size=100`? I think that's what has confused you. Plus, as you may or may not know [the dense layer is applied on the last axis](https://stackoverflow.com/a/52092176/2099607); so as you can see in the model summary, the `Dense(1)` is applied on the last axis of output of convolution layer before it.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52359905
type: Comment

http://stackoverflow.com/q/52391572
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/35562789
tagged with: word2vec
tagged with: python
tagged with: gensim
has comment: http://stackoverflow.com/comment/91737835
has comment: http://stackoverflow.com/comment/91735817
tagged with: nlp
has comment: http://stackoverflow.com/comment/91748262
answer count: 0
tagged with: corpus
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91730933
has body: I am trying to use a text corpus file (One sentence by line) to extarct words co-occurrence from it in order to use them in a later traitement. So how can i extract word(statistical) co-occurrence from large corpus file using gensim and how to use them later ?
score: 0
linked to: http://stackoverflow.com/q/42814452
has comment: http://stackoverflow.com/comment/91729856
favorite count: 0
has title: Gensim: How to extract words co-occurrence?
has comment: http://stackoverflow.com/comment/91728480
has comment: http://stackoverflow.com/comment/91731130

http://stackoverflow.com/q/52288066
has body: I am using Haar cascade in an emotion detection system. Every video input I am giving to the model has only one face in it (It is a requirement). When I run Haar cascade model to detect faces, it has some false positives. Since I have only one face in the video, I want to take the most positive area detected and ignore all other detection. Is there a way to do that?
tagged with: deep-learning
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/52288261
favorite count: 0
tagged with: face-detection
tagged with: python
score: 2
upvote count: 2
has title: how to limit number of faces detected by haar cascades
type: Question
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52288261
tagged with: haar-classifier

http://stackoverflow.com/q/52307224
has comment: http://stackoverflow.com/comment/91561827
has answer: http://stackoverflow.com/a/52307301
tagged with: python
has answer: http://stackoverflow.com/a/52307303
has comment: http://stackoverflow.com/comment/91561714
has comment: http://stackoverflow.com/comment/91561707
has title: Interpretation of this command
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52307301
accepted answer: http://stackoverflow.com/a/52307303
downvote count: 1
type: AnsweredQuestion
score: -1
type: Question
has body: I am really new to python and come majorly from programming in R. While studying I came across this snippet of code. xs=[()] res=[False]*2 if xs: res[0]= True if xs[0]: res[1]=True print(res) Initially I thought that this is a way to initialize an empty array. However when I run the same snippet replacing the initialize part with an empty list, it gives me an error. xs=list() res=[False]*2 if xs: res[0]= True if xs[0]: res[1]=True print(res) Can someone please help me understand the difference between these 2 codes. Any help is appreciated. Thanks!
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/91561596

http://stackoverflow.com/comment/91677696
comment on: http://stackoverflow.com/a/52338697
score: 0
type: AnswerComment
type: Comment
has text: I tested your solution and I found a small problem. By using the merge method, you will have several departure flights linked to the same arrival. That is why I used the column `Already_linked` and in each iteration that column would be updated. Is there any way to solve this problem?

http://stackoverflow.com/a/52330445
type: Answer
has comment: http://stackoverflow.com/comment/91612049
upvote count: 4
has body: Since you already have a trained graph saved in a checkpoint, in theory the simplest solution for you is to export the inference graph via optimize_for_inference. This tool works both for already-frozen graphs and, as is your case, for graphs with variables still defined. Assuming you go for the frozen graph way, the first step is to transform your graph's variables in constants via: python freeze_graph.py \ --input_graph=temp/path/graph.pbtxt \ --input_checkpoint=temp/path/your_model_name.ckpt \ --output_graph=frozen_model.pb \ --output_node_names=name_of_the_output_tensor_you_want_to_use This will generate a new binary file called frozen_model.pb that has the Variable operations replaced with Const ops with the values loaded from the checkpoint file. Then, you need to generate the inference graph with: python optimize_for_inference.py \ --input=frozen_model.pb \ --output=inference.pb \ --frozen_graph=True \ --input_names=IteratorGetNext --output_names=name_of_the_output_tensor_you_want_to_use This will replace the IteratorGetNext node with a float placeholder. You might want to choose another node, in which case just change the name. You can also change the type of the generated placeholder via the --placeholder_type_enum option. In that case, you need to provide an integer value matching the datatype you want from the DataType enum. NOTE: I said "in theory" because actually inspecting the generated inception graph from a test I made it seems there are still some weird ops in there that are not really necessary for inference. You might have to further process your graph via nvidia's Graph Surgeon or TF's graph transform tool
has comment: http://stackoverflow.com/comment/100830957
has comment: http://stackoverflow.com/comment/100826395
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/91616388
has comment: http://stackoverflow.com/comment/91612520
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52319765
answers question: http://stackoverflow.com/q/52319765

http://stackoverflow.com/comment/91712824
score: 0
has text: What is serving the static assets? Why have you nested them under /diaoibou?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52384416

http://stackoverflow.com/a/52364853
answers question: http://stackoverflow.com/q/52364836
has body: because else has to be lonely there (meaning that nothing is right), so maybe elif again: def tesla (x,y) : if x &gt; y : return "1" elif x == y : return 0 elif x &lt; y : return -1 But in this case can be direct else because no other cases that could happen: def tesla (x,y) : if x &gt; y : return "1" elif x == y : return 0 else: return -1
score: 2
has comment: http://stackoverflow.com/comment/91677398
downvote count: 0
type: Answer
upvote count: 2

http://stackoverflow.com/comment/91671225
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52363546
has text: Thank you @jezrael for your help :)

http://stackoverflow.com/q/52391727
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52393803
has comment: http://stackoverflow.com/comment/91728626
has body: Let's say we have multiple functions which all accept an URL as their first argument and this URL needs to be validated. This can be nicely solved with a decorator def validate_url(f): def validated(url, *args, **kwargs): assert len(url.split('.')) == 3 # trivial example return f(url, *args, **kwargs) return validated @validate_url def some_func(url, some_other_arg, *some_args, **some_kwargs): pass This approach will work and allow me to factor the validation behavior out of many instances of similar functions. But now I would want to write a class method which also takes a validated URL. However, the naive approach will not work class SomeClass: @validate_url def some_method(self, url, some_other_args): pass because we will end up attempting to validate self and not url. My question is how to write a single decorator which will work for both functions and methods with the minimum amount of boilerplate. Note 1: I am aware why this happens, it's just that I don't know how to work around this in the most elegant manner. Note 2: The URL validation problem is just an example, so checking if isinstance(args[0], str) is not a good solution.
score: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52393803
tagged with: python
linked to: http://stackoverflow.com/q/53225
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91731862
has title: Decorator which skips `self` for methods
upvote count: 1

http://stackoverflow.com/q/52401988
has answer: http://stackoverflow.com/a/52402505
has answer: http://stackoverflow.com/a/52402430
has comment: http://stackoverflow.com/comment/91747962
has comment: http://stackoverflow.com/comment/91748055
has answer: http://stackoverflow.com/a/52402145
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
tagged with: lambda
answer count: 4
tagged with: list
has answer: http://stackoverflow.com/a/52402070
type: Question
has comment: http://stackoverflow.com/comment/91747906
has title: Get the least greater than value from python list of dictionaries
score: 0
has comment: http://stackoverflow.com/comment/91748053
has comment: http://stackoverflow.com/comment/91748188
has comment: http://stackoverflow.com/comment/91747946
has body: What I want to achieve? I have the following list of dictionaries. values=[ { "tax": 6, "threshold": 1000 }, { "tax": 9, "threshold": 2500 }, { "tax": 14, "threshold": 7500 } ] I want to get the least value of tax, applicable to some amount which is greater than or equal to the value. Let's say: If my amount is 1100 and I compare it to the threshold of these dicts. I should get the value of tax = 9. What I've been able to do so far? floor_value = map(lambda x: x.get("tax") if x.get( "threshold") &gt; 1000 else None, values) print (floor_value) output: [None, 9, 14] What I want is floor_value = 9

http://stackoverflow.com/q/52429587
upvote count: 5
tagged with: bayesian
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/52434726
score: 5
tagged with: python
tagged with: pymc3
has comment: http://stackoverflow.com/comment/91805432
tagged with: dirichlet
answer count: 1
has title: pymc3 : Dirichlet with multidimensional concentration factor
tagged with: multinomial
accepted answer: http://stackoverflow.com/a/52434726
has body: I am struggling with implementing a model where the concentration factor of the Dirichlet variable is dependent on another variable. The situation is the following: A system fails due to faulty components (there are three components, only one fails at each test/observation). The probability of failure of the components is dependent on the temperature. Here is a (commented) short implementation of the situation: import numpy as np import pymc3 as pm import theano.tensor as tt # Temperature data : 3 cold temperatures and 3 warm temperatures T_data = np.array([10, 12, 14, 80, 90, 95]) # Data of failures of 3 components : [0,0,1] means component 3 failed F_data = np.array([[0, 0, 1], \ [0, 0, 1], \ [0, 0, 1], \ [1, 0, 0], \ [1, 0, 0], \ [1, 0, 0]]) n_component = 3 # When temperature is cold : Component 1 fails # When temperature is warm : Component 3 fails # Component 2 never fails # Number of observations : n_obs = len(F_data) # The number of failures can be modeled as a Multinomial F ~ M(n_obs, p) with parameters # - n_test : number of tests (Fixed) # - p : probability of failure of each component (shape (n_obs, 3)) # The probability of failure of components follows a Dirichlet distribution p ~ Dir(alpha) with parameters: # - alpha : concentration (shape (n_obs, 3)) # The Dirichlet distributions ensures the probabilities sum to 1 # The alpha parameters (and the the probability of failures) depend on the temperature alpha ~ a + b * T # - a : bias term (shape (1,3)) # - b : describes temperature dependency of alpha (shape (1,3)) _ # The prior on "a" is a normal distributions with mean 1/2 and std 0.001 # a ~ N(1/2, 0.001) # The prior on "b" is a normal distribution zith mean 0 and std 0.001 # b ~ N(0, 0.001) # Coding it all with pymc3 with pm.Model() as model: a = pm.Normal('a', 1/2, 1/(0.001**2), shape = n_component) b = pm.Normal('b', 0, 1/(0.001**2), shape = n_component) # I generate 3 alphas values (corresponding to the 3 components) for each of the 6 temperatures #…

http://stackoverflow.com/comment/91646186
type: QuestionComment
has text: Under the folder build\exe.win-amd64-3.6\lib, I can see the cytoolz and scipy, do I still need to add them into buildOptions ?
comment on: http://stackoverflow.com/q/52320664
score: 0
type: Comment

http://stackoverflow.com/comment/91652179
type: Comment
type: QuestionComment
has text: Possible duplicate of [Generate a random letter in Python](https://stackoverflow.com/questions/2823316/generate-a-random-letter-in-python)
comment on: http://stackoverflow.com/q/52353686
score: 0

http://stackoverflow.com/q/52337536
tagged with: websocket
tagged with: flask
favorite count: 0
has answer: http://stackoverflow.com/a/52339134
tagged with: kubernetes
tagged with: python
has title: websocket on port 443 with /socket.io under kubernetes not working
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91623702
score: 1
has comment: http://stackoverflow.com/comment/91624585
tagged with: minikube
type: Question
upvote count: 1
has body: Trying to move my development environment to run on minikube. The page loads but my page uses websockets on the same port/protocol that the index.html is loaded with (https in this case), and the websockets do no seem to be working correctly. Here is an example of the correct output when run through nginx / python on my local development box. 127.0.0.1 - - [14/Sep/2018 14:14:35] "GET / HTTP/1.0" 200 - 127.0.0.1 - - [14/Sep/2018 14:14:35] "GET /static/jquery.min.js HTTP/1.0" 200 - 127.0.0.1 - - [14/Sep/2018 14:14:35] "GET /static/socket.io.min.js HTTP/1.0" 200 - 127.0.0.1 - - [14/Sep/2018 14:14:35] "GET /socket.io/?EIO=3&amp;transport=polling&amp;t=MNPIg-N HTTP/1.0" 200 - 127.0.0.1 - - [14/Sep/2018 14:14:35] "GET /favicon.ico HTTP/1.0" 404 - 127.0.0.1 - - [14/Sep/2018 14:14:35] "GET /favicon.ico HTTP/1.0" 404 - 127.0.0.1 - - [14/Sep/2018 14:14:35] "POST /socket.io/?EIO=3&amp;transport=polling&amp;t=MNPIg-o&amp;sid=0570b4fe27f345e9b11858b3acb40a6e HTTP/1.0" 200 - 127.0.0.1 - - [14/Sep/2018 14:14:35] "GET /socket.io/?EIO=3&amp;transport=polling&amp;t=MNPIg-r&amp;sid=0570b4fe27f345e9b11858b3acb40a6e HTTP/1.0" 200 - 127.0.0.1 - - [14/Sep/2018 14:14:35] "POST /socket.io/?EIO=3&amp;transport=polling&amp;t=MNPIg_x&amp;sid=0570b4fe27f345e9b11858b3acb40a6e HTTP/1.0" 200 - 127.0.0.1 - - [14/Sep/2018 14:14:35] "GET /socket.io/?EIO=3&amp;transport=polling&amp;t=MNPIg_w&amp;sid=0570b4fe27f345e9b11858b3acb40a6e HTTP/1.0" 200 - 127.0.0.1 - - [14/Sep/2018 14:14:40] "GET /socket.io/?EIO=3&amp;transport=polling&amp;t=MNPIh0L&amp;sid=0570b4fe27f345e9b11858b3acb40a6e HTTP/1.0" 200 - 127.0.0.1 - - [14/Sep/2018 14:14:45] "GET /socket.io/?EIO=3&amp;transport=polling&amp;t=MNPIiE3&amp;sid=0570b4fe27f345e9b11858b3acb40a6e HTTP/1.0" 200 - 127.0.0.1 - - [14/Sep/2018 14:14:50] "GET /socket.io/?EIO=3&amp;transport=polling&amp;t=MNPIjSI&amp;sid=0570b4fe27f345e9b11858b3acb40a6e HTTP/1.0" 200 - 127.0.0.1 - - [14/Sep/2018 14:14:55] "GET /socket.io/?EIO=3&amp;transport=polling&amp;t=MNPIkgS&amp;sid=0…
answer count: 1

http://stackoverflow.com/q/52408705
tagged with: loops
has body: I am sure this is an easy fix, but I haven't been able to find the exact solution to my problem. My data set has a column called 'LANE' which contains unique values. I want to add rows for each 'LANE' based on a range of numbers (which would be 0 to 12). As a result each 'LANE' would have 13 rows with a new column 'NUMBER' ranging from 0 up to and including 12. Example: Input LANE a b Output LANE NUMBER a 0 a 1 a 2 a 3 a 4 a 5 a 6 a 7 a 8 a 9 a 10 a 11 a 12 b 0 b 1 b 2 b 3 b 4 b 5 b 6 b 7 b 8 b 9 b 10 b 11 b 12 I am currently trying different forms of: num = 0 while num &lt;= 12: for x in df['LANE']: df['NUMBER'] = num num += 1 The problem with this loop is, I still have one record for each lane and the 'NUMBER' column only has the value 12.
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52409318
upvote count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/52409318
tagged with: python
has answer: http://stackoverflow.com/a/52408751
accepted answer: http://stackoverflow.com/a/52408751
score: 2
has title: Loop to create a new row for a given range of numbers
type: AnsweredQuestion

http://stackoverflow.com/comment/91824714
score: 0
comment on: http://stackoverflow.com/q/52420585
type: QuestionComment
type: Comment
has text: My current solution checks the age of the directories in `/tmp/<username>/JModelica.org/` and deletes occurrences older than a specific limit.

http://stackoverflow.com/comment/91660472
comment on: http://stackoverflow.com/a/52357960
has text: Okay that makes more sense, thank you so much. I'm really loving the idea of designing my own programs and simple games, but I've found myself unduly angry a few too many times, I'm gonna check this out in a moment; I can have my computer at work but Football has us busy. I'll come back and let you know if it worked out.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/52358908
has title: Passing parameter to a python class when initializing it asynchronously
upvote count: 3
has body: I was looking at this answer where they explain how to initialize a class asynchronously with the method __await__. The question is: is it possible to pass parameters when awaiting the initialization of the class, just like when it is initialized synchronously? In other words, I'd like to be able to do my_class = await MyClass(my_parameter), however I wasn't able to make it work in any way. Should I just fall back to using the classic __init__ like in this answer?
type: Question
possible better answer: http://stackoverflow.com/a/52362240
tagged with: async-await
has answer: http://stackoverflow.com/a/52362240
linked to: http://stackoverflow.com/q/37369849
answer count: 2
has answer: http://stackoverflow.com/a/52358950
score: 3
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/33128325
tagged with: python-3.x
tagged with: python-asyncio
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52358950

http://stackoverflow.com/q/52303579
possible better answer: http://stackoverflow.com/a/56797338
tagged with: saml
has answer: http://stackoverflow.com/a/56797338
has comment: http://stackoverflow.com/comment/91575392
has title: ImportError: No module named saml2.auth
has comment: http://stackoverflow.com/comment/91561616
has answer: http://stackoverflow.com/a/52629932
answer count: 3
upvote count: 7
has comment: http://stackoverflow.com/comment/91577120
has body: I'm trying to build a SAML authentication mechanism in Python using the OneLogin module, but I keep getting this error: ImportError: No module named saml2.auth I have followed the steps listed here: https://github.com/onelogin/python3-saml and installed dependencies as well but i can't install xmlsec library and it says Failed building wheel for xmlsec and failed with error code 1. (I have done pip install wheel as well) Any suggestions how to get around this error?
favorite count: 0
has comment: http://stackoverflow.com/comment/91557979
has answer: http://stackoverflow.com/a/52404450
accepted answer: http://stackoverflow.com/a/52404450
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91554867
tagged with: onelogin
downvote count: 0
score: 7
type: Question

http://stackoverflow.com/q/52306842
has comment: http://stackoverflow.com/comment/91624100
has comment: http://stackoverflow.com/comment/92210466
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/92210468
score: 0
tagged with: keras
has comment: http://stackoverflow.com/comment/91624866
has comment: http://stackoverflow.com/comment/91562283
type: UnansweredQuestion
tagged with: python
has title: Integral of Function - Keras Custom Loss
answer count: 0
has body: I am trying to create a custom loss function which integrates an input curve. The curve can be a mix of polynomial, exponential, and sinusoidal. The inputs are of the form: [x0, x1, ...., x9] where x0-x3 are the polynomial coefficients, x4-x6 are the exponential coefficients and x7-x9 are the sinusoidal coefficients. EDIT: I got the following to compile but I would like to have a much more precise integration result. def integrate_loss(y_true, y_pred): x_range = K.arange(-5.0, 5.0, step=1, dtype='float32') y_true_pol = y_true[0]*x_range**3+y_true[1]*x_range**2+y_true[2]*x_range+y_true[3] y_pred_pol = y_pred[0]*x_range**3+y_pred[1]*x_range**2+y_pred[2]*x_range+y_pred[3] diff_pol = K.abs(K.sum(y_true_pol - y_pred_pol)) y_true_exp = y_true[4]*K.exp(y_true[5]*(x_range-y_true[6])) y_pred_exp = y_pred[4]*K.exp(y_pred[5]*(x_range-y_pred[6])) diff_exp = K.abs(K.sum(y_true_exp - y_pred_exp)) y_true_sin = y_true[7]*K.sin(y_true[8]*(x_range-y_true[9])) y_pred_sin = y_pred[7]*K.sin(y_pred[8]*(x_range-y_pred[9])) diff_sin = K.abs(K.sum(y_true_sin - y_pred_sin)) area_between = diff_pol + diff_exp + diff_sin return area_between EDIT: This produces the following errors: Epoch 1/150 9/18 [==============&gt;...............] - ETA: 1s - loss: 41.94232018-09-13 13:03:56.343324: W tensorflow/core/framework/op_kernel.cc:1158] Invalid argument: slice index 4 of dimension 0 out of bounds. 2018-09-13 13:03:56.343324: W tensorflow/core/framework/op_kernel.cc:1158] Invalid argument: slice index 2 of dimension 0 out of bounds. 2018-09-13 13:03:56.343324: W tensorflow/core/framework/op_kernel.cc:1158] Invalid argument: slice index 3 of dimension 0 out of bounds. 2018-09-13 13:03:56.343329: W tensorflow/core/framework/op_kernel.cc:1158] Invalid argument: slice index 6 of dimension 0 out of bounds. 2018-09-13 13:03:56.343331: W tensorflow/core/framework/op_kernel.cc:1158] Invalid argument: slice index 5 of dimension 0 out of bounds. 2018-09-13 13:03:56.343485: W tensorflow/core/framework/op_kerne…

http://stackoverflow.com/comment/91568439
comment on: http://stackoverflow.com/q/52310731
score: 0
has text: I am using the Python 3.6.5
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52280524
upvote count: 1
has answer: http://stackoverflow.com/a/52281242
downvote count: 1
type: Question
has body: I'm new to Pandas and trying to create a new dataframe from an existing one. My current dataframe has a format: ID Country Status ABC USA Go ABC Columbia Stop ABC Japan Pause ABC Egypt Go DEF Canada Go DEF Peru Stop I'm trying to consolidate the data to make it more compact. My new format is: ID Go Stop Pause ABC USA, Egypt Columbia Japan DEF Canada Peru Basically, the possible Status values become the columns and, for each ID, these columns are populated with a list of countries having that status. I'm new to pandas and struggling with the best way to approach this - any suggestions would be greatly appreciated.
has title: Pandas Dataframes - new dataframe with reorganized data
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/52281306
score: 0
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/91516600
has comment: http://stackoverflow.com/comment/91510513
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91509226
accepted answer: http://stackoverflow.com/a/52281242
has answer: http://stackoverflow.com/a/52281306
type: AnsweredQuestion

http://stackoverflow.com/comment/91507456
comment on: http://stackoverflow.com/q/52278105
has text: In theory, the appropriate forums are [Cross Validated](https://stats.stackexchange.com/) and [Data Science](https://datascience.stackexchange.com/), but I highly doubt that you will get any meaningful answer even there, since your question is also too vague, plus it touches on interpretation issues, which is still a hot topic of current research...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91509916
comment on: http://stackoverflow.com/q/52280214
has text: What about changing `return round(full,2)` to `return full`?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52380557
accepted answer of: http://stackoverflow.com/q/52380530
answers question: http://stackoverflow.com/q/52380530
type: Answer
has body: Maybe you're overthinking this, but just remove anything that isn't a digit from that column? # Setup df = pd.DataFrame({'number' : ['234-567-8901', '(234)-567-8901', '2345678901']}) print(df) number 0 234-567-8901 1 (234)-567-8901 2 2345678901 df['number'] = df.number.str.replace(r'\D+','') print(df) number 0 2345678901 1 2345678901 2 2345678901
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/91724992
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91694065
has text: @MarkAnt already working on it , just solving the doubles portion
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52374350

http://stackoverflow.com/comment/91725526
type: QuestionComment
comment on: http://stackoverflow.com/q/52373167
has text: Expecting derivatives of a spline to look smooth ignores the fact that splines are defined in a piecewise manner.
type: Comment
score: 1

http://stackoverflow.com/comment/91646991
score: 0
type: Comment
type: QuestionComment
has text: OK, this took me a while, but basically, your x labels should start at 0.
comment on: http://stackoverflow.com/q/52350774

http://stackoverflow.com/comment/91522892
type: Comment
score: 1
type: QuestionComment
has text: Not sure if this helps, but I get different `dtype`s: `row` is `int32` (you had `int64`), df is `float64` and it prints `row 0.0` on the last line. pandas `0.23.3`, python `3.6.6`, numpy `1.15.0`
comment on: http://stackoverflow.com/q/52287530

http://stackoverflow.com/comment/140265777
comment on: http://stackoverflow.com/q/52358505
has text: @MaximDsouza OP is talking about code that detects cancer. They _absolutely_ should strengthen their understanding, and should never be "in a hurry"; lives are allegedly at stake.
score: 0
type: Comment
type: QuestionComment

amazon-rds
tags question: http://stackoverflow.com/q/52403012
tag name: amazon-rds
tags question: http://stackoverflow.com/q/52415197
tags question: http://stackoverflow.com/q/52296365
type: Tag
tags question: http://stackoverflow.com/q/52422395

http://stackoverflow.com/comment/91687528
comment on: http://stackoverflow.com/q/52371264
has text: @wen tried, all value is nan then.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91590884
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52321586
type: AnswerComment
has text: yea.... this is it..... I created the object but didn't `save()`........

http://stackoverflow.com/comment/91581957
comment on: http://stackoverflow.com/a/52280393
score: 0
type: AnswerComment
has text: Looks like its working now, I must have changed something and forgotten. Again, thanks!
type: Comment

http://stackoverflow.com/q/52390892
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91729618
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52396690
has comment: http://stackoverflow.com/comment/91729657
upvote count: 0
answer count: 1
has title: Get a subarray from a 3d matrix by fixing one axis like in NumPy index+slices
tagged with: javascript
favorite count: 0
has comment: http://stackoverflow.com/comment/91730016
has body: My input is a 3x3x3 array such as this one: m = [[[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]]] And these are the outputs that I would like to get, using only vectorial or matricial operations: out1 = [[0,1,2],[3,4,5],[6,7,8]] (corresponding to indice 0 along first axis) out2 = [[0,1,2],[9,10,11],[18,19,20]] (corresponding to indice 0 along second axis) out3 = [[0,3,6],[9,12,15],[18,21,24]] (corresponding to indice 0 along third axis) I know that I can do that with python using numpy like this: cube = np.arange(27).resize(3,3,3) out1 = cube[0,:,:] out2 = cube[:,0,:] out3 = cube[:,:,0] But I need to implement this in javascript. I know how to to do it with loops and indices but I thought there may be a more efficient way to do it.
has comment: http://stackoverflow.com/comment/91729368
tagged with: matrix
has answer: http://stackoverflow.com/a/52396690
has comment: http://stackoverflow.com/comment/91729040
has comment: http://stackoverflow.com/comment/91728290
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/91730346

http://stackoverflow.com/comment/91796111
type: QuestionComment
comment on: http://stackoverflow.com/q/52423549
has text: It seems that you want to operate on both keys and values at the same time. Are you looking for ``counter.items()`` perhaps? Otherwise, can you please clarify how your value operations relate to the key operations?
score: 0
type: Comment

http://stackoverflow.com/q/52287117
has answer: http://stackoverflow.com/a/62661553
has answer: http://stackoverflow.com/a/77487296
tagged with: python
has answer: http://stackoverflow.com/a/60619417
has answer: http://stackoverflow.com/a/74958881
tagged with: anaconda
has comment: http://stackoverflow.com/comment/103551742
has answer: http://stackoverflow.com/a/66986780
has answer: http://stackoverflow.com/a/71192298
has comment: http://stackoverflow.com/comment/103525699
has answer: http://stackoverflow.com/a/77998495
score: 41
has answer: http://stackoverflow.com/a/75942630
has comment: http://stackoverflow.com/comment/91525556
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/66085333
has answer: http://stackoverflow.com/a/76506548
has comment: http://stackoverflow.com/comment/91522214
has answer: http://stackoverflow.com/a/63559159
linked to: http://stackoverflow.com/q/70182993
has comment: http://stackoverflow.com/comment/91522175
has answer: http://stackoverflow.com/a/77029582
has answer: http://stackoverflow.com/a/72294694
has answer: http://stackoverflow.com/a/53259151
has body: I installed python and jupyter notebook through the Anaconda distribution. I have been successfully using jupyter notebook for weeks and it has run perfectly fine. However, I can only launch a notebook through the Anaconda Navigator GUI. When I try to run the command (in command prompt) to start a notebook it says 'jupyter' is not recognized as an internal or external command This is also the same case with Python 'python' is not recognized as an internal or external command I am using Windows 10. I am assuming its a PATH issue but I have not had any luck with the solutions I found from other posts. I am relatively new to programming and python so any help would be greatly appreciated.
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/91522457
favorite count: 0
type: Question
upvote count: 41
answer count: 14
has title: 'Jupyter' is not recognized as an internal or external command

http://stackoverflow.com/comment/91564946
comment on: http://stackoverflow.com/q/52300267
score: 0
type: Comment
type: QuestionComment
has text: @eyllanesc i have added some pictures

http://stackoverflow.com/q/52271413
type: UnansweredQuestion
tagged with: python
has title: can not find a version when I install tensorflow
duplicate of: http://stackoverflow.com/q/38896424
has answer: http://stackoverflow.com/a/52272094
linked to: http://stackoverflow.com/q/38896424
tagged with: tensorflow
type: Question
has body: this is my symptom: [shankai@shankai ~]$ pip3 install tensorflow Collecting tensorflow Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching distribution found for tensorflow my python : 3.7 64bit os : ArchLinux
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52271787
tagged with: linux

http://stackoverflow.com/a/52336553
has body: Here you go, I'm assuming you are starting at 0 if not just use [2::2] code = int(input("Enter code: ")) numbers = [] for i in (str(code)): numbers.append(int(i)) total = sum(numbers[::2]) print(total) (xenial)vash@localhost:~/python$ python3.7 code.py Enter code: 123456 9
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52334113

http://stackoverflow.com/comment/91634494
comment on: http://stackoverflow.com/q/52344228
has text: db.execute("INSERT INTO users (name,pw,email) VALUES ('+Name1+','+pw1+','+Email1+')"), shouldn't it be concanated?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52327380
downvote count: 1
upvote count: 0
answers question: http://stackoverflow.com/q/52327163
has body: Last number is never included in python range. You need to adjust the code accordingly. e.g. To print values form -5 to -1(included) use, &gt;&gt;&gt; print(list(range(-5, 0))) [-5, -4, -3, -2, -1] In reverse order &gt;&gt;&gt; print(list(range(-1, -6, -1))) [-1, -2, -3, -4, -5]
score: -1
type: Answer

http://stackoverflow.com/comment/91707961
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52381779
has text: you need to do `a[0]==b[0]`, i think, to compare the values. Here is more on that : https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python

http://stackoverflow.com/a/52386222
has comment: http://stackoverflow.com/comment/91761272
upvote count: 1
has comment: http://stackoverflow.com/comment/91740542
answers question: http://stackoverflow.com/q/52385946
has comment: http://stackoverflow.com/comment/91721456
score: 1
has comment: http://stackoverflow.com/comment/91740570
has body: Your question isn't really clear, but I will ask your question in the title. If you have a string and you like to search a sub-string you can only use if substring in string: #do what you want to do another way is to use regular expression, here the documentations re python next time please share your script to help everyone to understand your problem ;) EDIT filename = "test.text" import re def splitAddresses(data): addresses=[] l=[] pattern=re.compile("^[GROUP]+[0-9]+[:]$") for element in data: isAmatch=pattern.match(element) if isAmatch==None: l.append(element) else: addresses.append(l) l=[] addresses.append(l) return(addresses[1:]) def parseAddress(): with open(filename) as f: data = f.readlines() addresses=splitAddresses(data) for element in addresses: prefix=element[0][32:36] length_data=len(element) for address in element[1:]: if address.count(prefix)!=2: element.remove(address) new_length = len(element) if new_length==length_data: print(element[0]) else: print(element[1:]) parseAddress() Tried with this file GROUP1: set group address "Private-MT" "ABCD45-48/70-71" set group address "Private-MT" "ABCD45-48/70-71" add "ABCD47" set group address "Private-MT" "ABCD45-48/70-71" add "ABCD48" set group address "Private-MT" "ABCD45-48/70-71" add "ABCD70" set group address "Private-MT" "ABCD45-48/70-71" add "ABCD71" GROUP2: set group address "Private-MT" "ABCD45-48/70-71" set group address "Private-MT" "ABCD45-48/70-71" add "ABCD47" set group address "Private-MT" "ABCD45-48/70-71" add "ABCD48" set group address "Private-MT" "ABCD45-48/70-71" add "XYCD70" set group address "Private-MT" "ABCD45-48/70-71" add "XYCD71" the Output was : set group address "Private-MT" "ABCD45-48/70-71" ['set group address "Private-MT" "ABCD45-48/70-71" add "ABCD47"\n', 'set group address "Private-MT" "ABCD45-48/70-71" add "ABCD48"\n'] you can edit the script and store infos because I did a print to show you that's works ;)
downvote count: 0
has comment: http://stackoverflow.com/comment/91717096
has comment: http://stackoverflow.com/comment/91716762
has comment: http://stackoverflow.com/comment/91717016
has comment: http://stackoverflow.com/comment/91723707
has comment: http://stackoverflow.com/comment/91717180
type: Answer
has comment: http://stackoverflow.com/comment/91720160
has comment: http://stackoverflow.com/comment/91758270
has comment: http://stackoverflow.com/comment/91740580
has comment: http://stackoverflow.com/comment/91787370
has comment: http://stackoverflow.com/comment/91746693
has comment: http://stackoverflow.com/comment/91724304
has comment: http://stackoverflow.com/comment/91718153

http://stackoverflow.com/q/52287487
has body: I have a background loop that will spit out an emoji every X amount of minutes with a reaction attached to it. I want for when someone presses on the reaction of the message, it will delete the message and then send another message saying "messageauthor has grabbed the loot" and then add the amount to the cash json file. Right now, my code is making the background loop work, but I am not sure how to grab the message.author.id in regards to the background loop so I can reference it in on_reaction_add. The current code is making the bot react once when it spits out the background loop and then again in on_reaction_add. I'm trying to make it wait for a user to react to the background loop message with the same emoji and not the bot. client = discord.Client() emoji_msg_grab = {} try: with open("cash.json") as fp: cash = json.load(fp) except Exception: cash = {} def save_cash(): with open("cash.json", "w+") as fp: json.dump(cash, fp, sort_keys=True, indent=4) def add_dollars(user: discord.User, dollars: int): id = user.id if id not in cash: cash[id] = {} cash[id]["dollars"] = cash[id].get("dollars", 0) + dollars print("{} now has {} dollars".format(user.name, cash[id]["dollars"])) save_cash() async def background_loop(): await client.wait_until_ready() while not client.is_closed: channel = client.get_channel("479919577279758340") emojigrab = '' emojimsgid = await client.send_message(channel, emojigrab) await client.add_reaction(emojimsgid, "") user_id = emojimsgid.author.id emoji_msg_grab[user_id] = {"emoji_msg_id": emojimsgid.id, "emoji_user_id": user_id} await asyncio.sleep(600) @client.event async def on_reaction_add(reaction, user): msgid = reaction.message.id chat = reaction.message.channel if reaction.emoji == "" and msgid == emoji_msg_grab[user.id]["emoji_msg_id"] and user.id == emoji_msg_grab[user.id]["emoji_user_id"]: emoji_msg_grab[user.id]["emoji_msg_id"] = None await client.send_message(chat, "{} has grabbed the loot!".format(user.mention)) await client.delet…
tagged with: python-3.x
type: Question
type: AnsweredQuestion
tagged with: discord.py
has answer: http://stackoverflow.com/a/52296274
score: 0
answer count: 1
has title: Background Loop with Reactions Discord.Py
tagged with: python
accepted answer: http://stackoverflow.com/a/52296274
tagged with: discord

http://stackoverflow.com/comment/91662479
has text: This is very interesting, but I agree, I should call the awaitables later on.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52358950
type: Comment

http://stackoverflow.com/comment/91540611
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52296306
has text: I would just do those calculations in the view and keep the template as dumb as possible. At least than you have access to the full datetime library.

django
tags question: http://stackoverflow.com/q/52353062
tags question: http://stackoverflow.com/q/52350429
tags question: http://stackoverflow.com/q/52358356
tags question: http://stackoverflow.com/q/52355620
tags question: http://stackoverflow.com/q/52379847
tags question: http://stackoverflow.com/q/52308132
tags question: http://stackoverflow.com/q/52335505
tags question: http://stackoverflow.com/q/52387118
tags question: http://stackoverflow.com/q/52292555
tags question: http://stackoverflow.com/q/52357452
tags question: http://stackoverflow.com/q/52345182
tags question: http://stackoverflow.com/q/52353962
tags question: http://stackoverflow.com/q/52423024
tags question: http://stackoverflow.com/q/52309584
tags question: http://stackoverflow.com/q/52338215
tags question: http://stackoverflow.com/q/52341904
tags question: http://stackoverflow.com/q/52305341
tags question: http://stackoverflow.com/q/52410615
tags question: http://stackoverflow.com/q/52318228
tags question: http://stackoverflow.com/q/52342961
tags question: http://stackoverflow.com/q/52355025
tags question: http://stackoverflow.com/q/52356305
tags question: http://stackoverflow.com/q/52386318
tags question: http://stackoverflow.com/q/52413802
tags question: http://stackoverflow.com/q/52338146
tags question: http://stackoverflow.com/q/52325662
tags question: http://stackoverflow.com/q/52321013
tags question: http://stackoverflow.com/q/52326782
tags question: http://stackoverflow.com/q/52343045
tags question: http://stackoverflow.com/q/52289325
tags question: http://stackoverflow.com/q/52394833
tags question: http://stackoverflow.com/q/52361130
tags question: http://stackoverflow.com/q/52360924
tags question: http://stackoverflow.com/q/52288560
tags question: http://stackoverflow.com/q/52281958
tags question: http://stackoverflow.com/q/52390968
tags question: http://stackoverflow.com/q/52416237
tags question: http://stackoverflow.com/q/52271368
tags question: http://stackoverflow.com/q/52367379
tags question: http://stackoverflow.com/q/52318358
tags question: http://stackoverflow.com/q/52327666
tags question: http://stackoverflow.com/q/52329266
tags question: http://stackoverflow.com/q/52329542
tags question: http://stackoverflow.com/q/52295245
tags question: http://stackoverflow.com/q/52313351
tags question: http://stackoverflow.com/q/52391139
tags question: http://stackoverflow.com/q/52352323
tags question: http://stackoverflow.com/q/52390390
tags question: http://stackoverflow.com/q/52304057
tags question: http://stackoverflow.com/q/52351237
tags question: http://stackoverflow.com/q/52338364
tags question: http://stackoverflow.com/q/52345911
tags question: http://stackoverflow.com/q/52414967
tags question: http://stackoverflow.com/q/52317752
type: Tag
tags question: http://stackoverflow.com/q/52397145
tags question: http://stackoverflow.com/q/52386379
tags question: http://stackoverflow.com/q/52420526
tags question: http://stackoverflow.com/q/52354104
tags question: http://stackoverflow.com/q/52339136
tags question: http://stackoverflow.com/q/52322715
tags question: http://stackoverflow.com/q/52417494
tags question: http://stackoverflow.com/q/52418782
tags question: http://stackoverflow.com/q/52292481
tags question: http://stackoverflow.com/q/52366891
tags question: http://stackoverflow.com/q/52418234
tags question: http://stackoverflow.com/q/52358406
tags question: http://stackoverflow.com/q/52389718
tags question: http://stackoverflow.com/q/52327186
tags question: http://stackoverflow.com/q/52343523
tags question: http://stackoverflow.com/q/52296306
tags question: http://stackoverflow.com/q/52332925
tags question: http://stackoverflow.com/q/52379309
tags question: http://stackoverflow.com/q/52321702
tags question: http://stackoverflow.com/q/52291445
tags question: http://stackoverflow.com/q/52288697
tags question: http://stackoverflow.com/q/52397283
tags question: http://stackoverflow.com/q/52420373
tags question: http://stackoverflow.com/q/52412717
tags question: http://stackoverflow.com/q/52373674

http://stackoverflow.com/q/52272552
has comment: http://stackoverflow.com/comment/91492889
linked to: http://stackoverflow.com/q/1175208
has comment: http://stackoverflow.com/comment/91493152
answer count: 1
has comment: http://stackoverflow.com/comment/91495519
has comment: http://stackoverflow.com/comment/91492706
favorite count: 0
has comment: http://stackoverflow.com/comment/91492627
has comment: http://stackoverflow.com/comment/91497567
has comment: http://stackoverflow.com/comment/91492269
has comment: http://stackoverflow.com/comment/91493041
has body: When I'm trying to load classes dynamically using getattr, I get a module class instead of my real class. module = importlib.import_module("bigpackage.animals") class_ = getattr(module, "dog_input") pprint(type(class_)) # Outputs &lt;class 'module'&gt; My dog_input class: from bigpackage.animals.animal import AbstractAnimal class DogInput(AbstractAnimal): def __init__(self): self.b = "bb" @property def name(self): prefix = super(DogInput, self).name return prefix + "Name" I have the following packages: bigpackage (package) animals (package) abstract_animal (class) dog_input (class) init init server (class where I (try to) load the classes dynamically
has comment: http://stackoverflow.com/comment/91496891
tagged with: python
has answer: http://stackoverflow.com/a/52272886
has comment: http://stackoverflow.com/comment/91492368
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91492325
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/91492361
upvote count: 1
has comment: http://stackoverflow.com/comment/91493027
has title: Getattr loads module instead of class
type: Question
has comment: http://stackoverflow.com/comment/91492391
score: -1
has comment: http://stackoverflow.com/comment/91493322
has comment: http://stackoverflow.com/comment/91492555

http://stackoverflow.com/comment/91614312
type: Comment
type: QuestionComment
has text: It is just the `posts` or any other url that gives the 404?
comment on: http://stackoverflow.com/q/52333370
score: 0

http://stackoverflow.com/a/52311803
has body: Your question is a bit unclear, as you define df twice (+1 in a comment), but if I understand correctly (that is: you already have 'DATE' in the .csv file) this may help: df = pd.read_csv('moving_average_calculation.csv', sep=',') df['Day'] = pd.DatetimeIndex(df['DATE']).day df['Month'] = pd.DatetimeIndex(df['DATE']).month df['Year'] = pd.DatetimeIndex(df['DATE']).year df.drop('DATE', axis=1, inplace=True) df = df'Day','Month','Year','Max_R','Total_R','Avg_R','MAX_T','TOTAL_T','AVG_T'
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52311611
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91570725
accepted answer of: http://stackoverflow.com/q/52311611

http://stackoverflow.com/q/52427999
score: 2
upvote count: 3
downvote count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91813243
has answer: http://stackoverflow.com/a/52428085
answer count: 1
linked to: http://stackoverflow.com/q/15562446
tagged with: flask
favorite count: 0
has title: Python Flask app not exiting with sys exit
duplicate of: http://stackoverflow.com/q/15562446
has body: I'd like to be able to terminate my flask app remotely with an http request like this: import flask import sys master = flask.Flask(__name__) @master.route('/shutdown') def shutdown(): #do things sys.exit() if __name__ == '__main__': master.run() Thing is it just doesn't work. From the terminal I get nothing, as if it's not even processing the request. I know that sys.exit() just raises a SystemExit, so I think it may be that it gets caught somewhere. The fact that os._exit(0) does work also leads me to think so. Am I tripping on something stupid? Is it actually a bug and there is a workaround? I'd prefer not to use os._exit(0) if possible. Thanks! Edit: I wouldn't say this question is a duplicate since the accepted answers differ and the other one is from '13 (Flask's gone a long way in the meantime)
has comment: http://stackoverflow.com/comment/91799350
tagged with: python
accepted answer: http://stackoverflow.com/a/52428085

http://stackoverflow.com/comment/91772003
has text: Never ever propose to use `load()` (read the documentation if you don't know why) when it is not necessary (almost always). Alwasy use `safe_load()` in examples.
comment on: http://stackoverflow.com/a/52412796
type: AnswerComment
type: Comment
score: 2

http://stackoverflow.com/comment/91579422
has text: @MJB: I have added detailed explanation of regex in my answer. Let me know which part is not clear and I will add more details.
score: 0
comment on: http://stackoverflow.com/a/52315889
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/91689290
type: QuestionComment
has text: You may use nltk, a module in python for NLP which gives you multiple functions to perform such task.
comment on: http://stackoverflow.com/q/52370113
score: 0
type: Comment

http://stackoverflow.com/q/52306827
has comment: http://stackoverflow.com/comment/91561511
has comment: http://stackoverflow.com/comment/91561611
has title: Parent and Child bullet in Python
has comment: http://stackoverflow.com/comment/91561365
has comment: http://stackoverflow.com/comment/91561157
upvote count: 1
has comment: http://stackoverflow.com/comment/91560846
answer count: 1
tagged with: python-docx
favorite count: 0
score: 0
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52307167
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91560866
has body: I have a document which contains the following sample text, This is a document which contains parent and child • Photosynthesis • CO~2~ in • H~2~0 in • Sunlight in • Glucose • CO~2~ in • C~6~H~12~O~6~ • Oxygen out How to separate those parent and child bullets in Python, I used python-docx import docx doc = docx.Document('bullet_test.docx') for p in doc.paragraphs: text = p.text.encode("utf-8").strip() style = p.style.name.strip() print style I am getting style as 'List Paragraph' and I can't able to get it as 'List Bullet' or 'List Bullet2' or 'List Number'
type: Question

http://stackoverflow.com/comment/91719288
score: 0
type: QuestionComment
type: Comment
has text: Are you able to use crispy form ? if yes i can answer you ...
comment on: http://stackoverflow.com/q/52387118

http://stackoverflow.com/q/52326258
favorite count: 0
tagged with: rouge
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47045436
has comment: http://stackoverflow.com/comment/91599788
has comment: http://stackoverflow.com/comment/91599758
tagged with: python
has answer: http://stackoverflow.com/a/54056863
has comment: http://stackoverflow.com/comment/91599680
has answer: http://stackoverflow.com/a/52326801
score: 1
has title: pyrouge: __init__() got an unexpected keyword argument 'n_words'
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52326439
answer count: 3
downvote count: 0
has body: i'm trying to install pyrouge, and i ran this code (following this repo) from pyrouge import Rouge155 from pprint import pprint ref_texts = {'A': "Poor nations pressurise developed countries into granting trade subsidies.", 'B': "Developed countries should be pressurized. Business exemptions to poor nations.", 'C': "World's poor decide to urge developed nations for business concessions."} summary_text = "Poor nations demand trade subsidies from developed nations." rouge = Rouge155(n_words=100) score = rouge.score_summary(summary_text, ref_texts) pprint(score) But i got some error, the traceback displayed as below: Traceback (most recent call last): File "&lt;ipython-input-116-94aea372ee05&gt;", line 1, in &lt;module&gt; runfile('C:/Users/cerdas/Documents/Bil/Lat/rouge.py', wdir='C:/Users/cerdas/Documents/Bil/Lat') File "C:\Users\cerdas\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\Users\cerdas\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/cerdas/Documents/Bil/Lat/rouge.py", line 10, in &lt;module&gt; rouge = Rouge155(n_words=100) TypeError: __init__() got an unexpected keyword argument 'n_words' and here the code of __init__.py from pyrouge.base import Doc, Sent from pyrouge.rouge import Rouge155 and the called function Rouge155 class Rouge155(object): def __init__(self, rouge_home=ROUGE_EVAL_HOME, n_words=None, stem=False, keep_files=False): self._stem = stem self._n_words = n_words self._discover_rouge(rouge_home) self._keep_files = keep_files

http://stackoverflow.com/comment/91768464
type: Comment
type: QuestionComment
has text: This is how it's in the .spec file that I recompiled
comment on: http://stackoverflow.com/q/52411630
score: 0

http://stackoverflow.com/comment/91514771
type: Comment
has text: Take a look, not sure if that was your goal but from our conversation that is what I put together
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52277166

http://stackoverflow.com/a/52378063
has body: subprocess.call() will block until the program called is complete. If you want the called program to run in parallel, it would be better to use something like subprocess.Popen()
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52378007
downvote count: 0
answers question: http://stackoverflow.com/q/52378007
score: 1

http://stackoverflow.com/q/52406732
has answer: http://stackoverflow.com/a/52407333
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/13411544
tagged with: geojson
type: Question
has comment: http://stackoverflow.com/comment/91757333
possible better answer: http://stackoverflow.com/a/52407333
has comment: http://stackoverflow.com/comment/91759320
has answer: http://stackoverflow.com/a/52407042
has comment: http://stackoverflow.com/comment/91758165
has title: How to eliminate first column from 'pandas.core.frame.DataFrame'
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91757241
linked to: http://stackoverflow.com/q/20107570
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/91757596
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52407042
tagged with: python
has body: I have code which is giving output in below format. How should i remove the first column and can store the elements of second row in list ? type of the output is in 'pandas.core.frame.DataFrame' format speed lat lng 1 19.130506 12.616756 7.460664 2 63.595894 52.616838 7.460691 3 40.740044 72.616913 7.460718 4 22.227747 82.616993 7.460734 5 68.058223 12.617062 7.460758
has comment: http://stackoverflow.com/comment/91758072
has comment: http://stackoverflow.com/comment/91757319
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91757442

http://stackoverflow.com/q/52293389
accepted answer: http://stackoverflow.com/a/52360597
tagged with: python
has body: How can we collect tweets using tweepy in json format and save to local disk. I need to input the json file in Solr for indexing and tokenization. here is the code i am using: ` import json import tweepy from tweepy import OAuthHandler ckey="" csecret="" atoken="" asecret="" auth = OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) api = tweepy.API(auth) data1 = api.search(q='politics', count = 1)`
tagged with: tweepy
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/91535866
tagged with: information-retrieval
type: Question
has answer: http://stackoverflow.com/a/52360597
score: 0
tagged with: rest
has comment: http://stackoverflow.com/comment/91534793
has title: Saving tweets using tweepy in json format
answer count: 1

http://stackoverflow.com/q/52335593
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/52335729
tagged with: python
type: AnsweredQuestion
upvote count: 2
downvote count: 1
has body: I have a CSV file that looks like this: Date,Time,Mood,Tags,Medications,Notes "Jul 25, 2018",9:41 PM,8,,,"", "Jul 26, 2018",10:05 AM,4,,,"", "Jul 26, 2018",12:00 PM,3,,,"", "Jul 26, 2018",7:00 PM,8,,,"", "Jul 27, 2018",12:01 PM,8,,,"", I run the following code: import pandas as pd df = pd.read_csv("./data/MoodLog_2018_09_14.csv", dtype={'Date': str, 'Time': str, 'Mood': str, 'Tags': str, 'Medications': str, 'Notes': str}) print(df['Time'].head(5)) and it prints the following: Jul 25, 2018 8 Jul 26, 2018 4 Jul 26, 2018 3 Jul 26, 2018 8 Jul 27, 2018 8 Name: Time, dtype: object It's including the Mood column in the Time column. Why is that?
type: Question
tagged with: pandas
answer count: 1
score: 1
has answer: http://stackoverflow.com/a/52335729
favorite count: 0
has title: pd.read_csv parsing incorrectly

http://stackoverflow.com/comment/91668556
comment on: http://stackoverflow.com/a/52362216
score: 0
has text: this flattens it too. It has to be more like `res = [[int(j) for j in ast.literal_eval(i)] for i in lst]`
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52356369
downvote count: 1
tagged with: ode
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91658882
score: -1
type: Question
has title: python two coupled second order ODEs Runge Kutta 4th order
answer count: 1
has comment: http://stackoverflow.com/comment/91658262
favorite count: 0
has comment: http://stackoverflow.com/comment/91676317
accepted answer: http://stackoverflow.com/a/52389077
has comment: http://stackoverflow.com/comment/91660135
tagged with: python
tagged with: runge-kutta
has answer: http://stackoverflow.com/a/52389077
upvote count: 0
has comment: http://stackoverflow.com/comment/91660111
has body: I am a beginner in python. I have a problem with 2 ODEs that are second order and they are coupled. I want to solve it with Runge Kutta 4th order. I have made 2 matrices.[A] and [B] that V' = A*C + B . But I couldn't get the answer. Can anyone help me? This is equations Equations this is my code: import numpy as np from math import sqrt from sympy import * import matplotlib.pyplot as plt x,v1, v2, v3, v4, dv1, dv2, dv3, dv4, t = symbols('x v1 v2 v3 v4 dv1 dv2 dv3 dv4 t') # Parameters mr = m = c = k = F = # Equations: A = Matrix([[0, 0, 1, 0], [0, 0, 0, 1], [-k / mr, k / mr, -c / mr, c / mr], [k / m, -k / m, c / m, -c / m]]) B = Matrix([0, 0, 0, -F]) dv1 = diff(v1, t) dv2 = diff(v2, t) dv3 = diff(v3, t) dv4 = diff(v4, t) C = Matrix([v1,v2,v3,v4]) def V(v1,v2,v3,v4,t): V = A*C+B return V def rk4(f, v1, v2, v3 ,v4 , x0 , x1 , n): k11 = [0] * (n + 1) k21 = [0] * (n + 1) k31 = [0] * (n + 1) k41 = [0] * (n + 1) k12 = [0] * (n + 1) k22 = [0] * (n + 1) k32 = [0] * (n + 1) k42 = [0] * (n + 1) k13 = [0] * (n + 1) k23 = [0] * (n + 1) k33 = [0] * (n + 1) k43 = [0] * (n + 1) k14 = [0] * (n + 1) k24 = [0] * (n + 1) k34 = [0] * (n + 1) k44 = [0] * (n + 1) h = (x1 - x0) / n for i in range(1, n + 1): k11 = h * f(v1, v2, v3, v4, t) k21 = h * f(v1, v2, v3, v4, t) k31 = h * f(v1, v2, v3, v4, t) k41 = h * f(v1, v2, v3, v4, t) k12 = h * f(v1 + 0.5 * h, v2 + 0.5 * h, v3 + 0.5 * h, v4 + 0.5 * h, t + 0.5 * k11) k22 = h * f(v1 + 0.5 * h, v2 + 0.5 * h, v3 + 0.5 * h, v4 + 0.5 * h, t + 0.5 * k21) k32 = h * f(v1 + 0.5 * h, v2 + 0.5 * h, v3 + 0.5 * h, v4 + 0.5 * h, t + 0.5 * k31) k42 = h * f(v1 + 0.5 * h, v2 + 0.5 * h, v3 + 0.5 * h, v4 + 0.5 * h, t + 0.5 * k41) k13 = h * f(v1 + 0.5 * h, v2 + 0.5 * h, v3 + 0.5 * h, v4 + 0.5 * h, t + 0.5 * k12) k23 = h * f(v1 + 0.5 * h, v2 + 0.5 * h, v3 + 0.5 * h, v4 + 0.5 * h, t + 0.5 * k22) k33 = h * f(v1 + 0.5 * h, v2 + 0.5 * h, v3 + 0.5 * h, v4 + 0.5 * h, t + 0.5 * k32) k43 = h * f(v1 + 0.5 * h, v2 + 0.5 * h, v3 + 0.5 * h, v4 + 0.5 * h, t + 0.5 * k42) k14 = h *…

http://stackoverflow.com/a/52393141
type: Answer
has comment: http://stackoverflow.com/comment/91739358
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52392637
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52392637
has body: The best thing you can do is stop creating new widgets on every &lt;Configure&gt; event. Create them once, then move them only when you've computed that they need to move. When I resize the main window just wide enough to create a single row, your code will have created anywhere from 200 to 2000 buttons or more depending on how fast I do the resize. An alternate solution You might want to consider using grid rather than pack, since grid doesn't require that you create internal frames for each row. Here's a quick and dirty example to illustrate the concept. It hasn't been tested much, but it seems to work: import tkinter as tk import tkinter.ttk as ttk class FrameButtons(ttk.Frame): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.buttons = [] self.bind("&lt;Configure&gt;", self._redraw) def _redraw(self, event=None): maxwidth = self.winfo_width() row = column = rowwidth = 0 for button in self.buttons: # will it fit? If not, move to the next row if rowwidth + button.winfo_width() &gt; maxwidth: row += 1 column = 0 rowwidth = 0 rowwidth += button.winfo_width() button.grid(row=row, column=column) column += 1 def add_button(self, *args, **kwargs): '''Add one button to the frame''' button = ttk.Button(self, *args, **kwargs) self.buttons.append(button) self._redraw() if __name__ == "__main__": root = tk.Tk() button_frame = FrameButtons(root) button_frame.pack(side="top", fill="x", expand=False) for i in range(20): button_frame.add_button(text=str(i)) root.mainloop()

http://stackoverflow.com/comment/91781344
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52419117
has text: Tip : Never mix 4 spaces and 8 spaces indentation.
score: 0

http://stackoverflow.com/comment/91743762
type: Comment
type: QuestionComment
has text: This code is working good in Django shell
comment on: http://stackoverflow.com/q/52398066
score: 0

http://stackoverflow.com/a/52350715
answers question: http://stackoverflow.com/q/52337608
has comment: http://stackoverflow.com/comment/91657438
accepted answer of: http://stackoverflow.com/q/52337608
has body: See @dirkgroten's as to why the question produces the error. Read on for an alternate method that solves the issue. The reason why @dirkgroten's answer wouldn't work is that the model definition for Event doesn't include a value signups. However, since the ManyToMany relationship is defined on the Signup model, I can get the prefetch_related to work off of the Signup query, as we see below. signups = Signup.objects.filter( tournament_id=tournament_id ).prefetch_related( 'event', ... ) context['signups'] = signups context['events'] = signups.values('event', 'event__name', ...).distinct().order_by('event__name') (Note that order_by is required in order for distinct to work and that values() returns a dict, not a queryset.)
type: Answer
has comment: http://stackoverflow.com/comment/91657966
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91656925
has comment: http://stackoverflow.com/comment/91657280
has comment: http://stackoverflow.com/comment/91650787
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91658177

http://stackoverflow.com/comment/91692818
type: QuestionComment
has text: Is `center_crop` independent from the `i` and `j` ?
comment on: http://stackoverflow.com/q/52373938
score: 0
type: Comment

http://stackoverflow.com/q/52297527
type: Question
tagged with: google-cloud-datastore
tagged with: google-cloud-platform
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/91559060
has title: Performance after Period of inactivity
favorite count: 0
has answer: http://stackoverflow.com/a/52306357
type: UnansweredQuestion
tagged with: google-app-engine
has comment: http://stackoverflow.com/comment/91550649
tagged with: python
has comment: http://stackoverflow.com/comment/91575023
has body: We have a Google App Engine Service developed. There are two controllers which pull from google datastore however after a lull generally 6:30 AM local Eastern time (services are in us-central) the first pull on these controllers generally results in 30 second latency. Our current thought is to create a scheduled task to keep these services "hot" Is this an appropriate way of thinking or is better to look elsewhere?
downvote count: 0
score: 1

http://stackoverflow.com/a/52393822
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52393659
has body: You can also use a lambda function: df['newCol'] = df.apply(lambda x: int(x['v0'] in x.values[2:]), axis=1) id v0 v1 v2 v3 v4 newCol 0 1 10 5 10 22 50 1 1 2 22 23 55 60 50 0 2 3 8 2 40 80 110 0 3 4 15 15 25 100 101 1
type: Answer
score: 2

http://stackoverflow.com/a/52346726
upvote count: 14
has comment: http://stackoverflow.com/comment/118587000
downvote count: 2
answers question: http://stackoverflow.com/q/52346725
has comment: http://stackoverflow.com/comment/113154446
accepted answer of: http://stackoverflow.com/q/52346725
has body: Yes. Subclass the TransformerMixin and build a custom transformer. Here is an extension to one of the existing outlier detection methods: from sklearn.pipeline import Pipeline, TransformerMixin from sklearn.neighbors import LocalOutlierFactor class OutlierExtractor(TransformerMixin): def __init__(self, **kwargs): """ Create a transformer to remove outliers. A threshold is set for selection criteria, and further arguments are passed to the LocalOutlierFactor class Keyword Args: neg_conf_val (float): The threshold for excluding samples with a lower negative outlier factor. Returns: object: to be used as a transformer method as part of Pipeline() """ self.threshold = kwargs.pop('neg_conf_val', -10.0) self.kwargs = kwargs def transform(self, X, y): """ Uses LocalOutlierFactor class to subselect data based on some threshold Returns: ndarray: subsampled data Notes: X should be of shape (n_samples, n_features) """ X = np.asarray(X) y = np.asarray(y) lcf = LocalOutlierFactor(**self.kwargs) lcf.fit(X) return (X[lcf.negative_outlier_factor_ &gt; self.threshold, :], y[lcf.negative_outlier_factor_ &gt; self.threshold]) def fit(self, *args, **kwargs): return self Then create a pipeline as: pipe = Pipeline([('outliers', OutlierExtraction()), ...])
score: 12
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/116774032
has comment: http://stackoverflow.com/comment/91673611
type: Answer

http://stackoverflow.com/comment/91713614
comment on: http://stackoverflow.com/a/52371589
type: Comment
type: AnswerComment
has text: @John Well `$lookup` performs left join So it will only be productive if there is a `$match` condition at the starting of the pipeline which you don't have. So it is better to use three queries instead.
score: 0

http://stackoverflow.com/comment/91962947
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52408404
has text: Yep, question is still relevant as I could not get the code working as suggested in that article in medium. I haven't received any resolution from the author yet. BTW, as mentioned in my earlier comment, I am in between setting-up my new laptop and hence unable to share full stack trace. give me a day or two for the same.
type: Comment

http://stackoverflow.com/comment/91562136
score: 0
type: Comment
type: QuestionComment
has text: @ReblochonMasque That is not a set of orthogonal polygon points.
comment on: http://stackoverflow.com/q/52306377

http://stackoverflow.com/a/59112442
type: Answer
has comment: http://stackoverflow.com/comment/128810916
answers question: http://stackoverflow.com/q/52381091
downvote count: 1
score: 3
upvote count: 4
has body: I just ran into this issue using shelve in a small module for caching exchange rates. You can solve the issue with python threading and a global threading.Lock() object. from threading import Lock import shelve mutex = Lock() mutex.acquire() db = shelve.open(db_name) # write to db db.close() mutex.release() the original source for the code snippet and credit for the idea can be found @ http://georg.io/2014/06/Python-Shelve-Thread-Safety The ```threading.Lock()`` object works by blocking the other python threads until it's released. see https://docs.python.org/2/library/threading.html#lock-objects

http://stackoverflow.com/q/52374941
has comment: http://stackoverflow.com/comment/91694866
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/52375211
has title: Error when access Json Data from Php file
type: Question
has comment: http://stackoverflow.com/comment/91694966
possible better answer: http://stackoverflow.com/a/52375211
has answer: http://stackoverflow.com/a/52375122
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91695291
has comment: http://stackoverflow.com/comment/91694923
accepted answer: http://stackoverflow.com/a/52375122
has body: i have a Json Data that i can access from my own api But the Json Data is not in a .json file its in Php file (like in the link below) now i want to use Python to print the Data import json from urllib.request import urlopen with urlopen("https://**********.000webhostapp.com/api/value/read_all.php") as response: source = response.read() data = source for item in data['value']['temp']: print(item) This the python Script i use this is the main Error : for item in data['value']['temp']: TypeError: byte indices must be integers or slices, not str The JSON looks like: {"value":[{"id":"1","temp":"25.60","water":"80%","total":"5L","percent":"50%"}...
tagged with: python
has comment: http://stackoverflow.com/comment/91694804

http://stackoverflow.com/comment/91557047
type: Comment
type: QuestionComment
has text: What is the larger picture here? What are you trying to achieve with these large numbers?
comment on: http://stackoverflow.com/q/52303407
score: 0

http://stackoverflow.com/a/58966051
upvote count: 1
has body: @Vorticity has the right fix. Just remove the leading "^" in your additional_lookup regex as follows: 'additional_lookup': { 'url': 'regex("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$")', 'field': 'email' } You should be able to retrieve your item with or without url encoding eg: localhost:5000/user_creds/someemail@gmail.com localhost:5000/user_creds/someemail%40gmail.com If you have any interest in making your items retrievable at the item level by email only (not object id), you can use item_lookup_field together with item_url: 'user_creds': { ... 'item_url': 'regex("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$")', 'item_lookup_field': 'email' }
answers question: http://stackoverflow.com/q/52306826
score: 1
accepted answer of: http://stackoverflow.com/q/52306826
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/52354246
favorite count: 0
tagged with: python
downvote count: 1
type: AnsweredQuestion
has title: Add multiple dataframes based on one column
has answer: http://stackoverflow.com/a/52354573
accepted answer: http://stackoverflow.com/a/52354573
has comment: http://stackoverflow.com/comment/91655728
has answer: http://stackoverflow.com/a/52356484
possible better answer: http://stackoverflow.com/a/52354449
tagged with: average
has comment: http://stackoverflow.com/comment/91653764
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/91653699
has body: I have several hundred dataframes with same column names, like this: df1 wave num stlines fwhm EWs MeasredWave 0 4050.32 3 0.28269 0.07365 22.16080 4050.311360 1 4208.98 5 0.48122 0.08765 44.90035 4208.972962 2 4374.94 9 0.71483 0.11429 86.96497 4374.927110 3 4379.74 9 0.31404 0.09107 30.44271 4379.760601 4 4398.01 14 0.50415 0.09845 52.83236 4398.007473 5 5520.50 1 0.06148 0.12556 8.21685 5520.484742 df2 wave num stlines fwhm EWs MeasredWave 0 4050.32 3 0.28616 0.07521 22.91064 4050.327388 1 4208.98 6 0.48781 0.08573 44.51609 4208.990029 2 4374.94 9 0.71548 0.11437 87.10152 4374.944513 3 4379.74 10 0.31338 0.09098 30.34791 4379.778009 4 4398.01 15 0.49950 0.08612 45.78707 4398.020367 5 4502.21 9 0.56362 0.10114 60.67868 4502.223123 6 4508.28 3 0.69554 0.11600 85.88428 4508.291777 7 4512.99 2 0.20486 0.08891 19.38745 4512.999332 8 5520.50 1 0.06148 0.12556 8.21685 5520.484742 That's how i0'm reading them path_to_files = '/home/Desktop/computed_2d/' lst = [] for filen in dir1: df = pd.read_table(path_to_files+filen, skiprows=0, usecols=(0,1,2,3,4,8),names=['wave','num','stlines','fwhm','EWs','MeasredWave'],delimiter=r'\s+') lst.append(df) The desired result should look like this: wave num stlines fwhm EWs MeasredWave 0 4050.32 3.0 0.284425 0.074430 22.535720 4050.319374 1 4208.98 5.5 0.484515 0.086690 44.708220 4208.981496 2 4374.94 9.0 0.715155 0.114330 87.033245 4374.935812 3 4379.74 9.5 0.313710 0.091025 30.395310 4379.769305 4 4398.01 14.5 0.501825 0.092285 49.309715 4398.013920 5 4502.21 9 0.56362 0.10114 60.67868 4502.223123 6 4508.28 3 0.69554 0.11600 85.88428 4508.291777 7 4512.99 2 0.20486 0.08891 19.38745 4512.999332 8 5520.50 1.0 0.061480 0.125560 8.216850 5520.484742 As you can see the number of rows are not same. Now i want to take the average of all the dataframes based on column1 wave and i want to make sure that the each index of column wave of df1 gets added to the correct index of df2
has comment: http://stackoverflow.com/comment/91655034
has comment: http://stackoverflow.com/comment/91653654
tagged with: dataframe
score: -1
has comment: http://stackoverflow.com/comment/91653382
has comment: http://stackoverflow.com/comment/91653737
has comment: http://stackoverflow.com/comment/91653525
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/91654169
has answer: http://stackoverflow.com/a/52354449

http://stackoverflow.com/q/52370902
has answer: http://stackoverflow.com/a/52370990
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52371189
score: -1
type: Question
answer count: 2
has title: Splitting a string based on semi-consistent features
favorite count: 0
has answer: http://stackoverflow.com/a/52371189
accepted answer: http://stackoverflow.com/a/52370990
has body: I have a text file that represents a transcript. I need to find a way to split this so that I have a list of strings representing what each person said. So this; mystr = '''Bob: Hello there, how are you? Alice: I am fine how are you?''' Becomes this; mylist= ['Bob: Hello there, how are you?','Alice: I am fine how are you?'] I am new to regular expressions but recognize that this could be the way to go. The problem is I want to iterate this over many transcripts in circumstances where the names will differ (e.g. John, Paul, George, Ringo and so on). What will be consistent is the presence of a word (representing the speaker), followed by a colon, followed by a white-space.
downvote count: 1
tagged with: regex
upvote count: 0

http://stackoverflow.com/q/52399017
type: Question
has comment: http://stackoverflow.com/comment/91744220
has comment: http://stackoverflow.com/comment/91744086
downvote count: 0
has title: How to convert to bytes format for PIL images which is similar to normal bytes format
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91743622
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52399668
has comment: http://stackoverflow.com/comment/91743965
tagged with: python
has body: Sorry that I couldnt explain clearly in subject. I used read() to read the entire image in the form of bytes and also I used PIL's tobytes() to read the same image. But to me the image bytes looks different. Could you please advice on how to have the same bytes generated using read() using PIL's package utility? From raw encoding to utf-8 Code sample: path3 = r'path' with io.open(path3, 'rb') as image_file: content1 = image_file.read() b'\xff\xd8\x ... Using PIL: with io.open(path3, 'rb') as image_file: content1 = Image.open(image_file).tobytes() b'\xbf\x91\xc0\xbf\x91\xc0\xbe\x90\xbf\xbe' In my use case: from pdf2image import convert_from_bytes images = convert_from_bytes(open('pp.pdf', 'rb').read()) b=images[0].read() # since this returns list format AttributeError: 'PpmImageFile' object has no attribute 'read' Is it possible to have same byte format like read()?
score: 1
tagged with: image-processing
upvote count: 1

http://stackoverflow.com/comment/91653062
type: Comment
type: QuestionComment
has text: Also see http://sscce.org/
comment on: http://stackoverflow.com/q/52349790
score: 0

http://stackoverflow.com/a/76056312
has body: It is possible to extend this to an arbitrary number of arguments of different types. For that, you must check for each positional argument and keyword argument if it is of type numpy array and convert them to tuples. The other arguments you don't touch. Before your function is called, you convert all tuples in the positional arguments and keywords arguments back to numpy arrays. from typing import Callable import numpy as np from functools import cache, wraps def np_cache(function): @cache def cached_wrapper(*args, **kwargs): args = [np.array(a) if isinstance(a, tuple) else a for a in args] kwargs = { k: np.array(v) if isinstance(v, tuple) else v for k, v in kwargs.items() } return function(*args, **kwargs) @wraps(function) def wrapper(*args, **kwargs): args = [tuple(a) if isinstance(a, np.ndarray) else a for a in args] kwargs = { k: tuple(v) if isinstance(v, np.ndarray) else v for k, v in kwargs.items() } return cached_wrapper(*args, **kwargs) wrapper.cache_info = cached_wrapper.cache_info wrapper.cache_clear = cached_wrapper.cache_clear return wrapper
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/52331944
downvote count: 0
score: 3

http://stackoverflow.com/comment/91666519
comment on: http://stackoverflow.com/q/52361059
has text: I tested it, but java -version also does not work.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91528018
type: Comment
type: QuestionComment
score: 1
has text: Have you tried printing your image before rotating it? `img = img.rotate(40)` statement might be the reason behind this.
comment on: http://stackoverflow.com/q/52287894

http://stackoverflow.com/comment/110216975
comment on: http://stackoverflow.com/a/57466875
score: 0
type: AnswerComment
has text: Hi Santana, I checked with the zip code 02222. Seems like the latitude and longitudes are not present corresponding to this zip in the uszipcode library. If you'll just print various variables, zip1, zip2 ,lat and long, etc. you'll be able to see the info available. I checked the zip code online and found the lat and long,,,and using the values it works fine. uszipcode might not have exhaustive info of all zip codes and you may search if there is any other library available. Hope this helps....
type: Comment

http://stackoverflow.com/q/52402758
has comment: http://stackoverflow.com/comment/91749307
downvote count: 0
has title: Is there a drawback to using an inplace function within map/filter?
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91749361
has body: Is there any drawback to using a function like map to apply an inplace function to a list? For example, could the fact that the map function produces an output be "harmful/negative"? My understanding is that map is slightly more efficient than a for loop. See the following two methods to achieve the same result: lists = [[1,2,3], [4,5,6], [7,8,9]] map(lambda l: l.sort(), lists) vs. lists = [[1,2,3], [4,5,6], [7,8,9]] for l in lists: l.sort() The question is just to satisfy my curiosity and to understand better how python works. It is not to discuss which method is cleaner or more pythonic.
tagged with: python
favorite count: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
upvote count: 1
linked to: http://stackoverflow.com/q/39023423
score: 1
type: Question
duplicate of: http://stackoverflow.com/q/39023423

anaconda
tags question: http://stackoverflow.com/q/52293956
tags question: http://stackoverflow.com/q/52294939
tags question: http://stackoverflow.com/q/52346652
tags question: http://stackoverflow.com/q/52327284
tags question: http://stackoverflow.com/q/52361110
type: Tag
tags question: http://stackoverflow.com/q/52376025
tags question: http://stackoverflow.com/q/52424811
tags question: http://stackoverflow.com/q/52352302
tags question: http://stackoverflow.com/q/52414943
tags question: http://stackoverflow.com/q/52403414
tags question: http://stackoverflow.com/q/52287152
tags question: http://stackoverflow.com/q/52297593
tags question: http://stackoverflow.com/q/52378427
tags question: http://stackoverflow.com/q/52341855
tags question: http://stackoverflow.com/q/52424172
tags question: http://stackoverflow.com/q/52377159
tags question: http://stackoverflow.com/q/52412901
tags question: http://stackoverflow.com/q/52284072
tags question: http://stackoverflow.com/q/52410484
tags question: http://stackoverflow.com/q/52300265
tags question: http://stackoverflow.com/q/52425060
tags question: http://stackoverflow.com/q/52301956
tag name: anaconda
tags question: http://stackoverflow.com/q/52302072
tags question: http://stackoverflow.com/q/52287117
tags question: http://stackoverflow.com/q/52362389
tags question: http://stackoverflow.com/q/52385957
tags question: http://stackoverflow.com/q/52376313
tags question: http://stackoverflow.com/q/52306340
tags question: http://stackoverflow.com/q/52375466
tags question: http://stackoverflow.com/q/52300930
tags question: http://stackoverflow.com/q/52299781
tags question: http://stackoverflow.com/q/52429305
tags question: http://stackoverflow.com/q/52375243
tags question: http://stackoverflow.com/q/52372425
tags question: http://stackoverflow.com/q/52426408
tags question: http://stackoverflow.com/q/52375485
tags question: http://stackoverflow.com/q/52340758
tags question: http://stackoverflow.com/q/52330667
tags question: http://stackoverflow.com/q/52377462
tags question: http://stackoverflow.com/q/52334135

http://stackoverflow.com/q/52309134
has comment: http://stackoverflow.com/comment/91566280
type: Question
tagged with: python-imaging-library
has title: Drawing Text on Images
tagged with: image
has comment: http://stackoverflow.com/comment/91566075
score: 0
has body: I am a beginnner in OpenCV and while using Face API i'd like to draw rectangles around it and print text on it(age,gender). How exactly could I do this? I have attached my code below. import requests # If you are using a Jupyter notebook, uncomment the following line. #%matplotlib inline import matplotlib.pyplot as plt from PIL import Image from io import BytesIO # Replace &lt;Subscription Key&gt; with your valid subscription key. subscription_key = "1ed933c3d81f4b5d8b998c81f3f48cf8" assert subscription_key # You must use the same region in your REST call as you used to get your # subscription keys. For example, if you got your subscription keys from # westus, replace "westcentralus" in the URI below with "westus". # # Free trial subscription keys are generated in the westcentralus region. # If you use a free trial subscription key, you shouldn't need to change # this region. vision_base_url = "https://japaneast.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&amp;returnFaceLandmarks=false" analyze_url = vision_base_url + "analyze" # Set image_path to the local path of an image that you want to analyze. image_path = "image.jpg" # Read the image into a byte array image_data = open(image_path, "rb").read() headers = {'Ocp-Apim-Subscription-Key': subscription_key, 'Content-Type': 'application/octet-stream'} params = { 'returnFaceId': 'true', 'returnFaceLandmarks': 'false', 'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,' + 'emotion,hair,makeup,occlusion,accessories,blur,exposure,noise' } response = requests.post( analyze_url, headers=headers, params=params, data=image_data) response.raise_for_status() # The 'analysis' object contains various fields that describe the image. The most # relevant caption for the image is obtained from the 'description' property. analysis = response.json() print(analysis) # image_caption = analysis["description"]["captions"][0]["text"].capitalize() # Display the image and overlay it with the caption. ima…
type: UnansweredQuestion
tagged with: python
answer count: 0

http://stackoverflow.com/comment/91681162
score: 0
has text: Not really, my code in the question above is exactly what my code file has. That's odd...it's like it skips a line and then prints the result every time.
type: Comment
comment on: http://stackoverflow.com/a/52368126
type: AnswerComment

http://stackoverflow.com/comment/91740542
type: AnswerComment
has text: Yes all the Group have different names.
comment on: http://stackoverflow.com/a/52386222
type: Comment
score: 0

http://stackoverflow.com/comment/101452895
score: 0
type: Comment
type: QuestionComment
has text: hi, @Wallace can you share any references how you achieved your goal programmatically with adobe redact?
comment on: http://stackoverflow.com/q/52346942

http://stackoverflow.com/comment/91692910
comment on: http://stackoverflow.com/q/52373938
score: 0
type: QuestionComment
type: Comment
has text: Does `center_crop()` take `img` as a parameter or anything?

http://stackoverflow.com/comment/91593687
has text: I think you could work around it by registering a callback for the `missing-reference` event. When I tried my handler was getting called after intersphinx's handler for the same event had processed it, and it modifies `node['reftarget']` in-place to remove the colon and the part before it so that information is lost.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52305692
score: 0

http://stackoverflow.com/a/52411063
accepted answer of: http://stackoverflow.com/q/52403235
type: AcceptedAnswer
downvote count: 0
score: 8
has comment: http://stackoverflow.com/comment/110439762
upvote count: 8
type: Answer
answers question: http://stackoverflow.com/q/52403235
has body: import numpy as np np.unique(list1+list2) # keeps only non dublicates this is also keeps the order incase that was a priority

http://stackoverflow.com/comment/91685989
comment on: http://stackoverflow.com/a/52367957
score: 0
type: AnswerComment
type: Comment
has text: Thanks! I overlooked that.

http://stackoverflow.com/comment/91607861
comment on: http://stackoverflow.com/q/52330444
score: 0
type: Comment
has text: @VineethSai %%writefile filename is a Jupyter notebook magic alias for writing contents of a cell to a file. In this case, the first block of code gets written to **mainss_script.py** when the cell containing those code was run. She is having trouble importing the file because the file does not exist or is not in a place known to the interpreter.
type: QuestionComment

http://stackoverflow.com/a/52312293
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52305911
accepted answer of: http://stackoverflow.com/q/52305911
has body: The first index is not needed, if you have the second index. It is important both that the columns be the same and that they be in the same order. The columns in the first index are the same as the initial columns in the second index, so the first is not necessary. Further, it is not really desirable. Each index incurs overhead (both space and time) when data changes. So, you should just stick with the second index.
type: AcceptedAnswer
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/91555193
type: Comment
type: QuestionComment
has text: .. What's `pm`?
score: 0
comment on: http://stackoverflow.com/q/52303258

http://stackoverflow.com/q/52323642
tagged with: python
has answer: http://stackoverflow.com/a/52323680
possible better answer: http://stackoverflow.com/a/52323667
type: AnsweredQuestion
has title: looping over list and delete items in for loop
has answer: http://stackoverflow.com/a/52323667
upvote count: 1
downvote count: 1
type: Question
has body: I have list which has more than 1000 elements and i have a page where i must add those elements from the list but the thing is the page only accepts 40 entries at a time. so what i am tring to do is grab 40 elements from the list then submit those elements to the page using for loop then delete these elements from the list and grab 40 elements again, i need to do this till all the elements from the list are submitted to the page. this is what i have done so far and failed mylist1 = ['1','2','3','4','5','6','7','8','9','10','10','11',] def listget(): newlistget = [x for x in mylist1] return newlistget while True: for x in listget(): for i in range(0,40): #do stuff mylist1.remove(mylist1[i]) if not listget(): break
has answer: http://stackoverflow.com/a/52323939
tagged with: python-2.7
score: 0
answer count: 3
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52323939

http://stackoverflow.com/a/52417633
has comment: http://stackoverflow.com/comment/91807501
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52408958
downvote count: 0
has body: you need np.repeat and df.stack() out_df=pd.DataFrame(columns=df.columns) out_df['Machine']=np.repeat(df['Machine'].values,repeats=len(df['Application'].str.split(';')),axis=0) out_df['Vulnerability']=np.repeat(df['Vulnerability'].values,repeats=len(df['Application'].str.split(';')),axis=0) out_df['Application']=df['Application'].str.split(';',expand=True).stack().values print(out_df) Machine Vulnerability Application 0 1 vuln1 App1 1 1 vuln1 App2 2 1 vuln1 App3 3 1 vuln2 App1 4 1 vuln2 App2 5 1 vuln2 App3 6 1 vuln3 App1 7 1 vuln3 App2 8 1 vuln3 App3
type: Answer

http://stackoverflow.com/a/52296359
has comment: http://stackoverflow.com/comment/91541893
score: 3
has comment: http://stackoverflow.com/comment/91566464
has comment: http://stackoverflow.com/comment/91541966
has comment: http://stackoverflow.com/comment/91543100
type: AcceptedAnswer
downvote count: 0
has body: You are mixing Python syntax into your SQL query. SQL is parsed and executed by the database, not by Python, and the database knows nothing about datetime.datetime.now() or datetime.date() or timedelta()! The specific error you see is caused by your Python code being interpreted as SQL instead and as SQL, datetime.datetime.now references the now column of the datetime table in the datetime database, which is a cross-database reference, and psycopg2 doesn't support queries that involve multiple databases. Instead, use SQL parameters to pass in values from Python to the database. Use placeholders in the SQL to show the database driver where the values should go: params = { # all rows after this timestamp, 7 days ago relative to 'now' 'earliest': datetime.datetime.now() - datetime.timedelta(days=7), # if you must have a date *only* (no time component), use # 'earliest': datetime.date.today() - datetime.timedelta(days=7), } df = pd.read_sql(""" select store_name,count(*) from sales where created_at &gt;= %(latest)s""", params=params, con=con) This uses placeholders as defined by the psycopg2 parameters documentation, where %(latest)s refers to the latest key in the params dictionary. datetime.datetime() instances are directly supported by the driver. Note that I also fixed your 7 days ago expression, and replaced your BETWEEN syntax with &gt;=; without a second date you are not querying for values between two dates, so use &gt;= to limit the column to dates at or after the given date.
answers question: http://stackoverflow.com/q/52296014
has comment: http://stackoverflow.com/comment/91546880
type: Answer
accepted answer of: http://stackoverflow.com/q/52296014
has comment: http://stackoverflow.com/comment/91541221
has comment: http://stackoverflow.com/comment/91550348
upvote count: 3

http://stackoverflow.com/q/52312606
type: Question
has title: from where SSL ConnectionResetError comes from?
has body: TL;DR My question is simple - where is the code responsible to raise ConnectionResetError on cpython3 following a call to self._sslobj.read(len, buffer) on ssl.py? Background I'm getting sometimes ConnectionResetError when trying to connect to S3 with ssl. this error occurs rarely so its tricky to reproduce it. # trimmed stacktrace File "/MYPROJECT/MY_FUNC.py", line 123, in &lt;genexpr&gt; rows = (row for row in reader) File "/XXX/lib/python3.6/csv.py", line 112, in _next_ row = next(self.reader) File "/XXX/lib/python3.6/tarfile.py", line 706, in readinto buf = self.read(len(b)) File "/XXX/lib/python3.6/tarfile.py", line 695, in read b = self.fileobj.read(length) File "/XXX/lib/python3.6/gzip.py", line 276, in read return self._buffer.read(size) File "/XXX/lib/python3.6/_compression.py", line 68, in readinto data = self.read(len(byte_view)) File "/XXX/lib/python3.6/gzip.py", line 469, in read buf = self._fp.read(io.DEFAULT_BUFFER_SIZE) File "/XXX/lib/python3.6/gzip.py", line 91, in read self.file.read(size-self._length+read) File "/XXX/lib/python3.6/site-packages/s3fs/core.py", line 1311, in read self._fetch(self.loc, self.loc + length) File "/XXX/lib/python3.6/site-packages/s3fs/core.py", line 1292, in _fetch req_kw=self.s3.req_kw) File "/XXX/lib/python3.6/site-packages/s3fs/core.py", line 1496, in _fetch_range return resp['Body'].read() File "/XXX/lib/python3.6/site-packages/botocore/response.py", line 74, in read chunk = self._raw_stream.read(amt) File "/XXX/lib/python3.6/site-packages/botocore/vendored/requests/packages/urllib3/response.py", line 239, in read data = self._fp.read() File "/XXX/lib/python3.6/http/client.py", line 462, in read s = self._safe_read(self.length) File "/XXX/lib/python3.6/http/client.py", line 612, in _safe_read chunk = self.fp.read(min(amt, MAXAMOUNT)) File "/XXX/lib/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b) File "/XXX/lib/python3.6/ssl.py", line 1009, in recv_into return self.read(nbytes, buffer) File …
answer count: 1
upvote count: 16
favorite count: 0
has comment: http://stackoverflow.com/comment/91704855
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52365350
accepted answer: http://stackoverflow.com/a/52365350
tagged with: exception
tagged with: python
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/91705438
score: 16

http://stackoverflow.com/a/52351401
answers question: http://stackoverflow.com/q/52351333
has comment: http://stackoverflow.com/comment/91648238
has comment: http://stackoverflow.com/comment/91657666
has body: Using astype seems to achieve it df=df.astype("int64") You can also explicitly assign types to each column df = pd.DataFrame({'col1':pd.Series([], dtype='int'), 'col2':pd.Series([], dtype='int'), 'col3':pd.Series([], dtype='int')}) print(df.dtypes) col1 int64 col2 int64 col3 int64 dtype: object
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91648136
type: Answer

http://stackoverflow.com/comment/91747046
comment on: http://stackoverflow.com/q/52401629
score: 0
has text: What have you tried so far? Any libraries in particular?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52389786
type: UnansweredQuestion
tagged with: converters
tagged with: python
has comment: http://stackoverflow.com/comment/91724591
type: Question
has body: I am trying to convert the time below to the format HH:MM:SS. PXTIMEFLOWSTARTED_TIME 40538.22 131725.529 I am using: dataset['PXTIMEFLOWSTARTED_TIME'] = pd.to_datetime(dataset.PXTIMEFLOWSTARTED_TIME, unit = 's' ) However, I just get the results below: PXTIMEFLOWSTARTED_TIME 1970-01-01 11:15:38.220 1970-01-02 12:35:25.529 Anybody could help me to fix it? Thank you.
has answer: http://stackoverflow.com/a/52390459
score: 0
tagged with: pandas
answer count: 1
tagged with: python-3.x
has title: Python - Converter object in time
tagged with: time
has comment: http://stackoverflow.com/comment/91724651

http://stackoverflow.com/comment/91770676
comment on: http://stackoverflow.com/a/52394474
type: AnswerComment
type: Comment
has text: Thanks ross, working fine, and for Microsoft Sql Server i used "django-pyodbc-azure" to be the backend engine. (pip install django-pyodbc-azure).
score: 1

http://stackoverflow.com/comment/91643371
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52348894
has text: all you need is your code, and your `variables.py` which like I said I would make your own `auth_users.py` and that way you can just do this over and over and over and not interfere with whatever else you are storing then you could do `from auth_users import auth_users`
score: 0

http://stackoverflow.com/a/52304848
answers question: http://stackoverflow.com/q/52303130
score: 8
has body: Solved. I want to explain the issue rather than deleting my post, so that it maybe can help other people as well.. I will only give the example for the evaluate_generator(...) function. This is how I was calling the function.. lstm_model.evaluate_generator(data_generator(TEST_FILE_PATHS, TEST_BATCH_SIZE), steps=(NR_TEST_EXAMPLES // TEST_BATCH_SIZE), verbose=1) And I changed it as following: test_data_generator = data_generator(TEST_FILE_PATHS, TEST_BATCH_SIZE) lstm_model.evaluate_generator(test_data_generator, steps=(NR_TEST_EXAMPLES // TEST_BATCH_SIZE), verbose=1) And the problem is solved. I saw both ways of usage at different places, even if each information one finds on the net is not necessarily true. It is not clear for me either why it is solved when changing the code above. If anyone knows, I would be happy to hear the explanation.
accepted answer of: http://stackoverflow.com/q/52303130
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/124387798
has comment: http://stackoverflow.com/comment/94298504
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91801353
type: QuestionComment
score: 0
has text: Please provide an expected output.
type: Comment
comment on: http://stackoverflow.com/q/52428845

http://stackoverflow.com/comment/91686231
type: QuestionComment
comment on: http://stackoverflow.com/q/52370748
has text: Is this something you are after - https://stackoverflow.com/a/16696317/267482?
score: 0
type: Comment

event-handling
tag name: event-handling
type: Tag
tags question: http://stackoverflow.com/q/52365708

http://stackoverflow.com/comment/91618162
comment on: http://stackoverflow.com/q/52315520
score: 0
has text: always published the solution, for example could from there find a better solution, I for example was moving in a solution but for lack of time I still do not finish it. Your question seems interesting to me since the correct solution must be implemented on-demand and for this you must use fetchMore() and canFetchMore()
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52285114
type: UnansweredQuestion
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/91518687
has title: Get API data and displaying it in a GUI window
type: Question
tagged with: api
downvote count: 0
has comment: http://stackoverflow.com/comment/91521136
tagged with: python
favorite count: 0
answer count: 0
has body: I am new to python and programming in general. I have 2 questions: 1. I am trying to build a GUI that askes the user for input details to connect directly to a device via IP and subscribe to its API. I have managed to write working console code, but want to make it more user friendly in a GUI. 2. The output I get needs to be parsed correctly and displayed in the bottom frame of my input window. Here is what I have so far... import urllib.parse import requests import json from websocket import create_connection IP=input('Enter camera IP address: ') Type=input('Data or Event ? (Case sensitive): ') Data ={ "messageType":"Subscription", "subscription":{ "type":"Data", "action":"Subscribe" } } Event={ "messageType":"Subscription", "subscription":{ "type":"Event", "action":"Subscribe" } } main_api = 'ws://' API= '/api/subscriptions' ws = create_connection(main_api + IP + API) ws.connect(main_api + IP + API) print ('Connected !') if Type =='Data': ws.send(json.dumps(Data)) if Type =='Event': ws.send(json.dumps(Event)) while True: result = ws.recv() jsondata = json.loads(result) print ("Web Socket data received : \n'%s'" % result) print('') ws.close() Result: Enter camera IP address: 192.168.16.119 Data or Event ? (Case sensitive): Data Connected ! Web Socket data received : '{'messageType': 'Subscription', 'subscription': {'returnValue': 'OK', 'type': 'Data'}}' Web Socket data received : '{'dataNumber': '15751', 'intervalTime': '10', 'messageType': 'Data', 'time': '2018-09-12T10:02:00.001+01:00', 'type': 'PresenceData', 'zone': [{'numVeh': '0', 'zoneId': '1', 'zoneOccupancy': '0'}, {'numVeh': '0', 'zoneId': '2', 'zoneOccupancy': '0'}]}' Web Socket data received : '{'dataNumber': '15752', 'intervalTime': '10', 'messageType': 'Data', 'time': '2018-09-12T10:02:10.030+01:00', 'type': 'PresenceData', 'zone': [{'numVeh': '1', 'zoneId': '1', 'zoneOccupancy': '6'}, {'numVeh': '0', 'zoneId': '2', 'zoneOccupancy': '0'}]}' Web Socket data received : '{'dataNumber': '15753', 'interval…

http://stackoverflow.com/q/52355170
tagged with: moving-average
upvote count: 2
has answer: http://stackoverflow.com/a/52355426
has answer: http://stackoverflow.com/a/52355498
linked to: http://stackoverflow.com/q/509211
favorite count: 0
possible better answer: http://stackoverflow.com/a/52355659
tagged with: python
answer count: 4
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/52355322
accepted answer: http://stackoverflow.com/a/52355322
tagged with: average
type: Question
has comment: http://stackoverflow.com/comment/91655560
has body: I struggle to implement the moving average formula in my function. Took me quite a while to get where the code is right now. Is there a library I could probably take? Input: ma([2,3,4,3,2,6,9,3,2,1], 4) Expected Output: [None, None, None, 3.0, 3.0, 3.75, 5.0, 5.0, 5.0, 3.75] My Output: [None, None, 0.0, 3.0, 3.75, 5.0, 5.0, None, None, None] I am running into the problem that the middle parts of my result is right but the rest is a mystery. Why does it return None for the last three values in the list? def ma(prices, n): ma = [] sums = [] s = 0 ave = 0 for idx, i in enumerate(prices): s += i sums.append(s) print('idx: ' + str(idx)) print('list of sums ' + str(sums)) #print('sum ' + str(s)) if i &gt;= n+1: print('sums[idx] ' + str(sums[idx])) print('sums[idx-n] ' + str(sums[idx-n])) ave = (sums[idx] - sums[idx-n]) / n print('ave ' + str(ave)) ma.append(ave) print('ma ' + str(ma)) else: m = None ma.append(m) print('ma ' + str(ma)) (Sorry for all those print function calls, but I really wanted to get to the source of the issue).
downvote count: 0
has answer: http://stackoverflow.com/a/52355659
has title: Calculating a moving average
tagged with: data-science

http://stackoverflow.com/a/52285805
score: 0
answers question: http://stackoverflow.com/q/52285755
type: Answer
has body: Your code looks pretty much correct. html = ''' ... ''' soup = bs4.BeautifulSoup(html, 'lxml') # or 'html.parser' either way print([elem.text for elem in soup.find_all('tr', {'class': 'loser'})]) ['\nAtlanta Falcons\n12\n\nFinal\n\n']` What exactly is wrong?
has comment: http://stackoverflow.com/comment/91520339

featuretools
tag name: featuretools
type: Tag
tags question: http://stackoverflow.com/q/52418152

http://stackoverflow.com/a/52553043
has comment: http://stackoverflow.com/comment/92045004
answers question: http://stackoverflow.com/q/52404529
has comment: http://stackoverflow.com/comment/92183310
has comment: http://stackoverflow.com/comment/92213035
has comment: http://stackoverflow.com/comment/92046227
has comment: http://stackoverflow.com/comment/92068278
has body: Most probably, some path to Python environment that PyCharm tries to use has become invalid somewhere. There are (at least) two primary suspects: Path to your virtualenv in PyCharm settings PyCharm needs to know the path to your environment to run things in it. So, if that path changed, PyCharm's saved path has become invalid. Go to the interpreter settings for your project in File-&gt;Settings...-&gt;Project interpreter-&gt;(Gear icon)-&gt;Show all...: Then delete and recreate the necessary entries. Or edit them and specify correct paths. E.g. this is what my list looks like after I deleted an Anaconda installation: Path in the virtualenv to its base installation Since virtualenv is not a full installation, it must have a path to its base installation stored somewhere to be able to use files from there. As of this writing, virtualenv (v16.0.0) in Windows is implemented like this: The real python.exe and several other files are copied into the virtualenv's subtree In Lib\orig-prefix.txt, the path to the base installation is stored. It is used to add the base installation's Lib to sys.path via a custom site.py. So, if the path in that file becomes invalid, the virtualenv's Python interpreter will be unable to find any standard modules except those few that were copied. Which perfectly fits your symptoms.
downvote count: 1
has comment: http://stackoverflow.com/comment/92190099
upvote count: 12
has comment: http://stackoverflow.com/comment/92045066
has comment: http://stackoverflow.com/comment/92068279
has comment: http://stackoverflow.com/comment/92067990
has comment: http://stackoverflow.com/comment/110230885
has comment: http://stackoverflow.com/comment/92068007
has comment: http://stackoverflow.com/comment/92067638
has comment: http://stackoverflow.com/comment/92045093
has comment: http://stackoverflow.com/comment/92044947
has comment: http://stackoverflow.com/comment/92067632
type: Answer
score: 11

http://stackoverflow.com/comment/91662351
has text: The reason why I'm doing an asynchronous initialization is because I'm awaiting a few methods that need to be run as soon as the class is created, but because they are private methods I didn't want to call them "outside" of the class itself.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52358950
type: Comment

http://stackoverflow.com/comment/91566061
comment on: http://stackoverflow.com/q/52309212
score: 0
type: Comment
type: QuestionComment
has text: @PeterWood look up named tuple

http://stackoverflow.com/comment/91522746
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52287489
score: 1
has text: There's no function here. Functions start with a line `def functionname(parameters):`

http://stackoverflow.com/comment/91666738
comment on: http://stackoverflow.com/q/52361198
has text: You do not need any `literal_eval`'s or `str`s.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52428354
tagged with: python
has comment: http://stackoverflow.com/comment/91800575
has body: I am trying to install pandas in my project while numpy==1.13.1 already part of project and i want to keep numpy==1.13.1 and install pandas so: When I try to install with requirement.txt as: numpy==1.13.1 pandas==0.20.0 it installs perfectly , but when try to import pandas in python interpreter, i get error: ImportError: C extension: numpy.core.multiarray failed to import not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace --force' to build the C extensions first. while if i only keep requirement.txt as: pandas==0.20.0 it installs perfectly and import pandas works fine. My assumption is that when numpy is already installed separately , it is not able to build with pandas while when there is no numpy installed it gets installed as pandas dependency and hence built fine, if this it true and i remove numpy from requirement.txt and allow it be installed as pandas dependency what version of pandas i should install so that at the end of all library installation from requirement.txt, i will have numpy==1.13.1. If this is not the issue what should be way forward My desired ouput is: numpy==1.13.1 installed pandas version any except 0.23.* import pandas working fine python version : 2.7.10
has comment: http://stackoverflow.com/comment/91800692
score: 0
tagged with: numpy
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91800209
tagged with: pandas
has comment: http://stackoverflow.com/comment/91800944
has comment: http://stackoverflow.com/comment/91801051
has comment: http://stackoverflow.com/comment/91800345
type: Question
has comment: http://stackoverflow.com/comment/91800427
has comment: http://stackoverflow.com/comment/91800127
has title: Python pandas dependency with numpy

http://stackoverflow.com/comment/91707018
type: Comment
has text: Can you specify database? Or think pandas DataFrame?
score: 0
comment on: http://stackoverflow.com/q/52381343
type: QuestionComment

http://stackoverflow.com/comment/91671663
type: Comment
type: QuestionComment
score: 0
has text: what line throws this error?
comment on: http://stackoverflow.com/q/52362534

http://stackoverflow.com/q/52404416
tagged with: python-2.7
duplicate of: http://stackoverflow.com/q/15063936
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/99505648
tagged with: python
linked to: http://stackoverflow.com/q/15063936
answer count: 0
score: 1
upvote count: 1
type: Question
has body: I am trying to set the field size limit on CSV csv.field_size_limit(sys.maxsize) Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; OverflowError: Python int too large to convert to C long This runs perfectly well on MacOS and Ubuntu but I am facing this exception on Windows. I am running Windows 10 x64 and python 2.7 x64. If I run the above line without arguments, I get the current limit: csv.field_size_limit() 131072 How can I get this function to work on windows as well?
has title: OverFlowError: Python int too large to convert to C long on windows for CSV field size limit

http://stackoverflow.com/a/52408850
upvote count: 1
has comment: http://stackoverflow.com/comment/91763717
downvote count: 1
has comment: http://stackoverflow.com/comment/91761574
has comment: http://stackoverflow.com/comment/91761926
score: 0
has comment: http://stackoverflow.com/comment/91761796
has comment: http://stackoverflow.com/comment/91762027
type: Answer
has body: Neither option feels right. The name BenjaminFranklin suggests that this is an instance of something. However, the question is why no_legs, is_hungry etc are specific to Benjamin Franklin, and not to all cats. It seems that those attributes should me moved up to the parent Cat class, and Benjamin Franklin should be an instance of it. Moreover, if only benjamin franklin has a num_legs variable, what does he do with it? There is no added function that uses the new fields. In that sense, this seems more like a dict, or a namedtuple than an instance of a class. However, it's not possible to tell what the best way is without seeing the functionality of the Cat class, and how you use the extra attributes of benjamin franklin.
answers question: http://stackoverflow.com/q/52408697
has comment: http://stackoverflow.com/comment/91761980

http://stackoverflow.com/q/52289061
has comment: http://stackoverflow.com/comment/91526800
has comment: http://stackoverflow.com/comment/91527335
answer count: 1
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91527134
favorite count: 0
has answer: http://stackoverflow.com/a/60538830
has comment: http://stackoverflow.com/comment/91530888
type: UnansweredQuestion
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/91528879
has comment: http://stackoverflow.com/comment/91530060
has comment: http://stackoverflow.com/comment/91531760
has comment: http://stackoverflow.com/comment/91528343
has title: How to get flake8 in $PATH
upvote count: 1
has comment: http://stackoverflow.com/comment/91526162
type: Question
has comment: http://stackoverflow.com/comment/91528151
linked to: http://stackoverflow.com/q/45707756
has comment: http://stackoverflow.com/comment/91529465
has body: Windows 7 with Atom IDE. Stick with me here, I'm new to using command line and atom. flake8 error while running python in atom. terminal say file location for flake8 is: /c/Users/Parker/AppData/Local/Programs/Python/Python37/Scripts/flake8 How do I get flake8 in my path for atom? I tried download the virtualenv and then abandoned that when I hit sudo:command not found. Figured there must be an easier way. How do I do this? Been trying different methods for days and have exhausted the search function.
has comment: http://stackoverflow.com/comment/91530323
tagged with: atom-editor
tagged with: flake8

http://stackoverflow.com/comment/91672523
type: Comment
type: QuestionComment
score: 0
has text: Sorry but I can't understand how dicts relates to ms access, 'entry form' and databases. Just a hint though: dicts _always_ hold a single value per key indeed - that's part of the definition of a dict actually - but this value can be a `list`, `set`, `dict` or whatever.
comment on: http://stackoverflow.com/q/52362710

http://stackoverflow.com/comment/91643475
type: Comment
has text: you dont have to write 0 in your slice though
comment on: http://stackoverflow.com/a/52348980
score: 1
type: AnswerComment

http://stackoverflow.com/a/77477843
answers question: http://stackoverflow.com/q/52352302
has body: This error is recently due to Wifi Issue. Wifi works fine but, nltk is not downloaded. Please see this question: Jio wifi is the problem. It seems to be that on some networks, I've been told "Jio" is one of them, raw.githubusercontent.com is not accessible, e.g.: https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/packages/tokenizers/punkt.xml https://github.com/nltk/nltk/issues/1981#issuecomment-1804689730 https://github.com/nltk/nltk/issues/3104
type: Answer
score: 0

http://stackoverflow.com/q/52427412
has body: When installing a script using Python, the shebang gets replaced as discussed in this post. The problem is that in my case it gets replaced by #!/ssoft/spack/paien/v2/opt/spack/linux-rhel7-x86_E5v2_IntelIB/gcc-7.3.0/python-3.6.5-5yxsy6j5miw26wxpzrtync5gnhtsv5pt/bin/python3 which appears too long for the OS to handle: bad interpreter: /ssoft/spack/paien/v2/opt/spack/linux-rhel7-x86_E5v2_IntelIB/g: no such file or directory How can I work around this problem? (Except for overriding setuptools' default script copy routine.)
answer count: 1
has answer: http://stackoverflow.com/a/52430449
upvote count: 3
linked to: http://stackoverflow.com/q/10813538
has comment: http://stackoverflow.com/comment/91798246
favorite count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/91798397
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1530702
has comment: http://stackoverflow.com/comment/91822065
tagged with: python
has title: (Python's) shebang too long
score: 3
has comment: http://stackoverflow.com/comment/91804496
tagged with: setuptools
tagged with: shebang
type: Question
has comment: http://stackoverflow.com/comment/91798265

http://stackoverflow.com/a/52321496
answers question: http://stackoverflow.com/q/52319664
score: 0
type: Answer
has body: Would this not achieve your goal? for i in data: if i.get('id') == 'ieow83janx': print(i) (xenial)vash@localhost:~/python$ python3.7 split.py {'id': 'ieow83janx', 'name': 'Jane', 'mail': 'test@foobar.com'} Using comprehension: [i for i in data if i.get('id') == 'ieow83janx']

http://stackoverflow.com/q/52325215
favorite count: 0
has comment: http://stackoverflow.com/comment/91598098
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52327917
has title: python subprocess become idle after a while
possible better answer: http://stackoverflow.com/a/62279468
tagged with: python
type: AnsweredQuestion
tagged with: subprocess
upvote count: 3
has comment: http://stackoverflow.com/comment/91597991
has comment: http://stackoverflow.com/comment/91598374
accepted answer: http://stackoverflow.com/a/52327917
type: Question
has body: I have two script, one is for reading serial port continuously and other script is for running the serial port reading script in background. The script given below is I used for running as subprocess. subprocess.Popen("echo " + user_password + " | sudo -S " + filePath shell=True, stdout=subprocess.PIPE) if i run serial port reading script manually, it will not idle, it runs contineously. But if i use the above script for running as subprocess, the serial port reading script become idle after a few minutes. How i can stop this idle issue?
answer count: 2
has comment: http://stackoverflow.com/comment/91597839
has comment: http://stackoverflow.com/comment/91598007
downvote count: 0
tagged with: python-2.7
score: 3
has comment: http://stackoverflow.com/comment/91597425
has answer: http://stackoverflow.com/a/62279468
has comment: http://stackoverflow.com/comment/91597373
has comment: http://stackoverflow.com/comment/91598333

http://stackoverflow.com/q/52324838
has answer: http://stackoverflow.com/a/52324915
has answer: http://stackoverflow.com/a/52324867
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52325231
tagged with: python
answer count: 4
score: 1
has body: I'm trying to figure out how to duplicate a single file for example: I have a file in "C:\ ..." and would like to duplicate this exact same file once. If also possible is there a way to use python to open specific documents? thanks
tagged with: file
has answer: http://stackoverflow.com/a/52324957
downvote count: 1
has comment: http://stackoverflow.com/comment/91596600
type: Question
linked to: http://stackoverflow.com/q/123198
has title: Duplicate a file with Python

http://stackoverflow.com/q/52419474
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: pytest
has body: I'm new to python unit test. I learned and did sample unit test where method accepts input and returns output. But for code as mentioned below, I've some questions. How I mock configparser of init method in unittest? Path /config/program.cfg is on production server and not exists in dev directory. program.cfg file exists at other location in code directory. Is there a way to handle that in unittest? How I send or skip something like hardcoded path in unittest e.g. /var/log/info_server.log If possible, can you please tell me how would you write unittest for below code using pytest module? This will be helpful to understand the flow and I can do that with rest of code. def __init__(self): self.setup_logger() # Read config parameters config = configparser.ConfigParser() config.read("/config/program.cfg") self.host_ip = config.get('default','HostIP') self.redis_ip = config.get('default','RedisIP') self.redis_port = config.get('default','RedisPort') self.info_port = config.get('default','InfoPort') self.sqlite_db_file = config.get('default','SQLiteDbFile') self.connect_redis() def setup_logger(self): #Initialize logger self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.INFO) # Create a file handler handler = logging.FileHandler('/var/log/info_server.log') handler.setLevel(logging.INFO) # Create a logging format formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) # Add the handlers to the logger self.logger.addHandler(handler) def connect_redis(self): # Start up a Redis instance self.logger.info("Start Redis instance") self.ad_info = redis.StrictRedis(host=self.redis_ip, port=self.redis_port, db=0) if self.ad_info is None: self.logger.error("Failed to start Redis instance") else: self.logger.info("Started Redis instance")
tagged with: unit-testing
type: Question
accepted answer: http://stackoverflow.com/a/52458365
has title: unit test python code that has configparser reading from config file
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91811124
favorite count: 0
has answer: http://stackoverflow.com/a/52458365
upvote count: 2

http://stackoverflow.com/a/52380563
type: Answer
has comment: http://stackoverflow.com/comment/91711988
has comment: http://stackoverflow.com/comment/91737244
score: 0
has comment: http://stackoverflow.com/comment/91705715
has comment: http://stackoverflow.com/comment/91785489
has comment: http://stackoverflow.com/comment/91737233
has body: Agree with posting this on Code Review tho, but still can simplify it: import sys filename=sys.argv[1] if not isinstance(filename,str): raise Exception('wrong type') try: open(filename,'r') except FileNotFoundError: raise FileNotFoundError('Cannot find filename') Simplifying if/else into a if, and more efficient is isinstance, instead of type(..) == .. Btw sys.argv[1] is always a string so no need for if statement: import sys filename=sys.argv[1] try: open(filename,'r') except FileNotFoundError: raise FileNotFoundError('Cannot find filename') Btw, os.path.exists: if not os.path.exists(filename): raise FileNotFoundError
answers question: http://stackoverflow.com/q/52380342
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52380342

http://stackoverflow.com/q/52296306
has comment: http://stackoverflow.com/comment/91540546
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52336898
type: AnsweredQuestion
tagged with: django-templates
has comment: http://stackoverflow.com/comment/91540757
has comment: http://stackoverflow.com/comment/91540550
type: Question
has comment: http://stackoverflow.com/comment/91560287
has comment: http://stackoverflow.com/comment/91540697
has answer: http://stackoverflow.com/a/73420463
upvote count: 5
accepted answer: http://stackoverflow.com/a/52336898
has comment: http://stackoverflow.com/comment/91540748
has comment: http://stackoverflow.com/comment/91540611
has title: Django template - Is there a built-in way to get current date as type 'date' instead of type 'str'?
has comment: http://stackoverflow.com/comment/91540592
possible better answer: http://stackoverflow.com/a/73420463
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/91540451
downvote count: 0
has comment: http://stackoverflow.com/comment/91540965
has comment: http://stackoverflow.com/comment/91540653
favorite count: 0
has body: I know I can get the current date as a str in a Django template (using the template tag now), like this: {% now "Y-m-d" as today_str %} {{ today_str }} But I cannot use that for comparissons: {% now "Y-m-d" as today_str %} {% for elem in object_list %} {% if elem.date < today_str %} {# WRONG: this compares 'date' and 'str' #} {{ elem.pk }} before today {# do some other rendering #} {% endif %} {% endfor %} Possible solutions: I know I can pass a context variable to the template, but it requires code in my view: # in my class-based-view in 'views.py' def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx['today'] = timezone.now() return ctx Or I can create a custom template tag, but that is even more additional code. As you can see I have workarounds for my problem, but I would like to know if there is a buit-in way to get the current date (or datetime) in the template?
has comment: http://stackoverflow.com/comment/91540840

http://stackoverflow.com/comment/91505945
type: QuestionComment
has text: Try running `python3 -m test.test_module_1` on `project` directory
comment on: http://stackoverflow.com/q/52277705
score: 0
type: Comment

http://stackoverflow.com/a/52414488
score: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52414440
type: Answer
upvote count: 3
has body: I will recommend np.r_ df.drop(np.r_[40:50+1]) In case you want to drop two range at the same time np.r_[40:50+1,1:4+1] Out[719]: array([40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 1, 2, 3, 4])
accepted answer of: http://stackoverflow.com/q/52414440

http://stackoverflow.com/comment/91820666
comment on: http://stackoverflow.com/q/52425315
has text: Technically, the input file is mis-encoded. If Unicode escapes are used in a file, literal backslashes should be escaped (as double-backslashes) as well: `'Korado's output has gone up from 180,000 radiators per year to almost 1.7 million today,' says Vojt\u0115ch \u010camek.\nVoor alle bestanden kan de naam met de volledige padnaam (bijvoorbeeld: /u/slick/udfs/math.a (op UNIX), d:\\udfs\\math.dll (op Windows)).`
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91768709
has text: what boxen plot showing by replacing outlier with a thin line or arrow ?
type: AnswerComment
comment on: http://stackoverflow.com/a/52409148
score: 0
type: Comment

http://stackoverflow.com/a/52387149
score: 0
has body: Be careful with your indentation, you get this error because you sometimes you use spaces and other tabs to indent. As PM 2Ring said, reading 'Fault_codes.csv' everytime you read 1 line of your log is really not efficient. You should read faultcode once and store the content in RAM (if it fits). You can use pandas to do it, and store the content into a DataFrame. I would do that before reading your logs. You do not need to store all log.csv lines in RAM. So I'd keep reading it line by line with csv module, do my stuff, write to a new file, and read the next line. No need to use pandas here as it will fill your RAM for nothing.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91719330
type: Answer
accepted answer of: http://stackoverflow.com/q/52386872
answers question: http://stackoverflow.com/q/52386872

http://stackoverflow.com/comment/91662569
comment on: http://stackoverflow.com/q/52359042
score: 0
type: Comment
has text: show your `Login` class complete.
type: QuestionComment

http://stackoverflow.com/comment/91616312
score: 0
type: Comment
type: QuestionComment
has text: try , `index_col=None`
comment on: http://stackoverflow.com/q/52334484

http://stackoverflow.com/a/60479770
has body: You can also just override the mouseEvent of existing widgets. For example, if you want to ignore scroll events in a specific spinbox you can override the wheelEvent with a lambda function that does nothing: from PyQt5 import QtWidgets box = QtWidgets.QSpinBox() box.wheelEvent = lambda event: None Alternatively, you can use the findChildren function to change the event for all widgets of a certain type (QSpinBox, for example) that your main window contains, like so: from PyQt5 import QtCore, QtWidgets main = QtWidgets.QMainWindow() '''add some QSpinboxes to main''' opts = QtCore.Qt.FindChildrenRecursively spinboxes = main.findChildren(QtWidgets.QSpinBox, options=opts) for box in spinboxes: box.wheelEvent = lambda *event: None This same principle could theoretically be applied to other widget classes and events, but I haven't tested it beyond spinboxes and wheel events.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52370288
score: 6
upvote count: 6

http://stackoverflow.com/a/52396918
downvote count: 0
has body: Ignoring recursion: n = 6 &gt;&gt;&gt; sum(x ** x for x in range(n, 0, -1)) 50069 # 6 ** 6 + 5 ** 5 + 4 ** 4 + 3 ** 3 + 2 ** 2 + 1 ** 1 # = 46656 + 3125 + 356 + 27 + 4 + 1 # = 50069 Using recursion: def power_function(n): if n &lt; 1: return 0 return n ** n + power_function(n - 1) &gt;&gt;&gt; power_function(6) 50069
answers question: http://stackoverflow.com/q/52396852
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91738608
type: Answer
has comment: http://stackoverflow.com/comment/91738509

http://stackoverflow.com/a/52352744
has comment: http://stackoverflow.com/comment/91664952
upvote count: 7
type: AcceptedAnswer
has body: Kinda interesting question. Instead of referring to your questions first, I'll go for your comment. Once the input string has been consumed in full, why would you treat the fact that there is nothing left as the empty string? A position called end of subject string is left. It's a position and can be matched. Like other zero-width assertions and anchors \b, \B, ^, $... that assert, a dot-star .* can match an empty string. This is highly dependent on regex engine. E.g. TRegEx does it differently. And if you do, shouldn't this result in an infinite loop? No, this is one of the main jobs of regex engines to handle. They raise a flag and store current cursor data to avoid such loops to occur. Perl docs explain it this way: A common abuse of this power stems from the ability to make infinite loops using regular expressions, with something as innocuous as: 'foo' =~ m{ ( o? )* }x; The o? matches at the beginning of foo, and since the position in the string is not moved by the match, o? would match again and again because of the * quantifier. Another common way to create a similar cycle is with the looping modifier /g... Thus Perl allows such constructs, by forcefully breaking the infinite loop. The rules for this are different for lower-level loops given by the greedy quantifiers *+{} , and for higher-level ones like the /g modifier or split() operator. The lower-level loops are interrupted (that is, the loop is broken) when Perl detects that a repeated expression matched a zero-length substring. Now back to your questions: Is there a good reason for this behavior? Yes, there is. Every regex engine has to meet a significant amount of challenges in order to process a text. One of which is dealing with zero-length matches. Your question raises another question, Q: How does an engine should proceed after matching a zero-length string? A: It all depends. PCRE (or Ruby here) doesn't skip zero-length matches. It matches it then raises a flag to not match the same position again …
has comment: http://stackoverflow.com/comment/91658325
has comment: http://stackoverflow.com/comment/91657542
type: Answer
answers question: http://stackoverflow.com/q/52351217
downvote count: 0
score: 7
accepted answer of: http://stackoverflow.com/q/52351217
has comment: http://stackoverflow.com/comment/91659758
has comment: http://stackoverflow.com/comment/92065073
has comment: http://stackoverflow.com/comment/91683616
has comment: http://stackoverflow.com/comment/91658072
has comment: http://stackoverflow.com/comment/91659761
has comment: http://stackoverflow.com/comment/91660264

http://stackoverflow.com/comment/91589556
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52304720
type: AnswerComment
has text: Instead of an invisible button with an image, a simpler solution is to use an empty `Frame` which can be configure to be a specific width in pixels.

http://stackoverflow.com/q/52366703
has comment: http://stackoverflow.com/comment/91677765
has answer: http://stackoverflow.com/a/52366909
favorite count: 0
tagged with: python-3.x
upvote count: 2
has title: How to set start and stop input in Python which generating word list
accepted answer: http://stackoverflow.com/a/52366909
tagged with: python
score: 2
type: AnsweredQuestion
has body: I try Hard to figure out how to Input start and stop word for my Python wordlist generator. Here is my code: import itertools wrds = 'abcd0123' n = 5 for i in itertools.product(wrds, repeat = n): a = ''.join(i) print(a) My generator is giving me output like this as usual: aaaaa, aaaab, aaaac,... But how set the inputs in order to take a starting point and an ending point?. My length is 5. I want to generate for example from aaac1 to aaad3. How can I achieve this? I'm completely stuck.
type: Question
has comment: http://stackoverflow.com/comment/91677906
answer count: 1
downvote count: 0

qpainter
tags question: http://stackoverflow.com/q/52323548
type: Tag
tag name: qpainter

http://stackoverflow.com/a/52346894
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52346653
has body: Thanks for all your help guys! This is what did the trick: with open('MyServices.txt', 'w') as f: for (short_name, desc, status) in statuses: f.write(str(desc)) f.write(str(status)) f.write('----------&gt; Running') f.write(os.linesep) #Print output and append 'Running' at the end of each line print(desc, status, '----------&gt; Running')
type: Answer
score: 1

http://stackoverflow.com/comment/91730001
comment on: http://stackoverflow.com/a/52391462
type: AnswerComment
has text: You missed the update for the first line. Since you are using the same locator twice, it would probably be better to declare the locator as a variable and then use the variable. This won't work btw since you are clicking *after* waiting for stale. The wait for stale will timeout since nothing has happened to make it go stale. You need to get the element and assign it to a variable, `link`... then do `link.click()`, then wait for `link` to go stale.
score: 0
type: Comment

http://stackoverflow.com/comment/91701039
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52378071
type: Comment
has text: DSM Wen I am not familiar with networkx. I will give it a read. Thanks

http://stackoverflow.com/a/52305053
has body: Empirically, wordList is not finite: you append to it while you're iterating through it, which extends the list. Use a print statement within the loop to trace your values, and you'll see the problem. You insert a 0 in front of the letter you found. That letter gets bumped right one position, and you get to find the same letter on the next execution. for letter in wordList: if user_input == letter: indexNb = wordList.index(letter) word_holder.insert(indexNb, letter) wordList.insert(indexNb, '0') print('You found the letter', letter) print(' wordList is now', wordList) Instead, use the replace method or build a new string from the original. For instance, just replace this loop with wordList.replace(letter, '0') print('You found the letter', letter) Also, please note a distinct problem: you're working on the entire wordList, rather than just one word; I haven't fixed that portion.
answers question: http://stackoverflow.com/q/52304959
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91557599

wsgi
tags question: http://stackoverflow.com/q/52324921
type: Tag
tags question: http://stackoverflow.com/q/52330828
tags question: http://stackoverflow.com/q/52299317
tags question: http://stackoverflow.com/q/52357753
tags question: http://stackoverflow.com/q/52372187
tag name: wsgi

http://stackoverflow.com/comment/91707590
has text: @ReblochonMasque I would like to create a list comprising the default symbolic color names of Tk. So far, I have found 12 symbolic color names of Linux that Tk do not recognised. The valid list of symbol color names is to ensure valid symbolic color names are supplied to my tkinter application.
comment on: http://stackoverflow.com/q/52381046
score: 0
type: Comment
type: QuestionComment

beautifulsoup
tags question: http://stackoverflow.com/q/52390465
tags question: http://stackoverflow.com/q/52318884
tags question: http://stackoverflow.com/q/52427376
tags question: http://stackoverflow.com/q/52345850
tags question: http://stackoverflow.com/q/52343735
tags question: http://stackoverflow.com/q/52420147
tags question: http://stackoverflow.com/q/52298676
tags question: http://stackoverflow.com/q/52368255
tags question: http://stackoverflow.com/q/52320843
tags question: http://stackoverflow.com/q/52351261
tags question: http://stackoverflow.com/q/52359195
tags question: http://stackoverflow.com/q/52356152
tags question: http://stackoverflow.com/q/52333868
tags question: http://stackoverflow.com/q/52342666
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/52351466
tags question: http://stackoverflow.com/q/52408505
tags question: http://stackoverflow.com/q/52355051
tags question: http://stackoverflow.com/q/52372760
tags question: http://stackoverflow.com/q/52315060
tags question: http://stackoverflow.com/q/52396708
tags question: http://stackoverflow.com/q/52377732
tags question: http://stackoverflow.com/q/52391597
tags question: http://stackoverflow.com/q/52352795
tags question: http://stackoverflow.com/q/52289234
tags question: http://stackoverflow.com/q/52394976
tags question: http://stackoverflow.com/q/52284621
tags question: http://stackoverflow.com/q/52409296
tags question: http://stackoverflow.com/q/52332361
tags question: http://stackoverflow.com/q/52334940
tags question: http://stackoverflow.com/q/52358022
tags question: http://stackoverflow.com/q/52408701
tags question: http://stackoverflow.com/q/52371407
tags question: http://stackoverflow.com/q/52384262
tags question: http://stackoverflow.com/q/52328581
tags question: http://stackoverflow.com/q/52360080
tags question: http://stackoverflow.com/q/52359545
tags question: http://stackoverflow.com/q/52346272
tags question: http://stackoverflow.com/q/52277922
tags question: http://stackoverflow.com/q/52333368
tags question: http://stackoverflow.com/q/52308329
type: Tag
tags question: http://stackoverflow.com/q/52293548
tags question: http://stackoverflow.com/q/52363748
tags question: http://stackoverflow.com/q/52305329
tags question: http://stackoverflow.com/q/52373526
tags question: http://stackoverflow.com/q/52347616
tags question: http://stackoverflow.com/q/52343742
tags question: http://stackoverflow.com/q/52276220
tags question: http://stackoverflow.com/q/52304522
tags question: http://stackoverflow.com/q/52346180
tags question: http://stackoverflow.com/q/52398738
tags question: http://stackoverflow.com/q/52283259
tags question: http://stackoverflow.com/q/52294620
tags question: http://stackoverflow.com/q/52375755
tags question: http://stackoverflow.com/q/52396055
tags question: http://stackoverflow.com/q/52367279
tags question: http://stackoverflow.com/q/52342543
tags question: http://stackoverflow.com/q/52416158
tags question: http://stackoverflow.com/q/52369846
tags question: http://stackoverflow.com/q/52291270
tags question: http://stackoverflow.com/q/52373527
tags question: http://stackoverflow.com/q/52317111
tags question: http://stackoverflow.com/q/52396215
tags question: http://stackoverflow.com/q/52275204
tags question: http://stackoverflow.com/q/52405995
tags question: http://stackoverflow.com/q/52336394

http://stackoverflow.com/comment/92541476
score: 0
type: Comment
has text: Please I have more questions about this kind of problem here. https://stackoverflow.com/questions/52791324/adding-importance-of-points-in-matplotlib-heat-map
comment on: http://stackoverflow.com/a/52313584
type: AnswerComment

http://stackoverflow.com/a/52345896
has body: You could make a small function that converts a single value exactly how you want it, e.g.: def to_int(x): try: return int(x) except ValueError: return 0 which can be used with map: In [22]: a = ['15', '12', '', 18909, '8989', '90789', '8'] map(to_int, a) Out[23]: [15, 12, 0, 18909, 8989, 90789, 8] in a list comprehension: In [25]: np.array([to_int(x) for x in a]) Out[25]: array([ 15, 12, 0, 18909, 8989, 90789, 8]) or in a generator expression to directly create a numpy array: In [27]: np.fromiter((to_int(x) for x in a), dtype=int) Out[27]: array([ 15, 12, 0, 18909, 8989, 90789, 8])
has comment: http://stackoverflow.com/comment/91637585
score: 5
type: AcceptedAnswer
upvote count: 5
accepted answer of: http://stackoverflow.com/q/52345762
type: Answer
answers question: http://stackoverflow.com/q/52345762
downvote count: 0

http://stackoverflow.com/comment/91703207
comment on: http://stackoverflow.com/q/52379152
score: 1
type: Comment
type: QuestionComment
has text: What do you mean by "index"?

http://stackoverflow.com/a/52302986
has comment: http://stackoverflow.com/comment/137666262
has comment: http://stackoverflow.com/comment/91555887
has body: Marks are evaluated before the tests are executed, so there's no way to pass some kind of declarative mark (like skipif) that depends on other tests results. You can apply custom test skipping logic in hooks, though. Modifying the incremental testing - test steps recipe from pytest docs: # conftest.py import pytest def pytest_sessionstart(session): session.failednames = set() def pytest_runtest_makereport(item, call): if call.excinfo is not None: item.session.failednames.add(item.originalname) def pytest_runtest_setup(item): if item.originalname in item.session.failednames: pytest.skip("previous test failed (%s)" % item.name) # or use pytest.xfail like in the other answer Example test @pytest.mark.parametrize('i', range(10)) def test_spam(i): assert i != 3 yields: =================================== test session starts =================================== collected 10 items test_spam.py::test_spam[0] PASSED test_spam.py::test_spam[1] PASSED test_spam.py::test_spam[2] PASSED test_spam.py::test_spam[3] FAILED test_spam.py::test_spam[4] SKIPPED test_spam.py::test_spam[5] SKIPPED test_spam.py::test_spam[6] SKIPPED test_spam.py::test_spam[7] SKIPPED test_spam.py::test_spam[8] SKIPPED test_spam.py::test_spam[9] SKIPPED ========================================= FAILURES ======================================== _______________________________________ test_spam[3] ______________________________________ i = 3 @pytest.mark.parametrize('i', range(10)) def test_spam(i): &gt; assert i != 3 E assert 3 != 3 test_spam.py:5: AssertionError ====================== 1 failed, 3 passed, 6 skipped in 0.06 seconds ====================== Edit: working with custom markers def pytest_runtest_makereport(item, call): markers = {marker.name for marker in item.iter_markers()} if call.excinfo is not None and 'skiprest' in markers: item.session.failednames.add(item.originalname) def pytest_runtest_setup(item): markers = {marker.name for marker in item.iter_markers()} if item.originalname in item.sess…
answers question: http://stackoverflow.com/q/52295214
upvote count: 7
accepted answer of: http://stackoverflow.com/q/52295214
score: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91554320
downvote count: 0
has comment: http://stackoverflow.com/comment/137664484
type: Answer

http://stackoverflow.com/q/52316629
has body: I upgraded Odoo v11's python2 to python3. After that I edited my addons. One of my addons, i'm getting error. result = method(recs, *args, **kwargs) File "D:\Odoo 11.0\server\addons\addons- trbase\l10n_tr_account_einvoice\models\account_einvoice_provider.py", line 698, in action_einvoice_get_invoices self.einvoice_get_invoices() File "D:\Odoo 11.0\server\addons\addons- unauth\l10n_tr_account_einvoice_provider_isis\models\account_einvoice_provider.py", line 272, in einvoice_get_invoices bytedata = base64.decodestring(result.ByteData) File "D:\Odoo 11.0\python\lib\base64.py", line 552, in decodebytes _input_type_check(s) File "D:\Odoo 11.0\python\lib\base64.py", line 520, in _input_type_check raise TypeError(msg) from err TypeError: expected bytes-like object, not Text python says that; Deprecated alias of decodebytes(). Deprecated since version 3.1. I'm trying decodebytes() instead of decodestring() but it's not working. Here is my class method: def einvoice_get_invoices(self): if self.provider != 'isis': return super(AccountEinvoiceProvider, self).einvoice_get_invoices() else: try: client = self.isis_get_client() count = 0 while count &lt; 50: count += 1 result = client.service.GetSingleEnvelope(self.company_id.vat[2:]) self.isis_check_error(result) if result.EnvelopeUUID: bytedata = base64.decodestring(result.ByteData) buffer = io.BytesIO(bytedata) if zipfile.is_zipfile(buffer): file = zipfile.ZipFile(buffer, 'r') for name in file.namelist(): bytedata = file.read(name) _logger.debug("Processing Envelope: %s" % bytedata.decode('utf-8')) self.einvoice_process_envelope(bytedata) else: _logger.info("Invalid Zip File! EnvelopeUUID= %s" % result.EnvelopeUUID) else: count = 50 return True except WebFault as e: _logger.error(_('E-Invoice Provider WebService Error!') + '\n\n' + e.message) return False How can I fix it?
tagged with: python
score: 3
has answer: http://stackoverflow.com/a/52917652
tagged with: odoo-11
tagged with: odoo
upvote count: 3
type: Question
answer count: 2
downvote count: 0
tagged with: python-2.x
favorite count: 0
tagged with: python-3.x
has title: Odoo Python3 base64 error: TypeError: expected bytes-like object, not Text
has answer: http://stackoverflow.com/a/58569542
type: UnansweredQuestion

http://stackoverflow.com/comment/91651829
has text: Code runs fine..in that it iterate i+=1, but for wtv reason is defaulting to the if statement formula and not the else formula
comment on: http://stackoverflow.com/q/52353499
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52350833
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/52350869
tagged with: pandas
has body: Here is how the data structure is below... It is a List with inner List that contains two Dictionaries each. I want it into dataframe with these headings: hasPossession, score and spread. [[{'hasPossession': '0', 'score': '23', 'spread': '-0'}, {'hasPossession': '0', 'score': '34', 'spread': '0.0'}], [{'hasPossession': '0', 'score': '', 'spread': '-7.5'}, {'hasPossession': '0', 'score': '', 'spread': '7.5'}], [{'hasPossession': '0', 'score': '', 'spread': '-1'}, {'hasPossession': '0', 'score': '', 'spread': '1.0'}]] Generally, above structure is a List that contains 3 Lists and each List contains 2 Dictionary with 2 elements. How do I transform such into pandas dataframe?
has title: Python pandas: Nested List of Dictionary into Dataframe
score: 0
accepted answer: http://stackoverflow.com/a/52350869
tagged with: python
linked to: http://stackoverflow.com/q/952914
type: AnsweredQuestion
tagged with: list
tagged with: dataframe

http://stackoverflow.com/comment/91864237
type: Comment
score: 0
type: AnswerComment
has text: I just got the answer from the great Charlie Clark in [this link](https://groups.google.com/d/msg/openpyxl-users/0_q2T-icXPU/ZkEVe1rmCQAJ) that one needs version>= 2.5.5 for preserving images during openPyxl modification.
comment on: http://stackoverflow.com/a/52418829

http://stackoverflow.com/q/52307847
score: 1
upvote count: 1
has title: Pandas vectorisation between two dataframes
type: Question
has body: import numpy as np import pandas as pd from scipy.stats import levene as lev raw_data = {'IDs': ['G1', 'G2', 'G3', 'G4', 'G5'], 'Sample1': [102.2, 2310.4, 123.4, 213.0, 1234.2], 'Sample2': [112.8, 1910.4, 36.3, 188.2, 1271.2], 'Sample3': [32.2, 1290.3, 121.4, 212.3, 1333.5], 'Sample4': [52.1, 2210.1, 155.2, 244.7, 1987.1]} raw_data2 = {'IDs': ['S1', 'S2', 'S3', 'S4', 'S5'], 'Sample1': [1, 2, 1, 0, 2], 'Sample2': [2, 1, 2, 1, 2], 'Sample3': [2, 0, 1, 0, 1], 'Sample4': [1, 2, 1, 2, 1]} df1 = pd.DataFrame(raw_data, columns = ['IDs', 'Sample1', 'Sample2', 'Sample3', 'Sample4']) df2 = pd.DataFrame(raw_data2, columns = ['IDs', 'Sample1', 'Sample2', 'Sample3', 'Sample4']) I have been trying to figure out a way to implement a levenes test on each row of df1, with every row df2 defining the groups to split. For example row one of df1 would be grouped by every row of df2, every time a levenes test would be run. Obviously I can implement it with a nested loops such as (have to include the if statements also as not all rows will contain all groups): for i in range(0, df1.shape[0]): for j in range(0, df2.shape[0]): tmp1=df1.ix[i,:] tmp2=df2.ix[i,:] group1 = tmp1[tmp2==0] group2 = tmp1[tmp2==1] group3 = tmp1[tmp2==2] if len(group1) &lt;= 1: lev(group2,group3) # and some how return the output to a new df elif len(group2) &lt;= 1: lev(group1,group3) # and some how return the output to a new df elif len(group3) &lt;=1: lev(group1,group2) # and some how return the output to a new df else: lev(group1,group2,group3) # and some how return the output to a new df The samples are in the same order in the dataframes, however one df has a few extra columns of descriptor (important to retain for output). As I will be doing millions off comparisons it will be impractical to do it with loops, my first attempt was going to take 120 yrs... I have refined it, but need to drop the loops to really improve it. I have been reading about trying to use vectorisation, I am somewhat familiar with it in R …
has comment: http://stackoverflow.com/comment/91567702
has comment: http://stackoverflow.com/comment/91564406
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: vectorization
has answer: http://stackoverflow.com/a/52308689

http://stackoverflow.com/comment/91642378
type: Comment
type: QuestionComment
has text: This is not easy to do. You'll need to have a cache of all "first-seen" instances.
score: 0
comment on: http://stackoverflow.com/q/52348454

http://stackoverflow.com/q/52286971
type: UnansweredQuestion
tagged with: machine-learning
type: Question
tagged with: logistic-regression
score: 3
has title: Regularized Logistic Regression in Python (Andrew ng Course)
has comment: http://stackoverflow.com/comment/91524636
tagged with: regularized
has body: I'm starting the ML journey and I'm having troubles with this coding exercise here is my code import numpy as np import pandas as pd import scipy.optimize as op # Read the data and give it labels data = pd.read_csv('ex2data2.txt', header=None, name['Test1', 'Test2', 'Accepted']) # Separate the features to make it fit into the mapFeature function X1 = data['Test1'].values.T X2 = data['Test2'].values.T # This function makes more features (degree) def mapFeature(x1, x2): degree = 6 out = np.ones((x1.shape[0], sum(range(degree + 2)))) curr_column = 1 for i in range(1, degree + 1): for j in range(i+1): out[:,curr_column] = np.power(x1, i-j) * np.power(x2, j) curr_column += 1 return out # Separate the data into training and target, also initialize theta X = mapFeature(X1, X2) y = np.matrix(data['Accepted'].values).T m, n = X.shape cols = X.shape[1] theta = np.matrix(np.zeros(cols)) #Initialize the learningRate(sigma) learningRate = 1 # Define the Sigmoid Function (Output between 0 and 1) def sigmoid(z): return 1 / (1 + np.exp(-z)) def cost(theta, X, y, learningRate): # This is require to make the optimize function work theta = theta.reshape(-1, 1) error = sigmoid(X @ theta) first = np.multiply(-y, np.log(error)) second = np.multiply(1 - y, np.log(1 - error)) j = np.sum((first - second)) / m + (learningRate * np.sum(np.power(theta, 2)) / 2 * m) return j # Define the gradient of the cost function def gradient(theta, X, y, learningRate): # This is require to make the optimize function work theta = theta.reshape(-1, 1) error = sigmoid(X @ theta) grad = (X.T @ (error - y)) / m + ((learningRate * theta) / m) grad_no = (X.T @ (error - y)) / m grad[0] = grad_no[0] return grad Result = op.minimize(fun=cost, x0=theta, args=(X, y, learningRate), method='TNC', jac=gradient) opt_theta = np.matrix(Result.x) def predict(theta, X): sigValue = sigmoid(X @ theta.T) p = sigValue &gt;= 0.5 return p p = predict(opt_theta, X) print('Train Accuracy: {:f}'.format(np.mean(p == y) * 100)) So, when…
has comment: http://stackoverflow.com/comment/91533851
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52293326
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91524150
has comment: http://stackoverflow.com/comment/91524735
has comment: http://stackoverflow.com/comment/91524321
has answer: http://stackoverflow.com/a/52307179
has comment: http://stackoverflow.com/comment/91524673
has comment: http://stackoverflow.com/comment/91524622
has comment: http://stackoverflow.com/comment/91524641
upvote count: 3

http://stackoverflow.com/a/52416861
upvote count: 3
type: AcceptedAnswer
type: Answer
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/52409894
accepted answer of: http://stackoverflow.com/q/52409894
has body: I found the solution. I had to delete the root dir __init__.py file. I found this answer from the famous Miguel Grinberg: https://github.com/miguelgrinberg/flasky/issues/310#issuecomment-340641813 These files (__init__.py) make python believe the main directory of the package is one directory above, so that is the directory that is added to the Python path. Usually you want your top-level directory to not be a Python package, so that the current directory goes to the path. __

http://stackoverflow.com/comment/91655275
type: QuestionComment
comment on: http://stackoverflow.com/q/52355348
has text: Welcome to SO Nick, please make sure you read https://stackoverflow.com/help/how-to-ask .
score: 0
type: Comment

twisted.conch
tag name: twisted.conch
type: Tag
tags question: http://stackoverflow.com/q/52411224

http://stackoverflow.com/comment/91800977
type: QuestionComment
type: Comment
has text: the regex answer is probably the best way to go
comment on: http://stackoverflow.com/q/52428537
score: 0

http://stackoverflow.com/comment/91541966
score: 0
type: Comment
has text: @KevinNash: you are not using the `datetime` module correctly, at any rate. I also added a `datetime.date.today()` variant in a commented-out line.
type: AnswerComment
comment on: http://stackoverflow.com/a/52296359

http://stackoverflow.com/comment/91773302
type: Comment
has text: Try with `sudo` too
type: AnswerComment
comment on: http://stackoverflow.com/a/52414163
score: 0

http://stackoverflow.com/comment/91793312
type: Comment
type: AnswerComment
has text: @Thor, It should point to the right place. This could be a bug so please open a Github issue with a minimal reproducer
comment on: http://stackoverflow.com/a/52368290
score: 0

http://stackoverflow.com/q/52291585
has comment: http://stackoverflow.com/comment/91532187
has comment: http://stackoverflow.com/comment/91533262
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have this PySide2 code which works on Linux with Python 2.7 from PySide2.QtCore import QBuffer, QByteArray ... image = self.clipboard.image() ba = QByteArray() buffer = QBuffer(ba) buffer.open(QIODevice.WriteOnly) image.save(buffer, "PNG") return bytes(buffer.data()) But on windows with Python 3.6 it fails here: File "C:\....foo.py", line 93, in image_to_png return bytes(buffer.data()) Exception: TypeError: 'bytes' object cannot be interpreted as an integer What is the most simple way to get the PNG as bytes? I would like to avoid to create a temporary file, since it is not needed for this context. (I use PySide2, but I could switch to a different python-QT binding if you think it makes more sense. Please leave a comment if you think so)
score: 0
tagged with: pyside2
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91532252
type: Question
has title: PySide2: TypeError: 'bytes' object cannot be interpreted as an integer
tagged with: pyside
has answer: http://stackoverflow.com/a/53126910
answer count: 2
tagged with: pyqt
has answer: http://stackoverflow.com/a/52293072

http://stackoverflow.com/q/52394408
tagged with: python
tagged with: selenium-chromedriver
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/65523665
has answer: http://stackoverflow.com/a/70033955
linked to: http://stackoverflow.com/q/2953834
tagged with: selenium
tagged with: google-chrome
has answer: http://stackoverflow.com/a/72489355
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/67389309
has answer: http://stackoverflow.com/a/77608668
has answer: http://stackoverflow.com/a/52396769
has answer: http://stackoverflow.com/a/71305155
has answer: http://stackoverflow.com/a/61336851
tagged with: chrome-profile
answer count: 13
has answer: http://stackoverflow.com/a/71148607
has answer: http://stackoverflow.com/a/52399027
has body: So whenever I try to use my Chrome settings (the settings I use in the default browser) by adding options = webdriver.ChromeOptions() options.add_argument("user-data-dir=C:\Users\... (my webdriver path)") driver = webdriver.Chrome(executable_path="myPath", options=options) it shows me the error code SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes n 16-17: truncated \UXXXXXXXX escape in my bash. I don't know what that means and I'd be happy for any kind of help I can get. Thanks in advance!
linked to: http://stackoverflow.com/q/49270109
has answer: http://stackoverflow.com/a/70152245
accepted answer: http://stackoverflow.com/a/52399027
upvote count: 31
has title: How to use Chrome Profile in Selenium Webdriver Python 3
has answer: http://stackoverflow.com/a/52396606
duplicate of: http://stackoverflow.com/q/2953834
score: 30
favorite count: 0
has answer: http://stackoverflow.com/a/67389309
linked to: http://stackoverflow.com/q/66705751
has answer: http://stackoverflow.com/a/70738500

http://stackoverflow.com/a/52360597
answers question: http://stackoverflow.com/q/52293389
has body: You could try saving your data as a list and dump it into a json file, given that you already imported json. z = [x for x in data1] with open('your_data.json', 'w') as out: json.dump(z,out) alternatively, you could write z = [x for x in data1] as: z = list() for x in data1: z.append(x) /ogs
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52293389

http://stackoverflow.com/comment/91764626
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52407996
type: Comment
has text: @SreeramTP Would you clarify what you mean exactly by "persistence effect"?

http://stackoverflow.com/comment/91650111
type: AnswerComment
type: Comment
score: 2
comment on: http://stackoverflow.com/a/52352487
has text: Compared to the accepted answer, this is the more natural way to solve this problem in Pandas. +1.

http://stackoverflow.com/comment/91741540
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52398767
has text: how can I use that sort above without exception?
type: AnswerComment

http://stackoverflow.com/q/52423045
type: Question
score: 0
has title: Python - use schedule module, using parameters from file
answer count: 1
has comment: http://stackoverflow.com/comment/91789276
has comment: http://stackoverflow.com/comment/91789129
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/4075190
tagged with: getattr
has body: I'm wish to use the schedule module, as shown here, in a way that code read schedule parameters from a text file, for example: start_day=1,2,3,4 start_time=09:00 module's syntax is as follows (wish to change days, and job): schedule.every().monday.do(job) schedule.every().wednesday.at("13:15").do(job) my first get was to use getattr() - but it is for a more simple uses, such as shown here Appreciate any help
has answer: http://stackoverflow.com/a/52432183

http://stackoverflow.com/comment/91598834
type: QuestionComment
comment on: http://stackoverflow.com/q/52325673
has text: @Manjo Jadhav : yes as i said when i user category.objects.filter i don't get error and see the that but why i can't use get objects or 404 .
score: 0
type: Comment

http://stackoverflow.com/comment/91663590
type: Comment
type: QuestionComment
has text: @will.fiset that looks good. I'll give it a try
comment on: http://stackoverflow.com/q/52359411
score: 0

http://stackoverflow.com/q/52300481
has comment: http://stackoverflow.com/comment/91560045
has comment: http://stackoverflow.com/comment/91548818
tagged with: mathematical-lattices
type: UnansweredQuestion
tagged with: python
tagged with: quantitative-finance
answer count: 0
has body: I am trying to construct a binomial lattice model in Python. The idea is that there are multiple binomial lattices and based on the value in particular lattice, a series of operations are performed in other lattices. These operations are similar to 'option pricing model' ( Reference to Black Scholes models) in a way that calculations start at the last column of the lattice and those are iterated to previous column one step at a time. For example, If I have a binomial lattice with n columns, 1. I calculate the values in nth column for a single or multiple lattices. 2. Based on these values, I update the values in (n-1)th column in same or other binomial lattices 3. This process continues until I reach the first column. So in short, I cannot process the calculations for all of the lattice simultaneously as value in each column depends on the values in next column and so on. From coding perspective, I have written a function that does the calculations for a particular column in a lattice and outputs the numbers that are used as input for next column in the process. def column_calc(StockPrices_col, ConvertProb_col, y_col, ContinuationValue_col, ConversionValue_col, coupon_dates_index, convert_dates_index , call_dates_index, put_dates_index, ConvertProb_col_new, ContinuationValue_col_new, y_col_new,tau, r, cs, dt,call_trigger, putPrice,callPrice): for k in range(1, n+1-tau): ConvertProb_col_new[n-k] = 0.5*(ConvertProb_col[n-1-k] + ConvertProb_col[n-k]) y_col_new[n-k] = ConvertProb_col_new[n-k]*r + (1- ConvertProb_col_new[n-k]) *(r + cs) # Calculate the holding value ContinuationValue_col_new[n-k] = 0.5*(ContinuationValue_col[n-1-k]/(1+y_col[n-1-k]*dt) + ContinuationValue_col[n-k]/(1+y_col[n-k]*dt)) # Coupon payment date if np.isin(n-1-tau, coupon_dates_index) == True: ContinuationValue_col_new[n-k] = ContinuationValue_col_new[n-k] + Principal*(1/2*c); # check put/call schedule callflag = (np.isin(n-1-tau, call_dates_index)) &amp; (StockPrices_col[n-k] &gt;= call_trigger)…
type: Question
has comment: http://stackoverflow.com/comment/91548732
tagged with: for-loop
tagged with: performance
has title: Python - faster alternative to 'for' loops
score: 0

http://stackoverflow.com/a/52322497
score: 0
answers question: http://stackoverflow.com/q/52322264
type: Answer
has body: This works on the JavaScript File Side var jsonp_url = "https://example.com/cgi-bin/data.py?varExampleForPython=" + varExample + "&amp;callback=?"; Retreiving varExamplePython in the Python (.py) File Side retrievedVarExample = params['varExampleForPython'].value

http://stackoverflow.com/comment/91530620
type: Comment
type: QuestionComment
has text: @keyko Did you delete the old migration file and re run the makemigration command ?
comment on: http://stackoverflow.com/q/52290821
score: 0

http://stackoverflow.com/q/52332733
has title: Python 3.6 tuple strange behavior?
answer count: 0
type: Question
linked to: http://stackoverflow.com/q/29747224
has comment: http://stackoverflow.com/comment/91612181
upvote count: 6
has body: Can somebody explain why does Python 3.6 behaves so strange in this piece of code? a = (1, 2, [5, 6]) a[2]+=[7, 8] print(a) Output: Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; TypeError: 'tuple' object does not support item assignment &gt;&gt;&gt;print(a) (1, 2, [5, 6, 7, 8])
score: 4
has comment: http://stackoverflow.com/comment/91612487
downvote count: 2
has comment: http://stackoverflow.com/comment/91612155
has comment: http://stackoverflow.com/comment/91612438
favorite count: 0
has comment: http://stackoverflow.com/comment/91612275
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/29747224
tagged with: python

http://stackoverflow.com/a/60290438
has comment: http://stackoverflow.com/comment/137136860
has comment: http://stackoverflow.com/comment/137032802
has comment: http://stackoverflow.com/comment/137092237
downvote count: 0
has body: Use scoped_session to avoid this: session = scoped_session(sessionmaker(bind=engine))()
answers question: http://stackoverflow.com/q/52429434
has comment: http://stackoverflow.com/comment/137086962
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/52370476
answers question: http://stackoverflow.com/q/52370396
has body: You are missing parenthesis around row def printUF(): for row in xUF: print (row) &lt;--- count=0 if count&gt;5: break count += 1
has comment: http://stackoverflow.com/comment/91685504
score: 0
has comment: http://stackoverflow.com/comment/91686880
type: Answer

http://stackoverflow.com/q/52356024
has title: python telegram bot modules (telebot)
has answer: http://stackoverflow.com/a/73031305
type: Question
downvote count: 2
score: -2
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/77918050
tagged with: python
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52356868
has body: I have written a simple example bot with telebot module but I do not know how I should fix this problem. My code is : import telebot bot = telebot.testBot("699870969:AAHth6QQWI8GR2CuCyW9V98F3CXUIA2siAw") @bot.message_handler(commands = ['start', 'help']) def send_welcome(message): bot.reply_to(message, "hesam, how are you ?") @bot.message_handler(func=lambda message: True) def echo_all(message): bot.reply_to(message, message.text) bot.polling() ERROR : the telebot module has no attribute for test bot

http://stackoverflow.com/a/52428917
answers question: http://stackoverflow.com/q/52428601
type: Answer
has body: Use np.indices with a bit of reshaping: np.indices(test.shape).reshape(2, -1).T array([[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3], [3, 0], [3, 1], [3, 2], [3, 3]])
downvote count: 0
has comment: http://stackoverflow.com/comment/126587170
score: 3
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52428601

http://stackoverflow.com/q/52367475
has title: Exporting data from Athena to Python
tagged with: amazon-athena
has answer: http://stackoverflow.com/a/52369950
favorite count: 0
score: -4
tagged with: python
downvote count: 4
type: AnsweredQuestion
upvote count: 0
has body: i am trying to export data from Athena (AWS) to Python. Or, is there a way to connect python to Athena just like there is a way to connect python to MySql. i have around 15gb data in Athena and would like to export and perform further analysis. There needs to be some way to export such a large dataset. Detailed steps would be appreciated! Thanks in adavace!
type: Question
accepted answer: http://stackoverflow.com/a/52369950
answer count: 1
tagged with: amazon-web-services

http://stackoverflow.com/comment/91821422
comment on: http://stackoverflow.com/a/52406874
type: AnswerComment
score: 0
has text: image 1-https://i.sstatic.net/2JZyH.png i image2-https://i.sstatic.net/SCzu3.png
type: Comment

http://stackoverflow.com/q/52303550
tagged with: numpy
answer count: 2
tagged with: sympy
linked to: http://stackoverflow.com/q/42867494
has body: I have an underdetermined system of linear equations. This can for example be solved by SimPy, where the solution is then a function of some free variables. What I am looking for is, which are those free variables. This set of variables is not unique but one option is enough. For example [1 0 1] [x1] = [1] [0 1 0] [x2] = [1] [x3] Here, x2 is determined by the second equation, and either x1or x3 could be used as a free variable. So for example the set {x1} is a valid solution to my problem One way of finding this is using SymPy and parsing the solutions to find which variables are used in there. This is rather cumbersome. Is there a nicer way to do this? Preferably without any symbolic computations (returning the index of the free variables). Here the same question is asked, but not answered, as it turned out the asker wanted to ask something else: How to determine which one is free variable in the result of sympy.linsolve He just wanted a single solution to the system. I want to know the free variables, and don't even need to know a solution.
favorite count: 0
linked to: http://stackoverflow.com/q/50510558
has comment: http://stackoverflow.com/comment/91555522
has comment: http://stackoverflow.com/comment/91555472
has title: Find which variables are free in underdetermined linear system
tagged with: python
possible better answer: http://stackoverflow.com/a/52304117
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52304117
downvote count: 0
score: 6
tagged with: scipy
type: Question
accepted answer: http://stackoverflow.com/a/52304099
upvote count: 6
tagged with: linear-algebra
has answer: http://stackoverflow.com/a/52304099

http://stackoverflow.com/q/52281037
has answer: http://stackoverflow.com/a/75477510
upvote count: 4
answer count: 2
tagged with: neural-network
tagged with: keras
favorite count: 0
tagged with: python
score: 2
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/91524022
has title: keras load_weights() can not load weights
has body: I want to load weights from .hdf5 file, and use load_weights(). Error doesn't occur. But when I use the model to predict. The result is the same with the model before I load weights. The load weights doesn't work. My keras version is 2.2.2 tensorflow version is 1.10.0 How can I solve this problem. Thanks
has answer: http://stackoverflow.com/a/52281484
type: Question

http://stackoverflow.com/a/52341193
has body: What you have now looks fine. But since you are asking about other ways to achieve the desired functionality: you can create a 1-dimensional boolean mask that is either True or False for each row index. Here is an example. &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.random.seed(444) &gt;&gt;&gt; shape = 15, 4 &gt;&gt;&gt; mat = np.random.randint(low=0, high=10, size=shape) &gt;&gt;&gt; mat array([[3, 0, 7, 8], [3, 4, 7, 6], [8, 9, 2, 2], [2, 0, 3, 8], [0, 6, 6, 0], [3, 0, 6, 7], [9, 3, 8, 7], [3, 2, 6, 9], [2, 9, 8, 9], [3, 2, 2, 8], [1, 5, 6, 7], [6, 0, 0, 0], [0, 4, 8, 1], [9, 8, 5, 8], [9, 4, 6, 6]]) # The thresholds for x, y, z, respectively &gt;&gt;&gt; lower = np.array([5, 5, 4]) &gt;&gt;&gt; upper = np.array([6, 6, 7]) &gt;&gt;&gt; idx = len(lower) # Parentheses are required here. NumPy boolean ops use | and &amp; # which have different operator precedence than `or` and `and` &gt;&gt;&gt; mask = np.all((mat[:, :idx] &lt; lower) | (mat[:, :idx] &gt; upper), axis=1) &gt;&gt;&gt; mask array([False, False, True, True, False, False, True, False, True, True, False, False, True, False, False]) Now indexing mat by mask will constrain it to row indices where mask is True: &gt;&gt;&gt; mat[mask] array([[8, 9, 2, 2], [2, 0, 3, 8], [9, 3, 8, 7], [2, 9, 8, 9], [3, 2, 2, 8], [0, 4, 8, 1]]) What is a bit different about this approach is that it is scalable: instead of specifying each coordinate condition individually, you can specify them in two arrays, one for the upper threshold and one for the lower, and then take advantage of NumPy's vectorization &amp; broadcasting to build the mask. np.all() says, test that all values are True, row-wise. It captures the "and" conditions from your question, while the | operator captures the "or".
type: Answer
has comment: http://stackoverflow.com/comment/91629334
answers question: http://stackoverflow.com/q/52341085
upvote count: 3
has comment: http://stackoverflow.com/comment/91629457
score: 3
accepted answer of: http://stackoverflow.com/q/52341085
has comment: http://stackoverflow.com/comment/91629357
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52359813
has answer: http://stackoverflow.com/a/52506246
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91718782
has comment: http://stackoverflow.com/comment/91695232
score: 1
tagged with: cython
upvote count: 1
has body: I am learning cython and I have modified the code in the tutorial to try to do numerical differentiation: import numpy as np cimport numpy as np import cython np.import_array() def test3(a, int order=2, int axis=-1): cdef int i if axis&lt;0: axis = len(a.shape) + axis out = np.empty(a.shape, np.double) cdef np.flatiter ita = np.PyArray_IterAllButAxis(a, &amp;axis) cdef np.flatiter ito = np.PyArray_IterAllButAxis(out, &amp;axis) cdef int a_axis_stride = a.strides[axis] cdef int o_axis_stride = out.strides[axis] cdef int axis_length = out.shape[axis] cdef double value while np.PyArray_ITER_NOTDONE(ita): # first element pt1 = &lt;double*&gt;((&lt;char*&gt;np.PyArray_ITER_DATA(ita))) pt2 = (&lt;double*&gt;((&lt;char*&gt;np.PyArray_ITER_DATA(ita)) + 1*a_axis_stride)) pt3 = (&lt;double*&gt;((&lt;char*&gt;np.PyArray_ITER_DATA(ita)) + 2*a_axis_stride)) value = -1.5*pt1[0] + 2*pt2[0] - 0.5*pt3[0] (&lt;double*&gt;((&lt;char*&gt;np.PyArray_ITER_DATA(ito))))[0] = value for i in range(axis_length-2): pt1 = (&lt;double*&gt;((&lt;char*&gt;np.PyArray_ITER_DATA(ita)) + i*a_axis_stride)) pt2 = (&lt;double*&gt;((&lt;char*&gt;np.PyArray_ITER_DATA(ita)) + (i+2)*a_axis_stride)) value = -0.5*pt1[0] + 0.5*pt2[0] (&lt;double*&gt;((&lt;char*&gt;np.PyArray_ITER_DATA(ito)) + (i+1)*o_axis_stride))[0] = value # last element pt1 = (&lt;double*&gt;((&lt;char*&gt;np.PyArray_ITER_DATA(ita))+ (axis_length-3)*a_axis_stride)) pt2 = (&lt;double*&gt;((&lt;char*&gt;np.PyArray_ITER_DATA(ita))+ (axis_length-2)*a_axis_stride)) pt3 = (&lt;double*&gt;((&lt;char*&gt;np.PyArray_ITER_DATA(ita))+ (axis_length-1)*a_axis_stride)) value = 1.5*pt3[0] - 2*pt2[0] + 0.5*pt1[0] (&lt;double*&gt;((&lt;char*&gt;np.PyArray_ITER_DATA(ito))+(axis_length-1)*o_axis_stride))[0] = value np.PyArray_ITER_NEXT(ita) np.PyArray_ITER_NEXT(ito) return out The code produces correct results, and it is indeed faster than my own numpy implementation without cython. The problem is the following: I thought about only having one pt1 = (&lt;doubl…
type: Question
tagged with: numpy
tagged with: iterator
accepted answer: http://stackoverflow.com/a/52506246
has comment: http://stackoverflow.com/comment/91707010
downvote count: 0
tagged with: pointers
answer count: 1
has title: iterating through specified axis in cython
favorite count: 0
tagged with: python

http://stackoverflow.com/q/52402239
accepted answer: http://stackoverflow.com/a/52403878
favorite count: 0
has answer: http://stackoverflow.com/a/52403878
has title: calling python.py from C# .net
tagged with: process
tagged with: python
score: 2
has body: I have a problem in calling a python script from C#. My python script computes a value based on param 1 and param 2 and sends the computed value. I am not able to get the computed value. say, for example I am taking a simple python class and calling for C# the below is python.py : import argparse class demo: def add(self,a,b): return a+b def main(a,b): obj=demo() value=obj.add(a,b) print(value) return value if __name__ == "__main__": arg_parse = argparse.ArgumentParser() arg_parse.add_argument("a") arguments = arg_parse.parse_args() main(arguments.a,3) below is the C# code to call it. Process p = new Process(); int a = 2; p.StartInfo.FileName = "C:\\Users\\xyx\\AppData\\Local\\Programs\\Python\\Python36-32\\pythonw\\python.exe"; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; p.StartInfo.Arguments = "C:\\Users\\xyx\\AppData\\Local\\Programs\\Python\\Python36-32\\pythonw\\python.py "+a; parameter p.Start(); StreamReader s = p.StandardOutput; standardError = s.ReadToEnd(); output = s.ReadToEnd().Replace(Environment.NewLine, string.Empty); p.WaitForExit(); Since 2,3 are sent to main () in python, I want '5'back. I do not know how to get it back. Please help
type: AnsweredQuestion
downvote count: 0
type: Question
upvote count: 2
tagged with: c#
answer count: 1

http://stackoverflow.com/a/52326191
has body: i have solve the question,this is different from Merge Two Binary Trees with node sum def initial_node(name, cart=0, visit_cnt=1, goods_id='-1', depths=0, order_index=1, parent=None, pr=0): node = Node(name=name, cart=cart, visit_cnt=visit_cnt, back_cnt=0, goodsid=goods_id, depths=depths, sons_cnt=0, order_index=order_index, parent=parent, pr=pr) current_Node = node return current_Node def list_extend(l1, l2): len1 = len(l1) len2 = len(l2) if len1 == len2: pass elif len1 &gt; len2: l2.extend([None] * (len1 - len2)) else: l1.extend([None] * (len2 - len1)) return l1, l2 def tree_merge(node1, node2): res = None if node1 is None: res = node2 res.goodsid = '-1' res.name = str(node2.depths) + '-' + str(node2.order_index) res.parent=node2.parent return res if node2 is None: res = node1 res.goodsid = '-1' res.name = str(node1.depths) + '-' + str(node1.order_index) res.parent=node1.parent return res res=node1 res.cart += node2.cart res.visit_cnt += node2.visit_cnt res.goodsid = '-1' children_1 = list(node1.children) children_2 = list(node2.children) children_1,children_2=list_extend(children_1,children_2) tmp_children=[] for i,j in zip(children_1,children_2): tmp_children.append(tree_merge(i,j)) res.children=tmp_children return res this is for multiway tree merge with node value sum
answers question: http://stackoverflow.com/q/52288445
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52288445
score: 1
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/52336044
has body: You tagged pandas, so create a dataframe from the sample: sample = ["abc","def","ade", "acf", "bal"] df = pd.DataFrame() df['sample'] = sample Then groupby using the first letter of the string and count: df.groupby(df['sample'].str[0]).count() use this dataframe as you see fit.
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52335866
type: Answer

http://stackoverflow.com/q/52280499
has body: I am trying to update a value to "True" using different column arrays for each row. I have an all False Dataframe: Place1 Place2 ... PlaceN Id1 False False ... False Id2 False False ... False . . . IdN False False ... False An a Series with a list of places for each Id: Id1 [Place1, Place2] Id2 [Place4, Place54, PlaceN] . . . IdN [Place1] What I need is to change the value in column Place1 and Place2 for Id1 in the DataFrame to True. Currently I have a working code using a loop for id, row in df.iterrows(): df.loc[id]=row[series[id]]=True But it is way too slow for over 60k ids and 150 places. I need it to do it in the time I read a news article instead of the hours that it is right now. I have tried other methods such as apply but lambda functions do not allow for assignments. Having a series a well structured series of the columns for each row it felt like there should be a vectorized way of indexing the array of columns. But I have not found it. Thank you in advance for the help!
duplicate of: http://stackoverflow.com/q/45312377
type: Question
has answer: http://stackoverflow.com/a/52280635
has title: Python - Updating values for different Array columns (Speed Improvement)
answer count: 1
tagged with: arrays
downvote count: 0
favorite count: 0
tagged with: pandas
tagged with: python
type: UnansweredQuestion
upvote count: 1
tagged with: indexing
linked to: http://stackoverflow.com/q/45312377
has comment: http://stackoverflow.com/comment/91527314
tagged with: performance
score: 1

http://stackoverflow.com/q/52380849
has comment: http://stackoverflow.com/comment/91706199
tagged with: python
has body: I'm trying to get the Choice details but the page isn't rendering. Here is link to project: https://github.com/tsuryaa/my_project
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52381133
tagged with: django
has title: Page not found at polls/1/details in Django-2.1
has comment: http://stackoverflow.com/comment/91706139
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91706229
has answer: http://stackoverflow.com/a/52381229
type: Question

http://stackoverflow.com/a/52339145
has body: You can define and use a backend function for this purpose: from keras import backend as K # my_layer could be a layer from a previously built model, like: # my_layer = model.layers[3] func = K.function(model.inputs, [my_layer.output]) # or it is a layer with customized weights, like: # my_layer = Dense(...) # my_layer.set_weights(...) # out = my_layer(input_data) input_data = Input(shape=...) func = K.function([input_data], [my_layer.output]) # to use the function: layer_output = func(layer_input) # layer_input is a list of numpy array(s)
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52338033
type: Answer
answers question: http://stackoverflow.com/q/52338033

http://stackoverflow.com/q/52412657
has comment: http://stackoverflow.com/comment/91769421
has comment: http://stackoverflow.com/comment/91773877
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91769600
has answer: http://stackoverflow.com/a/52413034
type: Question
tagged with: quantitative-finance
tagged with: numpy
has body: In finance, conducting investment research on futures strategies can be complex. A future, in its simplest form, a is an agreement between two parties: one who holds a short position – the party who agrees to deliver a commodity; and one who holds a long position – the party who agrees to receive a commodity. Here is a DataFrame of what my data on futures look like. I use a multi-index structure to store it, where the outer value is an underlier (f.e. SP is the S&amp;P500), and the inner value is a daily timestamp, containing data on the contract that traded on that day: dataPoint RIC ExpirationDate Exchange Description Open Low High Last Settlement Price Ask Bid Volume OpenInterest BlockVolume TotalVolume2 SecurityDescription SecurityLongDescription RICRoot closingDate SP 2018-03-15 0 SPH0 2020-03-20 CME:Index and Options Market NaN NaN NaN NaN 2811.20 NaN NaN 0 NaN NaN NaN SP500 IDX MAR0 NaN 2018-03-16 1 SPH0 2020-03-20 CME:Index and Options Market NaN 2,812.20 2,817.20 NaN 2812.30 NaN NaN 0 NaN NaN NaN SP500 IDX MAR0 NaN 2018-03-19 2 SPH0 2020-03-20 CME:Index and Options Market NaN 2,753.30 2,772.30 NaN 2778.90 NaN NaN 0 NaN NaN NaN SP500 IDX MAR0 NaN 2018-03-20 3 SPH0 2020-03-20 CME:Index and Options Market NaN 2,770.90 2,782.90 NaN 2779.20 NaN NaN 0 NaN NaN NaN SP500 IDX MAR0 NaN 2018-03-21 4 SPH0 2020-03-20 CME:Index and Options Market NaN 2,770.20 2,796.20 NaN 2774.10 NaN NaN 0 NaN NaN NaN SP500 IDX MAR0 NaN 2018-03-22 5 SPH0 2020-03-20 CME:Index and Options Market 2727.1 2,699.10 2,743.10 NaN 2700.60 NaN NaN 0 NaN NaN NaN SP500 IDX MAR0 NaN 2018-03-23 6 SPH0 2020-03-20 CME:Index and Options Market NaN 2,650.60 2,712.60 NaN 2655.40 NaN NaN 0 NaN NaN NaN SP500 IDX MAR0 NaN 2018-03-26 7 SPH0 2020-03-20 CME:Index and Options Market NaN 2,663.40 2,719.40 NaN 2716.30 NaN NaN 0 NaN NaN NaN SP500 IDX MAR0 NaN 2018-03-27 8 SPH0 2020-03-20 CME:Index and Options Market NaN 2,654.30 2,727.30 NaN 2673.00 NaN NaN 0 NaN NaN NaN SP500 IDX MAR0 NaN 2018-03-28 9 SPH0 2020-03-…
answer count: 1
accepted answer: http://stackoverflow.com/a/52413034
has comment: http://stackoverflow.com/comment/91769340
favorite count: 0
score: 0
tagged with: pandas
tagged with: finance
tagged with: python
has title: efficiently finding a front-month contract on futures data in pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91784683

http://stackoverflow.com/q/52299420
has body: Every once in a while, I get to manipulate a csr_matrix but I always forget how the parameters indices and indptr work together to build a sparse matrix. I am looking for a clear and intuitive explanation on how the indptr interacts with both the data and indices parameters when defining a sparse matrix using the notation csr_matrix((data, indices, indptr), [shape=(M, N)]). I can see from the scipy documentation that the data parameter contains all the non-zero data, and the indices parameter contains the columns associated to that data (as such, indices is equal to col in the example given in the documentation). But how can we explain in clear terms the indptr parameter?
has answer: http://stackoverflow.com/a/70306169
has answer: http://stackoverflow.com/a/52299730
downvote count: 0
tagged with: sparse-matrix
has answer: http://stackoverflow.com/a/55920574
has answer: http://stackoverflow.com/a/76168289
possible better answer: http://stackoverflow.com/a/70306169
has comment: http://stackoverflow.com/comment/131124996
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91547667
upvote count: 58
tagged with: python
has answer: http://stackoverflow.com/a/63342110
favorite count: 0
has answer: http://stackoverflow.com/a/73930127
accepted answer: http://stackoverflow.com/a/52299730
has title: scipy csr_matrix: understand indptr
has answer: http://stackoverflow.com/a/67276790
tagged with: scipy
answer count: 7
score: 58

http://stackoverflow.com/a/52445870
has body: I solved this by inserting the host ip of the container: 172.17.0.2 into the connection string as such: 'postgresql://postgres:mysecretpasswd@172.17.0.2/raw_data' Which in combination with a function solved my problem: def db_create(engine_url, dataframe): """ Check if postgres db exists, if not creates it """ engine = create_engine(engine_url) if not database_exists(engine.url): print("Database does not exist, creating...") create_database(engine.url) print("Does it exist now?", database_exists(engine.url)) if database_exists(engine.url): data_type = str(engine.url).rsplit('/', 1)[1] print('Populating database with', data_type) dataframe.to_sql(data_type, engine) db_create('postgresql://postgres:mysecretpasswd@172.17.0.2/raw_data') will create a database called raw_data with a table called raw_data, and populate it with the target Pandas data frame.
accepted answer of: http://stackoverflow.com/q/52419849
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52419849
has comment: http://stackoverflow.com/comment/129396687
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/q/52410068
tagged with: web-scraping
tagged with: python
accepted answer: http://stackoverflow.com/a/52415005
has comment: http://stackoverflow.com/comment/91765754
type: AnsweredQuestion
tagged with: scrapy
type: Question
has title: convert nested json to dict
has body: Im trying to send the Json below with Scrapy { "version": 1, "message_type": 104, "message_id": 14, "body": [ { "message_type": 104, "chat_message": { "mssg": "hello", "message_type": 1, "uid": "15373703487091", "from_person_id": "5134266921", "to_person_id": "3093543561", "read": false } } ], "is_background": false } I've tried to send it hard coded like this self.postRequest = {"version":"1", "message_type":"104", "message_id":"18", "body":"[{'message_type':'104','chat_message':{'mssg':'hello','message_type':'1','uid':'15372201045381','from_person_id':'5134266921','to_person_id':'3093543561','read':'false'}}]", "is_background":"false"} yield FormRequest(url=response.url , formdata=self.postRequest, callback=self.parse_data,dont_filter=True, headers=self.params, cookies=self.cookies) i get HTTP 200 status with an error message : Unknown command server_unknown_action. so i dont know if i did something wrong with the json structure or the error is elsewhere
has comment: http://stackoverflow.com/comment/91766142
score: 0
has comment: http://stackoverflow.com/comment/91766034
answer count: 1
has answer: http://stackoverflow.com/a/52415005

http://stackoverflow.com/comment/91707229
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52373458
has text: `(?s)` enables `DOTALL` mode to enable dot match newlines as well.

http://stackoverflow.com/q/52413470
type: AnsweredQuestion
tagged with: list
score: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52413499
has comment: http://stackoverflow.com/comment/91770743
has title: find a piece of a string in a list and replace
answer count: 3
possible better answer: http://stackoverflow.com/a/52413650
accepted answer: http://stackoverflow.com/a/52413499
has answer: http://stackoverflow.com/a/52413650
favorite count: 0
has body: I've come across posts that demonstrate how to find a string in a list and replace, but i'm having difficulty generalizing the search to only a piece of a string. For example listX = ['color green', 'shape circle', 'above t'] I'd like to find all strings that begin with 'above', i've been able to do some minimal searching of a list using any and leaving the following space 'above ' but I can't figure out how to replace what I find. Output i'm trying to create would be: ['color green', 'shape circle', 'above'] I'd also like to figure out how to remove a string that begins with 'above' from the list all together.
has answer: http://stackoverflow.com/a/52413692
upvote count: 2
tagged with: python

http://stackoverflow.com/comment/91826461
comment on: http://stackoverflow.com/a/52424803
type: AnswerComment
score: 0
type: Comment
has text: then u should search that record id from specific model using commercial_group.text

http://stackoverflow.com/comment/91759252
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52369031
has text: What if I have this `030~01~The sign ~ is great~2017` If BELNR is a text field and someone used the delimiter sign in this text field. With `error_bad_lines=True` pandas would skip this line, but what would happen with you wrapper? Would the wrapper try to combine more lines in order to reach the delimiter count?
score: 0

http://stackoverflow.com/q/52283346
tagged with: dask
has comment: http://stackoverflow.com/comment/91515107
type: Question
has comment: http://stackoverflow.com/comment/91515981
has comment: http://stackoverflow.com/comment/91516830
accepted answer: http://stackoverflow.com/a/52284545
tagged with: python
tagged with: parallel-processing
upvote count: 3
answer count: 1
has title: Using dask.bag vs normal python list?
has body: When I run this parallel dask.bag code below, I seem to get much slower computation than the sequential Python code. Any insights into why? import dask.bag as db def is_even(x): return not x % 2 Dask code: %%timeit b = db.from_sequence(range(2000000)) c = b.filter(is_even).map(lambda x: x ** 2) c.compute() &gt;&gt;&gt; 12.8 s ± 1.15 s per loop (mean ± std. dev. of 7 runs, 1 loop each) # With n = 8000000 &gt;&gt;&gt; 50.7 s ± 2.76 s per loop (mean ± std. dev. of 7 runs, 1 loop each) Python code: %%timeit b = list(range(2000000)) b = list(filter(is_even, b)) b = list(map(lambda x: x ** 2, b)) &gt;&gt;&gt; 547 ms ± 8.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # With n = 8000000 &gt;&gt;&gt; 2.25 s ± 102 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
has answer: http://stackoverflow.com/a/52284545
has comment: http://stackoverflow.com/comment/91516760
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/91515391
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/52396634
tagged with: pycharm
type: Question
has comment: http://stackoverflow.com/comment/91738715
tagged with: python
answer count: 1
has title: How to remove ... when print out and print out the full sentences in the console of Pycharm?
linked to: http://stackoverflow.com/q/7836313
score: 0
tagged with: dataframe
tagged with: numpy
type: UnansweredQuestion
tagged with: pandas
has body: The below shown is the output console in pycharm. I would like to show a long sentence print out but it gives me ... notes 0 {'Notes': "85 Male Malay NKDA walking stick a... 1 {'Notes': '85yo chinese man nkda PHX 1) Hypert... This is the codes I used to achieved the print out: pd.set_option('display.width', 100000) pd.set_option('display.max_rows', 5000, 'display.max_columns', 500) df = pd.DataFrame(np.array(c3), columns=["notes"]).drop_duplicates() print(df)
has answer: http://stackoverflow.com/a/52396702

http://stackoverflow.com/a/52351581
has comment: http://stackoverflow.com/comment/91648839
has comment: http://stackoverflow.com/comment/91648781
has comment: http://stackoverflow.com/comment/91648696
type: Answer
has comment: http://stackoverflow.com/comment/91648432
has body: If you wish to find all links without trying it manually in Beautifulsoup. Then go for requests-html Sample code to grab all links, from requests_html import HTMLSession from bs4 import BeautifulSoup url = 'https://society6.com/discover' session = HTMLSession(mock_browser=True) r = session.get(url, headers={'User-Agent': 'Mozilla/5.0'}) print(r.html.links) print(r.html.absolute_links) soup = BeautifulSoup(r.html.raw_html, 'html.parser') a_tags = soup.find_all("a", attrs={"class": "author track"}) for a_tag in a_tags: print(a_tag['href'])
has comment: http://stackoverflow.com/comment/91648655
has comment: http://stackoverflow.com/comment/91648579
score: 0
answers question: http://stackoverflow.com/q/52345850
has comment: http://stackoverflow.com/comment/91648555

http://stackoverflow.com/comment/91694830
type: Comment
comment on: http://stackoverflow.com/a/52374588
score: 1
type: AnswerComment
has text: @Olivier Melançon, thanks a lot!! It's works as needed.

http://stackoverflow.com/q/52409203
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91762761
favorite count: 0
has title: Python selenium how to get only paragraphs with text
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52411889
has comment: http://stackoverflow.com/comment/91762490
tagged with: selenium
downvote count: 1
has body: Imagine I have such html: Sometext More text Using selenium, is there a way to get only paragraphs which contain text? In example it will be the first and the fourth paragraphs..
type: Question
score: -1

http://stackoverflow.com/comment/91782809
score: 0
has text: The log file shows the same error message again, except one line: Between line one and two comes this entry: Getting page https://pypi.python.org/simple/flask/
comment on: http://stackoverflow.com/q/52419481
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52353056
has comment: http://stackoverflow.com/comment/91651782
has body: I am creating a environment.yml file for the creation of a custom environment. One of the package (which I install via pip) requires an environment variable to be set (namely MACOSX_DEPLOYMENT_TARGET=10.7 in order to make gcc happy). How can I do that? name: mypy27 channels: # Default distribution from Continuum/Anaconda - defaults # Conda forge distribution # https://conda-forge.org - conda-forge dependencies: - python=2.7 - anaconda - pip: - rootnumpy - git+https://mypackage.git#egg=mypackage The key is to set the environment variable before rootnumpy installation is started.
favorite count: 0
linked to: http://stackoverflow.com/q/7501678
tagged with: python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/91651401
has title: Conda: specify environment variable before creating env from YAML file
type: Question
linked to: http://stackoverflow.com/q/31598963
has answer: http://stackoverflow.com/a/65438057
accepted answer: http://stackoverflow.com/a/65438057
tagged with: conda
upvote count: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/91515912
has text: Using BS is a requirement. The extraction of names from the link is not required (using regex or by any other means). And thank you Daniel for your explanation about the nested lists. I can see that now.
type: QuestionComment
comment on: http://stackoverflow.com/q/52283259
score: 0
type: Comment

http://stackoverflow.com/q/52397832
has comment: http://stackoverflow.com/comment/91740045
has comment: http://stackoverflow.com/comment/91740118
has title: Figuring out money change in python
has comment: http://stackoverflow.com/comment/91739914
has answer: http://stackoverflow.com/a/68867022
tagged with: python
has answer: http://stackoverflow.com/a/62064067
has comment: http://stackoverflow.com/comment/91740052
type: UnansweredQuestion
score: -4
has answer: http://stackoverflow.com/a/52415083
has body: I have an assignment where I have to prompt the user for cost of a product and amount paid, I have to output change in pennies, dimes, quarters, $1, $5, $20, $50, and $100, for example: The cost of the item is $19.99 and the client pays with a $50 bill. The change to be provided is 1 $20 bill, one $10 bill, and one penny. I am confused how to get an output like that though, any help would be greatly appreciated, heres what I have so far cost = float(input('Cost: ')) amount_paid = float(input('Amount paid: ')) penny = 0.01 dime = 0.10 quarter = 0.25 dollar_1 = 1.00 dollar_5 = 5.00 dollar_10 = 10.00 dollar_20 = 20.00 dollar_50 = 50.00 dollar_100 = 100.00 change = cost - amount_paid if amount_paid &lt; cost: print('Error') I dont know what to do next
type: Question
upvote count: 1
has answer: http://stackoverflow.com/a/52397970
has answer: http://stackoverflow.com/a/52397969
favorite count: 0
tagged with: currency
has comment: http://stackoverflow.com/comment/91739962
answer count: 5
downvote count: 5

http://stackoverflow.com/comment/127441843
score: 0
type: Comment
type: AnswerComment
has text: That "silently fail" part is extra important to note. Also monitor your output sizes to see if frames are being added.
comment on: http://stackoverflow.com/a/52414149

http://stackoverflow.com/comment/91648534
score: 1
comment on: http://stackoverflow.com/q/52351616
has text: Upgrade to 0.23.4. There was a bug regarding this parameter.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91778809
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52417785
has text: but if the line contains `line = 'AirPortFamily-1425.9` ,it should not match it...it should only match the lines that contain `:`

http://stackoverflow.com/comment/138931099
comment on: http://stackoverflow.com/a/52297788
score: 0
type: Comment
has text: What if the filter's funtions I'm using doesn't have any parameters for "na=False"? I´m trying to filter a dataframe on a column's values are not numeric values and get the same error posted because it countains one nan value. My filter: df[~df['column'].str.isnumeric()])
type: AnswerComment

http://stackoverflow.com/q/52298118
type: Question
has comment: http://stackoverflow.com/comment/91565087
has answer: http://stackoverflow.com/a/52407893
has body: I need to save once and load multiples times some big arrays in a flask application with Python 3. I originally stored these arrays on disk with the json library. In order to speed up this, I used Redis on the same machine to store the array by serializing the array in a JSON string. I wonder why I get no improvement (actually it takes more time on the server I use) whereas Redis keeps data in RAM. I guess the JSON serialization isn't optimize but I have no clue how I could speed up this: import json import redis import os import time current_folder = os.path.dirname(os.path.abspath(__file__)) file_path = os.path.join(current_folder, "my_file") my_array = [1]*10000000 with open(file_path, 'w') as outfile: json.dump(my_array, outfile) start_time = time.time() with open(file_path, 'r') as infile: my_array = json.load(infile) print("JSON from disk : ", time.time() - start_time) r = redis.Redis() my_array_as_string = json.dumps(my_array) r.set("my_array_as_string", my_array_as_string) start_time = time.time() my_array_as_string = r.get("my_array_as_string") print("Fetch from Redis:", time.time() - start_time) start_time = time.time() my_array = json.loads(my_array_as_string) print("Parse JSON :", time.time() - start_time) Result: JSON from disk : 1.075700044631958 Fetch from Redis: 0.078125 Parse JSON : 1.0247752666473389 EDIT: it seems that fetching from redis is actually fast, but the JSON parsing is quite slow. Is there a way to fetch directly an array from Redis without the JSON serialization part ? This is what we do with pyMySQL and it is fast.
accepted answer: http://stackoverflow.com/a/52367798
downvote count: 0
tagged with: database
answer count: 3
has comment: http://stackoverflow.com/comment/91679163
has title: Fastest way to keep data in memory with Redis in Python
has comment: http://stackoverflow.com/comment/91679394
has answer: http://stackoverflow.com/a/56177046
favorite count: 0
has comment: http://stackoverflow.com/comment/91566411
tagged with: redis
has comment: http://stackoverflow.com/comment/91679903
has comment: http://stackoverflow.com/comment/91564910
tagged with: python
upvote count: 7
has answer: http://stackoverflow.com/a/52367798
has comment: http://stackoverflow.com/comment/91563815
has comment: http://stackoverflow.com/comment/91564453
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91565669
tagged with: performance
linked to: http://stackoverflow.com/q/11610180
score: 7
possible better answer: http://stackoverflow.com/a/52407893

http://stackoverflow.com/q/52285681
answer count: 3
tagged with: python
has body: I am writing a program for counting the approximate number of words in the file and getting an error stating 'ascii' codec can't decode byte. How can I eliminate this error? Below is the traceback of above error: Traceback (most recent call last): File "/Users/NikolaMac/Desktop/alice.py", line 23, in &lt;module&gt; contents = f_obj.read() File "/Library/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 0xef in position 0: ordinal not in range(128)" Here is my code: filename='alice.txt' try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + " does not exist." print(msg) else: # Count the approximate number of words in the file. words = contents.split() num_words = len(words) print("The file " + filename + " has about " + str(num_words) + " words.")
has answer: http://stackoverflow.com/a/52287784
has answer: http://stackoverflow.com/a/52286199
type: UnansweredQuestion
has title: How to solve "UnicodeDecodeError: 'ascii' codec can't decode byte"
type: Question
has comment: http://stackoverflow.com/comment/91520492
has answer: http://stackoverflow.com/a/52286811
score: 0

http://stackoverflow.com/q/52310741
has answer: http://stackoverflow.com/a/52311000
has comment: http://stackoverflow.com/comment/91568442
tagged with: list
has answer: http://stackoverflow.com/a/52310845
possible better answer: http://stackoverflow.com/a/52311000
has answer: http://stackoverflow.com/a/52311509
has title: How do I append a list with sublists inside of it?
has answer: http://stackoverflow.com/a/52310985
has body: All I need to do is to create 1 list with all these values without sublists. example = ['a', ['c', 1, 3], ['f', 7, [4, '4']], [{'lalala': 111}]] newArray = [] def func(array): for i in array: for z in i: newArray.append(z) print(func(example)) The result here would be: ['a', 'c', 1, 3, 'f', 7, [4, '4'], {'lalala': 111}]. When I add 3rd for it would say that 'int' object is not iterable. Do I need somehow check whether the item is int or string and then skip them? Or am I missing something? P.S. I believe this is done with the recursive functions, but I have no clue about them :(
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52311192
downvote count: 0
score: 1
favorite count: 0
type: Question
answer count: 5
accepted answer: http://stackoverflow.com/a/52310985
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/91758520
type: Comment
type: QuestionComment
has text: It works good to me. I got TOM Dick DICK Harry Hello
comment on: http://stackoverflow.com/q/52407318
score: 0

http://stackoverflow.com/comment/96703159
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52274464
has text: `print u.decode('unicode-escape')` -> `ნათია`

http://stackoverflow.com/q/52292099
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
has body: this question has come up a lot of times, but unfortunatelly none of them was my case but one (at first). How to use pyInstaller to completely pack all the necessary Library? I have written a script in Python using multiple libraries, one of them being the webbot module. I managed to convert my script to an .exe file but when I tried to run the .exe the following error came up: Traceback (most recent call last): File "TM.py", line 132, in &lt;module&gt; File "site-packages\webbot\webbot.py", line 45, in __init__ FileNotFoundError: [WinError 3]The system could not find the path... Then I followed the instructions in the above link. Then I got the following error message: Traceback (most recent call last): File "TM3.py", line 12, in &lt;module&gt; AttributeError: module 'webbot' has no attribute 'data' [9292] Failed to execute script TM3 Where line 12 is: webbot.data.path.append(r'webbot_master_data') Could someone help me over here? Thanks in advance Using: Windows: 10 PyInstaller: 3.4 Python: 3.6.5
linked to: http://stackoverflow.com/q/37144170
tagged with: attributeerror
type: Question
answer count: 1
has title: pyinstaller: AttributeError module 'webbot' has no attribute 'data'
has answer: http://stackoverflow.com/a/53250157
score: 0
tagged with: pyinstaller

http://stackoverflow.com/a/52447989
score: 0
has comment: http://stackoverflow.com/comment/91848683
type: Answer
has body: Try it: import sys from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets import QLineEdit from PyQt5.QtWidgets import QPushButton from PyQt5.QtWidgets import QVBoxLayout, QTableView, QAbstractItemView,QLabel,QLineEdit,QTextEdit,QGridLayout from PyQt5.QtWidgets import QWidget from PyQt5 import QtSql,QtWidgets,QtGui,QtCore import sqlite3 as mdb class sqlite_conect(object): def sqlite_conect(self, find_text, find_function): self.connection = mdb.connect('imenik.db') self.cursor = self.connection.cursor() self.find_text1 = "%" + find_text + "%" db = QtSql.QSqlDatabase.addDatabase("SQLITE3"); ok = db.open() def createConnection(): db = QtSql.QSqlDatabase.addDatabase("QSQLITE") db.setDatabaseName("imenik.db") if not db.open(): QtWidgets.QMessageBox.critical(None, "Cannot open database", "Unable to establish a database connection.\n" "This example needs SQLite support. Please read " "the Qt SQL driver documentation for information how " "to build it.\n\n" "Click Cancel to exit.", QtWidgets.QMessageBox.Cancel) return False return True class Glavni_prozor(QWidget): def __init__(self): super(Glavni_prozor, self).__init__() self.setFixedSize(1024, 768) self.edit_window = edit_window(self) layout = QVBoxLayout(self) self.tabelaEditovanje = QTableView() self.tabelaEditovanje.setGeometry(50, 50, 300, 200) self.tabelaEditovanje.setSelectionMode(QAbstractItemView.SingleSelection) self.tabelaEditovanje.setSelectionBehavior(QAbstractItemView.SelectRows) self.tabelaEditovanje.doubleClicked.connect(self.select_id) self.tabelaEditovanje.doubleClicked.connect(self.prikazi_drugi) layout.addWidget(self.tabelaEditovanje) # pravi promjenjivu za pretragu baze podataka self.model = QtSql.QSqlQueryModel() ## --- ##self.model.setQuery("SELECT Lokacija,Kancelarija,Prezime,Ime,Telefon,Lokal,Fax,Oblast FROM telImenik") # +++ id, !!! self.model.setQuery("""SELECT id, Lokacija, Kancelarija, Prezime, Ime, Telefon, Lokal, Fax, Oblast FROM telImenik""") # upisuj…
answers question: http://stackoverflow.com/q/52368510
accepted answer of: http://stackoverflow.com/q/52368510
type: AcceptedAnswer

http://stackoverflow.com/comment/91721747
score: 0
type: QuestionComment
type: Comment
has text: id might not be unique. the same person could be listed a few times. Each dataframe does have the same # of rows
comment on: http://stackoverflow.com/q/52388194

http://stackoverflow.com/comment/137688345
type: AnswerComment
comment on: http://stackoverflow.com/a/52299730
type: Comment
score: 1
has text: Amazing answer. Super helpful buddy!

http://stackoverflow.com/a/61606295
answers question: http://stackoverflow.com/q/52278686
has body: Not sure if I'm answering too late. My understanding is you got a string buffer of raw address and you want to dump it in human convention to stdout. Unfortunately python doesn't have very good handling of hex formatting. One way of doing it is to convert the raw value into proper Python int and formatting it using %x and manually prepend 0x at the front. Sample code follows import struct hex_string = "\xad\x07\x40\x00" v, = struct.unpack('&lt;I', hex_string) print ('0x' + '%08x' % v)
score: 0
type: Answer

http://stackoverflow.com/q/52393679
has answer: http://stackoverflow.com/a/52402261
tagged with: python
type: AnsweredQuestion
has title: Handle keyboard interruption and file writing
has body: I have an application which monitors some data from web and write files almost every second. This application runs 24/7, but sometimes I have to turn it off. I use a keyboard interrupt exception to stop the app when I want, but once in a while the application does not finish the file writing and I got a corrupted file. What make me fix the file so as to get the app working properly when I turn it on again. This is a piece of the code: while True: try: conns = [http.client.HTTPSConnection(C.REQUEST_HOST) for k in range(C.num_coins)] for k in range(C.num_coins): conns[k].request("GET", C.REQUEST_PATH_TICKER.format(C.coin_types[k])) responses = [conns[k].getresponse().read() for k in range(C.num_coins)] responses_json_new = [ json.loads(responses[k].decode(), object_pairs_hook=OrderedDict) for k in range(C.num_coins) ] responses_json_new = [responses_json_new[k]["ticker"] for k in range(C.num_coins)] for k in range(C.num_coins): if responses_json_new[k]["last"] != responses_json_old[k]["last"]: date_ticker = datetime.datetime.fromtimestamp( int(responses_json_new[k]["date"]) ).strftime("%Y-%m-%d") with open(files_path[k] + date_ticker + ".json", "a") as f: json.dump(responses_json_new[k], f) f.write("\n") responses_json_old[k] = responses_json_new[k] print( out.format( C.coin_types[k], float(responses_json_new[k]["vol"]), float(responses_json_new[k]["last"]), datetime.datetime.fromtimestamp( responses_json_new[k]["date"] ).strftime("%Y-%m-%d %H:%M:%S"), ) ) currentDate, files_path = updateFilePath(currentDate, files_path) time.sleep(1) except KeyboardInterrupt: print("\nInterrupted!\n") for k in range(C.num_coins): if conns[k]: conns[k].close() sys.exit() except Exception as e: print("\nERROR:", sys.exc_info()[0]) ut.exception_log(e, traceback.format_exc()) ut.close_waiting(conns, wait=30) continue finally: for k in range(C.num_coins): if conns[k]: conns[k].close() I need some suggestions on how can I handle this. Thanks all!
has comment: http://stackoverflow.com/comment/91748272
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91732578
answer count: 1
accepted answer: http://stackoverflow.com/a/52402261
has comment: http://stackoverflow.com/comment/91733029
has comment: http://stackoverflow.com/comment/91732979

http://stackoverflow.com/q/52428301
has comment: http://stackoverflow.com/comment/91800297
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91800946
has comment: http://stackoverflow.com/comment/91800810
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91800435
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91801007
has answer: http://stackoverflow.com/a/52430941
answer count: 1
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/91800877
tagged with: python
has body: Following is the dataframe I have. JourneyGroup is my expected column. Day Journey InitialValue Value JourneyGroup 0 12 1 3.0 4 1 1 12 1 4.0 5 1 2 12 0 NaN 7 1 3 12 0 NaN 2 1 4 12 1 5.0 8 2 5 12 0 NaN 9 2 6 13 1 3.0 4 3 7 13 1 4.0 5 3 8 13 0 NaN 7 3 9 13 0 NaN 6 3 10 13 1 1.0 2 3 11 13 0 NaN 9 0 If Journey == 1, that indicates the beginning of a journey. As long as a Journey is ON, no other Journey can start in the same Day in the subsequent rows. A Journey will end if current row Value &lt; InitialValue(from the first row of a journey). Once a start and end is identified for a Journey, a group number is assigned in JourneyGroup grouped by Day. For example, in the first row, Journey ==1, then the Journey starts. In the second row, it is also Journey==1, but a Journey is already ON from the first row, so as of 2nd row, it is just the continuation of the first Journey from the 1st row. On the 4th row, Value of 2 &lt; InitialValue of 3, which marks the end of the Journey and JourneyGroup of 1 is assigned. I can use ngroup or pd.categorical to assign groups and check condition by doing something like: df.Value&lt;df.groupby(['Group??']).InitialValue.transform('first') but not sure how to iteratively put together the concepts while keeping memory on whether a Journey is ON or OFF. N.B:- A Journey cannot span multiple days and has to end in the same day just like Journey2 ended even when Value was always greater than InitialValue.
accepted answer: http://stackoverflow.com/a/52430941
has title: Iterating through pandas dataframe while keeping memory of earlier states

http://stackoverflow.com/comment/108408975
comment on: http://stackoverflow.com/a/54115197
type: Comment
score: 0
type: AnswerComment
has text: Spent 2 days working on this problem and this solution worked for me. Thanks!!!!

http://stackoverflow.com/q/52331873
tagged with: django-cms
has title: Tests for extended DjangoCMS toolbar
tagged with: python-unittest
type: Question
has comment: http://stackoverflow.com/comment/92100429
has answer: http://stackoverflow.com/a/52607392
score: 0
answer count: 1
has body: Can you help me how to write unit tests for extended toolbar in DjangoCMS? Here is a reference on how to extend toolbar http://support.divio.com/academy/advanced-how-to-build-a-website-and-blog-with-django-cms/17-adapting-your-application Has anyone had some experience with this? Thanks in advance!
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/a/52328924
answers question: http://stackoverflow.com/q/52328543
type: Answer
has body: I think you can check signals on a post save of your object. You check when an object is modified, get the objects that come after (if there's any) and re calculate the time for the month.
score: 0
accepted answer of: http://stackoverflow.com/q/52328543
type: AcceptedAnswer

http://stackoverflow.com/comment/91504436
type: Comment
type: QuestionComment
has text: Passing in a string works: `subset_strategy = "0.2037"`, seems like it could be bad documentation.
score: 0
comment on: http://stackoverflow.com/q/52278080

http://stackoverflow.com/comment/91796267
type: Comment
comment on: http://stackoverflow.com/a/52425251
has text: @schwobaseggl How can I then iterate through this `nested_dict` in templates?
type: AnswerComment
score: 0

http://stackoverflow.com/q/52347052
tagged with: python
accepted answer: http://stackoverflow.com/a/52347237
has comment: http://stackoverflow.com/comment/91639805
has comment: http://stackoverflow.com/comment/91639774
has comment: http://stackoverflow.com/comment/91639709
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52347201
has answer: http://stackoverflow.com/a/52347465
has answer: http://stackoverflow.com/a/52347237
has answer: http://stackoverflow.com/a/52347239
has comment: http://stackoverflow.com/comment/91639723
type: Question
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91640150
score: -1
has answer: http://stackoverflow.com/a/52347289
has comment: http://stackoverflow.com/comment/91639596
tagged with: python-2.7
downvote count: 2
tagged with: pandas
upvote count: 1
has title: How to compare two dataframe in pandas and show differences?
possible better answer: http://stackoverflow.com/a/52347289
favorite count: 0
has body: I have two data frame as mentioned below.I want to display only mismatched rows.Is there any way in pandas to do this? DataFrame1 emp_id emp_name City Salary 111 aaa pune 10000 222 bbb pune 20000 333 ccc mumbai 30000 444 ddd pune 40000 DataFrame2 emp_id emp_name City Salary 111 aaa pune 60000 222 bbb pune 20000 333 ccc mumbai 30000 444 eee pune 40000 The Output dataframe I want is :- emp_id emp_name City Salary 111 aaa pune 60000 444 eee pune 40000
answer count: 5
has comment: http://stackoverflow.com/comment/91639609

http://stackoverflow.com/a/54078849
has body: As stated in the comments, you can access all information in the metadata of each pod in the list of pod items returned by the API call. Here is an example: def get_pods(): v1 = client.CoreV1Api() pod_list = v1.list_namespaced_pod("example") for pod in pod_list.items: print("%s\t%s\t%s" % (pod.metadata.name, pod.status.phase, pod.status.pod_ip))
score: 24
upvote count: 24
downvote count: 0
answers question: http://stackoverflow.com/q/52329005
type: Answer

rpy2
tags question: http://stackoverflow.com/q/52299808
type: Tag
tag name: rpy2
tags question: http://stackoverflow.com/q/52361732

http://stackoverflow.com/q/52388005
answer count: 4
has comment: http://stackoverflow.com/comment/91720948
type: AnsweredQuestion
has body: I have tried to calculate the number of business days between two date (stored in separate columns in a dataframe ). MonthBegin MonthEnd 0 2014-06-09 2014-06-30 1 2014-07-01 2014-07-31 2 2014-08-01 2014-08-31 3 2014-09-01 2014-09-30 4 2014-10-01 2014-10-31 I have tried to apply numpy.busday_count but I get the following error: Iterator operand 0 dtype could not be cast from dtype('&lt;M8[ns]') to dtype('&lt;M8[D]') according to the rule 'safe' I have tried to change the type into Timestamp as the following : Timestamp('2014-08-31 00:00:00') or datetime : datetime.date(2014, 8, 31) or to numpy.datetime64: numpy.datetime64('2014-06-30T00:00:00.000000000') Anyone knows how to fix it? Note 1: I have passed tried np.busday_count in two way : 1. Passing dataframe columns, t['Days']=np.busday_count(t.MonthBegin,t.MonthEnd) Passing arrays np.busday_count(dt1,dt2) Note2: My dataframe has over 150K rows so I need to use an efficient algorithm
linked to: http://stackoverflow.com/q/31917964
score: 1
possible better answer: http://stackoverflow.com/a/52388156
type: Question
upvote count: 2
tagged with: numpy
has comment: http://stackoverflow.com/comment/91720779
linked to: http://stackoverflow.com/q/13019719
has answer: http://stackoverflow.com/a/52388156
has answer: http://stackoverflow.com/a/52388266
tagged with: pandas
has comment: http://stackoverflow.com/comment/91720905
has title: Count business day between using pandas columns
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52388333
accepted answer: http://stackoverflow.com/a/52388333
has answer: http://stackoverflow.com/a/52388455
tagged with: python

http://stackoverflow.com/comment/91740138
type: AnswerComment
comment on: http://stackoverflow.com/a/52397839
type: Comment
score: 1
has text: You can also check out the docs I linked to `numpy.array_equal`, which explains it differently, but is essentially the same function. As for how to check equality, @U9-Forward's comment makes sense (+1)

http://stackoverflow.com/q/52405777
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91755493
has comment: http://stackoverflow.com/comment/91755292
tagged with: matplotlib
has body: I am plotting a dataframe of ratio values where the values lie between -0.2 and 0.4. To plot the histogram I am simply using sheet = pd.read_csv('Spread_Ratio.csv') #read excel sheet containing values df = sheet['Ratio'] #where the 'Ratio' col is just values between -0.2 and 0.4 df.hist() plt.show() which returns the following histogram. Here my x axis is incrementing in ticks of 0.1, but I would like to see the data using 0.01 tick size across the xaxis. What do I need to alter in order to switch this?
type: Question
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/91755788
answer count: 1
tagged with: histogram
has answer: http://stackoverflow.com/a/65470732
linked to: http://stackoverflow.com/q/50396015
has title: Change Histogram Tick Size
tagged with: python

http://stackoverflow.com/comment/91712353
score: 1
has text: Showcasing your problem with a sample input/output always makes everyone's life easier
comment on: http://stackoverflow.com/q/52384149
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52331015
type: Answer
has comment: http://stackoverflow.com/comment/91675914
answers question: http://stackoverflow.com/q/52329521
score: 0
has body: SQL injections are only a problem if the values (in this case the db name) come from an untrusted source, and even then you could sanitize the db name manually. This being said, it might be easier to pass the db name to the connection object - eventually keeping a map of db_name:connection to avoid reopening new connections each time.

http://stackoverflow.com/q/52282267
tagged with: python
type: UnansweredQuestion
has body: I have a .py file that is a standalone program that takes in two command line arguments using argparse Followed the following youtube vid: ap = argparse.ArgumentParser() ap.add_argument("-1", "--Image", required=True, help="Image to be trained on") ap.add_argument("-2", "--SaveName", required=True, help="Name of file to be saved") args = vars(ap.parse_args()) image = cv2.imread(args["Image"]) fileName = (args["SaveName"]) The following is my setup.py file for py2app from setuptools import setup APP = ['DataTraining.py'] DATA_FILES=[] OPTIONS = { 'argv_emulation':True, 'packages':['certifi'], } setup( app=APP, data_files=DATA_FILES, options={'py2app':OPTIONS}, setup_requires=['py2app '] ) I can build the program into an applications but when I try to run it in terminal with the command line arguments I have specified it states the inputs as unrecognized options. This is my terminal execution without args that opens but fails immediately. open DataTraining.app/ This is my terminal execution with cmd line args that fails: open DataTraining.app/ --Image /Users/chrisradford/Documents/School/Masters/RA/Classifier/ImageSets/Orig_11.png --SaveName /Users/chrisradford/Documents/School/Masters/RA/Classifier/Python/Orig_11_TrainingAttempt Is there a way to bring in my desired two arguments to execute my program with the terminal? Also if I have my program printing without a GUI will it go to the terminal or will it crash?
tagged with: py2app
has answer: http://stackoverflow.com/a/52282398
tagged with: executable
tagged with: command-line-arguments
type: Question
score: 0
has title: Build/Run Python Executable in terminal that requires cmd line arguments using Py2app
answer count: 1

http://stackoverflow.com/comment/91655728
comment on: http://stackoverflow.com/q/52354246
score: 0
type: Comment
type: QuestionComment
has text: @GyanenderGandhar wanted to use value in column `wave` as index to find corresponding rows in all the dataframes. Then compute average values for all the relevant column.

http://stackoverflow.com/a/52392763
answers question: http://stackoverflow.com/q/52384386
has body: I don't think there is a built-in way to do so. However, one alternative way is to wrap the generator inside another generator and modify the labels in it (for the sake of demonstration, here I have assumed we have four classes initially, and we want the classes one and two to be considered as the new class one and the classes three and four to be considered as the new class two): # define the generator datagen = ImageDataGenerator(...) # assign class_mode to 'sparse' to make our work easier gen = datagen.flow_from_directory(..., class_mode= 'sparse') # define a mapping from old classes to new classes (i.e. 0,1 -&gt; 0 and 2,3 -&gt; 1) old_to_new = np.array([0, 0, 1, 1]) # the wrapping generator def new_gen(gen): for data, labels in gen: labels = old_to_new[labels] # now you can call np_utils.to_categorical method # if you would like one-hot encoded labels yield data, labels # ... define your model # fit the model model.fit(new_gen(gen), ...)
type: Answer
has comment: http://stackoverflow.com/comment/92692186
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52384386
has comment: http://stackoverflow.com/comment/92688898

google-cloud-functions
tag name: google-cloud-functions
tags question: http://stackoverflow.com/q/52395626
type: Tag
tags question: http://stackoverflow.com/q/52325727

http://stackoverflow.com/q/52343188
has comment: http://stackoverflow.com/comment/91632633
tagged with: python
has answer: http://stackoverflow.com/a/52348640
has title: No performance gain after using multiprocessing for a queue-oriented function
has body: The real code I want to optimize is too complicated to be included here, so here is a simplified example: def enumerate_paths(n, k): """ John want to go up a flight of stairs that has N steps. He can take up to K steps each time. This function enumerate all different ways he can go up this flight of stairs. """ paths = [] to_analyze = [(0,)] while to_analyze: path = to_analyze.pop() last_step = path[-1] if last_step &gt;= n: # John has reach the top paths.append(path) continue for i in range(1, k + 1): # possible paths from this point extended_path = path + (last_step + i,) to_analyze.append(extended_path) return paths and the output looks like this &gt;&gt;&gt; enumerate_paths(3, 2) [(0, 2, 4), (0, 2, 3), (0, 1, 3), (0, 1, 2, 4), (0, 1, 2, 3)] You may find the result confusing, so here is an explanation. For example, (0, 1, 2, 4) means John can visit place his foot on the first, second and fourth step chronological, and finally he stops at step 4 because he only need to go up 3 steps. I tried to incorporate multiprocessing into this snippet, but observed no performance gain, not even a little! import multiprocessing def enumerate_paths_worker(n, k, queue): paths = [] while not queue.empty(): path = queue.get() last_step = path[-1] if last_step &gt;= n: # John has reach the top paths.append(path) continue for i in range(1, k + 1): # possible paths from this point extended_path = path + (last_step + i,) queue.put(extended_path) return paths def enumerate_paths(n, k): pool = multiprocessing.Pool() manager = multiprocessing.Manager() queue = manager.Queue() path_init = (0,) queue.put(path_init) apply_result = pool.apply_async(enumerate_paths_worker, (n, k, queue)) return apply_result.get() The Python list to_analysis acts just like a task queue, and each item in this queue can be processed separately, so I think this function has the potential to be optimized by employing multi-threading/processing. Also, please note that the order of items doesn't matter. In fact, whe…
upvote count: 1
has comment: http://stackoverflow.com/comment/91632551
tagged with: multiprocessing
type: Question
type: AnsweredQuestion
tagged with: performance
score: 1
accepted answer: http://stackoverflow.com/a/52348640
tagged with: queue
has comment: http://stackoverflow.com/comment/91632589
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91632474
favorite count: 0
tagged with: optimization
has comment: http://stackoverflow.com/comment/91632533

http://stackoverflow.com/a/53157591
has comment: http://stackoverflow.com/comment/115285183
type: Answer
has body: I have faced the similar issue in Windows Server 2012 r2. After lot of findings I found that mfplat.dll was missing which is related to Window Media Service. Hence you have to manually install the features so that you can get dll related to window media service. Turn windows features on or off Skip the roles screen and directly go to Feature screen Select "Desktop Experience" under "User Interfaces and Infrastructure" After this all required dll of opencv would be available.
downvote count: 0
score: 7
answers question: http://stackoverflow.com/q/52349669
upvote count: 7

http://stackoverflow.com/q/52375035
upvote count: 2
has comment: http://stackoverflow.com/comment/91695285
answer count: 1
has answer: http://stackoverflow.com/a/52375463
tagged with: python-imaging-library
accepted answer: http://stackoverflow.com/a/52375463
has body: I'm using tkinter and I have a "sprite sheet" and I want to cut it into multiple images. I tried PIL: img = Image.open("test.png").convert("RGBA") img2 = img.crop([300,300,350,350]) image = ImageTk.PhotoImage(img2) win = tk.Tk() label = tk.Label(win, image = image) label.pack() but on my window, there is only an empty white rectangle and I don't understand why. Moreover I tried img2.show() just to make shure that img2 wasn't empty and it wasn't.
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/91695076
favorite count: 0
type: Question
tagged with: python
has title: Cropping an image in tkinter
tagged with: tkinter

http://stackoverflow.com/comment/91810797
comment on: http://stackoverflow.com/a/52433458
has text: @Hellbea the path used by QSettings does not depend on the executable.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/52310550
has comment: http://stackoverflow.com/comment/91613376
downvote count: 0
has comment: http://stackoverflow.com/comment/91573597
score: 4
answers question: http://stackoverflow.com/q/52310217
type: Answer
has comment: http://stackoverflow.com/comment/91573388
has body: The following is airflow-webserver.service that works for me with a virtual environment: [Unit] Description=Airflow webserver daemon After=network.target postgresql.service mysql.service redis.service rabbitmq-server.service Wants=postgresql.service mysql.service redis.service rabbitmq-server.service [Service] PIDFile=/run/airflow/webserver.pid EnvironmentFile=/etc/default/airflow User=airflow Group=airflow Type=simple ExecStart=/usr/bin/bash -c 'source /usr/local/airflow/venv/bin/activate ; airflow webserver --pid /run/airflow/webserver.pid' Restart=on-failure RestartSec=5s PrivateTmp=true [Install] WantedBy=multi-user.target
upvote count: 4

http://stackoverflow.com/q/52325941
has body: . dd language identifier to highlight code def function(foo): print(foo) ► put returns between paragraphs ► for linebreak add 2 spaces at end ► italic or bold ► indent code by 4 spaces ► backtick escapes like _so_ ► quote by placing &gt; at start of line
accepted answer: http://stackoverflow.com/a/52326066
has comment: http://stackoverflow.com/comment/91599084
has comment: http://stackoverflow.com/comment/91598893
type: Question
has title: Loop only works once
has comment: http://stackoverflow.com/comment/91598871
score: -2
answer count: 2
upvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/52326368
has answer: http://stackoverflow.com/a/52326066
has answer: http://stackoverflow.com/a/52326368
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/91599008
has comment: http://stackoverflow.com/comment/91598957
type: AnsweredQuestion

http://stackoverflow.com/comment/91617000
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52321630
type: AnswerComment
has text: Hey there, the other answer that helped you had a portion I forgot. You would need to add `tax = #` before `print()` with # being the tax amount for that bracket. My apologies! You could also make sure tax goes back to a set value (like 0) by putting `tax = 0` **after** `print()`

http://stackoverflow.com/a/52297070
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52297008
upvote count: 2
has body: my_list = [line for line in file if ".0130" in line]
answers question: http://stackoverflow.com/q/52297008
type: AcceptedAnswer

http://stackoverflow.com/a/52318979
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52318884
downvote count: 0
has body: from selenium import webdriver from selenium.webdriver.common.by import By from contextlib import closing from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver import Firefox from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys import time import urllib2 import re from bs4 import BeautifulSoup import unicodedata def remove_non_ascii_1(text): return ''.join([i if ord(i) &lt; 128 else ' ' for i in text]) with closing(Firefox()) as browser: site = "https://www.flipkart.com/asus-zenfone-2-laser-ze550kl-black-16-gb/product-reviews/itme9j58yzyzqzgc?pid=MOBE9J587QGMXBB7" browser.get(site) file = open("review.txt", "w") for count in range(1, 10): nav_btns = browser.find_elements_by_class_name('_33m_Yg') button = "" for btn in nav_btns: number = int(btn.text) if(number==count): button = btn break button.send_keys(Keys.RETURN) WebDriverWait(browser, timeout=10).until(EC.presence_of_all_elements_located((By.CLASS_NAME, "_2xg6Ul"))) read_more_btns = browser.find_elements_by_class_name('_1EPkIx') for rm in read_more_btns: browser.execute_script("return arguments[0].scrollIntoView();", rm) browser.execute_script("window.scrollBy(0, -150);") rm.click() page_source = browser.page_source soup = BeautifulSoup(page_source, "lxml") ans = soup.find_all("div", class_="_3DCdKt") for tag in ans: title = unicode(tag.find("p", class_="_2xg6Ul").string).replace(u"\u2018", "'").replace(u"\u2019", "'") title = remove_non_ascii_1(title) title.encode('ascii','ignore') content = tag.find("div", class_="qwjRop").div.prettify().replace(u"\u2018", "'").replace(u"\u2019", "'") content = remove_non_ascii_1(content) content.encode('ascii','ignore') content = content[15:-7] votes = tag.find_all("span", class_="_1_BQL8") upvotes = int(votes[0].string) downvotes = int(votes[1].string) file.write("Review…
has comment: http://stackoverflow.com/comment/119248396

http://stackoverflow.com/q/52338342
tagged with: numpy
tagged with: pandas
has title: A tricky situation involving compound growth rate between two different data frames
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52338452
has body: I am looking to calculate compound annual growth rate between census years (2011, 2016) and use that growth rate to extrapolate numbers for the in-between years. For example df_2011.head() Age Census_Tract_001 Census_Tract_002 0 100 600 df_2016.head() Age Census_Tract_001 Census_Tract_002 0 400 360 Then calculate CAGR between 2011 and 2016 Age Census_Tract_001 Census_Tract_002 0 .3195 -.0971 Apply CAGR to each of the inbetween years create df_2012 Age Census_Tract_001 Census_Tract_002 0 131.95 541.74 create df_2013 Age Census_Tract_001 Census_Tract_002 0 174.108 489.137 create df_2014 Age Census_Tract_001 Census_Tract_002 0 229.7355 441.6418 create df_2015 Age Census_Tract_001 Census_Tract_002 0 303.136 398.7584 My attempt I tired doing the following Number of years ny = 5 Present Turnover pt = ? Past turnover value ppt = ? m =(pt/ppt) AGR = Annual Growth rate agr = float((m**1/ny)-1)*100 I tired to do this for hours but if I can't I will just ref cells in excel to calculate, sadly...
tagged with: python
type: AnsweredQuestion
upvote count: 3
type: Question
score: 3
has answer: http://stackoverflow.com/a/52338452

http://stackoverflow.com/a/52420127
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/52419402
downvote count: 0
type: Answer
has body: Dictionaries are not supported by numba, thus it falls back to Python mode which causes runtime overhead. You can see that JIT compilation fails if you replace @jit by @jit(nopython=True) which disables switching to Python so that you get an error message in case you use unsupported Python features.

http://stackoverflow.com/comment/91655173
has text: @MishraSiba see edit. Not in a single step, but you can iterate over the Counter-results and apply any changes that you like to both lists. I use the `i-th` character and multiply it count times before pre-/postfixing, for all results of counter. This is not one step, its a look that modifies one list after the other, replacing one word, then the next. use a `print(L1)` inside the loop to see your data change forms.
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52347571

http://stackoverflow.com/comment/91506583
type: Comment
score: 0
type: AnswerComment
has text: I get a TypeError: 'float' object is not iterable error.
comment on: http://stackoverflow.com/a/52279253

http://stackoverflow.com/comment/91553627
comment on: http://stackoverflow.com/q/52302837
score: 0
has text: @Thomas In which case you should isolate the timing of `svd` if that's what you're interested in. `randn` may have different functionality / implementations.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91745618
type: AnswerComment
type: Comment
has text: Thanks for your time and response. I would try your suggestion and get to you back with the feedback.
comment on: http://stackoverflow.com/a/52400396
score: 0

http://stackoverflow.com/comment/91756137
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52406104
has text: am having multiple lines of heading to add to csv is there any other way to do that
type: Comment

http://stackoverflow.com/a/52420942
type: Answer
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/52418967
has body: Use tf.where as suggested in the comments. I have below provided a sample code and commented where necessary. x = tf.random_uniform(shape=[5, 3], minval=0, maxval=1, dtype=tf.float32) #same shape as x and only contains -1 c1 = tf.multiply(tf.ones(x.shape, tf.int32), -1) #same shape as x and only contains 1 c2 = tf.multiply(tf.ones(x.shape, tf.int32), 1) var = tf.zeros([5, 3], tf.int32) #assign 1 element wise if x&lt; 0.25 else 0 r1 = tf.where(tf.less(x, 0.25), c1, var) #assign -1 element wise if x&gt; 0.75 else 0 r2 = tf.where(tf.greater(x, 0.75), c2, var) r = tf.add(r1, r2) with tf.Session() as sess: _x, _r = sess.run([x, r]) print(_x) print(_r) Example Result [[0.6438687 0.79183984 0.40236235] [0.7848805 0.0117377 0.6858672 ] [0.6067281 0.5176437 0.9839716 ] [0.15617108 0.28574145 0.31405795] [0.28515983 0.6034068 0.9314337 ]] [[ 0 1 0] [ 1 -1 0] [ 0 0 1] [-1 0 0] [ 0 0 1]] Hope this helps.
accepted answer of: http://stackoverflow.com/q/52418967
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/91790511
has text: Hi @Daniel Roseman, Now it starts downloading the video but this time it's taking too much time, I think it ~6 minutes here but the video is still downloading.
comment on: http://stackoverflow.com/a/52423154
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52295615
type: Question
has body: I'm trying to implement a keyword based personal assistant My issue is my grammar is set up so that after I detect the keyword, I still need to use it in my grammar,but switching to jsfg mode discards that utterance Therefore I need to use Decoder.get_raw_data and Decoder.process_raw_data in but in Python there is no implementation for .get_raw_data method present in C/C++ implementation Is there any way I could use it? Thanks
has title: Pocketsphinx Python get_raw_data
tagged with: cmusphinx
score: 0
tagged with: pocketsphinx
has answer: http://stackoverflow.com/a/52938578
answer count: 1
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/71305155
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52394408
downvote count: 0
has body: this worked for me 100% and it showed up my selected profile.
type: Answer

http://stackoverflow.com/q/52287530
has body: I am attempting to add a series consisting of ints to a dataframe, but the items in the dataframe get converted to objects, instead of ints. How can I keep the dtype as int for the items in the dataframe. Here is some demo code: &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame(columns =['a','b','c'], dtype=int) &gt;&gt;&gt; row = pd.Series(0,['a','b','c'],dtype=int) &gt;&gt;&gt; row = row.rename('row') &gt;&gt;&gt; print(row) a 0 b 0 c 0 Name: row, dtype: int64 &gt;&gt;&gt; df.append(row)['a'] row 0 Name: a, dtype: object &gt;&gt;&gt;
answer count: 1
downvote count: 0
has title: Appending row to empty DataFrame converts dtype from int to object
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52287639
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91522892
accepted answer: http://stackoverflow.com/a/52287639
type: Question

http://stackoverflow.com/a/52320812
has comment: http://stackoverflow.com/comment/91590169
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91590438
type: Answer
answers question: http://stackoverflow.com/q/52319398
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52319398
has body: You'll need a second function and will have to call it outside your logger function. Something like this: def getlogfile(prefix): file_list = [filename for filename in os.listdir('.') if filename.startswith(prefix)] if prefix not in file_list: # file doesn't exist yet; make it. target_name = prefix else: # get latest one number_list = [int(filename[-1]) for filename in file_list if filename[-2] == '_'] try: latest_num = sorted(number_list)[-1] target_name = '{}_{}'.format(prefix, latest_num + 1) except IndexError: # there aren't any underscored names yet target_name = '{}_1'.format(prefix) return target_name def logger(event, date_file_name): event = str(event) current_date = datetime.datetime.now() current_time_for_log = current_date.strftime('%d-%m-%y %H:%M:%S --- ') with open('{}'.format(date_file_name), 'a+') as log_file: log_file.write('-' * 50 + '\n' + '\n') log_file.write(current_time_for_log + event + '\n') date_file_name = getlogfile(datetime.date.today().strftime('%d-%m-%y')) logger('first call, new file', date_file_name) logger('second call, same file', date_file_name) should do the trick for you.
has comment: http://stackoverflow.com/comment/91590145
has comment: http://stackoverflow.com/comment/91590837
has comment: http://stackoverflow.com/comment/91590216

http://stackoverflow.com/q/52319296
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/91585946
has comment: http://stackoverflow.com/comment/91586471
type: Question
has body: I have two lists: list_1 = ['2', '1', '1', '2', '1', '2', '1', '5', '4', '3', '2', '1', '3', '2', '1'] list_2 = ['az', 'z', 'c', 'bo', 'o', 'bo', 'o', 'beggh', 'eggh', 'ggh', 'gh', 'h', 'akl', 'kl', 'l'] The number of strings inside the two lists is the same. I want to create a dictionary from the two lists, so I try: new_dict = dict(zip(list_1, list_2)) I expect something like: { '2' : 'az', '1' : 'z', '1' : 'c', .... } I also expect that the number of key-value pairs in the dictionary is the same as the number of strings in either list_1 or list_2. However, when I try to print the dictionary out, it gives: {'2': 'kl', '1': 'l', '5': 'beggh', '4': 'eggh', '3': 'akl'} The number of key-value pairs is only 5, which is obviously less than the number of strings in either list_1 or list_2. What has gone wrong?
linked to: http://stackoverflow.com/q/44280227
has comment: http://stackoverflow.com/comment/91585931
has comment: http://stackoverflow.com/comment/91586268
has answer: http://stackoverflow.com/a/52319395
has comment: http://stackoverflow.com/comment/91585984
duplicate of: http://stackoverflow.com/q/44280227
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
downvote count: 2
accepted answer: http://stackoverflow.com/a/52319395
tagged with: python
score: -2
tagged with: dictionary
has title: When trying to create a dictionary from two lists, some elements are lost

http://stackoverflow.com/comment/91725973
has text: You might as well just use 10.0.**(np.arange(-2, 6))`; logspace isn't really buying you anything here.
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52390431

http://stackoverflow.com/comment/91610028
type: QuestionComment
has text: Not with OpenCV. Perhaps if you use ffmpeg or something like that directly. TBH, I don't see you gaining much doing this (other than a lot more code to write).
score: 0
comment on: http://stackoverflow.com/q/52330472
type: Comment

http://stackoverflow.com/q/52386195
has title: Do I have to constantly change the default python version?
tagged with: python
has comment: http://stackoverflow.com/comment/91716638
upvote count: 1
has comment: http://stackoverflow.com/comment/91716772
type: Question
has body: I had to change the default python to python2.7. Now I'm always running into problems because there are a bunch of apps that need python2.x as default and others that need python3.x and so I'm constantly changing the default to accommodate that. Did I broke something, and is there a way to solve the constant changing of the default python version?
has comment: http://stackoverflow.com/comment/91716765
has answer: http://stackoverflow.com/a/52386321
downvote count: 0
answer count: 1
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/92022850
tagged with: linux
type: UnansweredQuestion

http://stackoverflow.com/q/52386967
has body: It is known that dictionaries may be sorted in a different order that the one which each key,value pair is inserted. For example : my_dict = {} my_dict.update({'A': 2}) my_dict.update({'B': 1}) for keys,values in my_dict.items(): print(keys) print(values) #may result in B A 1 or 2 A B 2 1 Then, is an object, contained in a dictionnary may encounter the same behaviour ? For illustration : another_dict = {'Type A': [4], 'Type B' : [0]} another_dict['Type A'].append(2) another_dict['Type B'].append(1) for keys,values in another_dict.items(): print(keys) print(values) Type A: 4, 2 Type B: 0, 1 Will the content of the lists remain in the same order than their insertion, despite the lists order may vary ?
score: -3
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/91718380
has comment: http://stackoverflow.com/comment/91718392
favorite count: 0
accepted answer: http://stackoverflow.com/a/52554042
has comment: http://stackoverflow.com/comment/91718784
has comment: http://stackoverflow.com/comment/91718511
type: Question
has comment: http://stackoverflow.com/comment/91718561
tagged with: python
has comment: http://stackoverflow.com/comment/91719124
has comment: http://stackoverflow.com/comment/91718350
downvote count: 3
answer count: 1
has title: Could the order of a list contained in a dictionary vary?
has comment: http://stackoverflow.com/comment/91718590
has answer: http://stackoverflow.com/a/52554042

http://stackoverflow.com/a/52340775
score: 0
has body: Here is slight variation on the excellent answer from gilch that handles negative numbers and zero. def convert_to_string(num, base): ''' Convert integer (num) to base less than base 37. ''' alpha = string.digits + string.ascii_lowercase assert isinstance(num, int) assert isinstance(base, int) assert 1 &lt; base &lt;= len(alpha) if num == 0: return '0' def to_digits(num, base, alpha): ''' Generator to convert digits in reverse order. ''' while num &gt; 0: num, rem = divmod(num, base) yield alpha[rem] sign = '' if num &lt; 0: num, sign = -num, '-' return sign + ''.join(d for d in reversed(tuple(to_digits(num, base, alpha)))) def convert_from_string(num, base): ''' Convert string in base X to integer. ''' return int(str(num), base) def test(): ''' Test conversions. ''' assert convert_to_string(0, 2) == '0' assert convert_to_string(4, 2) == '100' assert convert_to_string(23, 12) == '1b' assert convert_to_string(-6, 2) == '-110' assert convert_from_string('1b', 12) == 23 assert convert_from_string('-110', 2) == -6
type: Answer
answers question: http://stackoverflow.com/q/52323971

http://stackoverflow.com/comment/91641083
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52341432
type: Comment
has text: I thought I made a clever workaround, but nope. I've added your example to my answer. TIL that you can override the metaclass like that.

http://stackoverflow.com/comment/91702294
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52378986
type: Comment
has text: have a look on My Question , :|

http://stackoverflow.com/q/52364016
score: 2
type: AnsweredQuestion
has title: How to fuse a small pandas.dataframe into a larger one based on values of a column?
downvote count: 0
possible better answer: http://stackoverflow.com/a/52364225
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/52364091
accepted answer: http://stackoverflow.com/a/52364091
has body: I have two pandas.dataframe df1 and df2: &gt;&gt;&gt;import pandas as pd &gt;&gt;&gt;import numpy as np &gt;&gt;&gt;from random import random &gt;&gt;&gt;df1=pd.DataFrame({'x1':range(10), 'y1':np.repeat(0,10).tolist()}) &gt;&gt;&gt;df2=pd.DataFrame({'x2':range(0,10,2), 'y2':[random() for _ in range(5)]}) &gt;&gt;&gt;df1 x1 y1 0 0 0 1 1 0 2 2 0 3 3 0 4 4 0 5 5 0 6 6 0 7 7 0 8 8 0 9 9 0 &gt;&gt;&gt;df2 x2 y2 0 0 0.075922 1 2 0.606703 2 4 0.272918 3 6 0.842641 4 8 0.576636 Now I want to fuse df2 into df1. This is to say, I want to change the values of y1 in df1 into the values of y2 in df2 when the value of x1 in df1 is equal to the value of x2 in df2. The final result I need is like the following: &gt;&gt;&gt;df1 x1 y1 0 0 0.075922 1 1 0 2 2 0.606703 3 3 0 4 4 0.272918 5 5 0 6 6 0.842641 7 7 0 8 8 0.576636 9 9 0 Although I can use the follow codes to get the above result: &gt;&gt;&gt; for i in range(df1.shape[0]): ... for j in range(df2.shape[0]): ... if df1.iloc[i,0] == df2.iloc[j,0]: ... df1.iloc[i,1]=df2.iloc[j,1] ... I think there must be better ways to achieve this. Do you know what they are? Thank you in advance.
tagged with: pandas
has answer: http://stackoverflow.com/a/52364225
has answer: http://stackoverflow.com/a/60319879
has answer: http://stackoverflow.com/a/52364136
favorite count: 0
answer count: 5
has answer: http://stackoverflow.com/a/52364349
tagged with: python

http://stackoverflow.com/comment/91655454
has text: @roganjosh It improves the situation by two ways 1. IO operation is not performed on the thread that runs the loop. Yes using locks involves system call. But it is still faster than an IO block. 2.Assuming that the python interpreter uses futex to implement locks, then lock is almost a no cost operation, as compared to worker thread , the main thread would rarely hold the lock.
type: Comment
comment on: http://stackoverflow.com/a/52355288
score: 0
type: AnswerComment

http://stackoverflow.com/q/52421142
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
type: UnansweredQuestion
has title: How could I use threading to run this subprogram alongside my main code?
tagged with: multithreading
has body: code i need to run along side my main code def check(): if running == True: if FourInRow == True: running == False else: print("A") window.after(100, check) I have tried making a threading class but I cant get it to work. Thanks in advance!!
tagged with: python
has comment: http://stackoverflow.com/comment/91785785
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91785644
has comment: http://stackoverflow.com/comment/91785429
score: -1
upvote count: 0
has answer: http://stackoverflow.com/a/52430084
answer count: 1

http://stackoverflow.com/q/52346338
tagged with: python
upvote count: 0
type: AnsweredQuestion
tagged with: list
score: -1
tagged with: list-comprehension
has body: Given a list containing monthly numerical data, how can I easily convert this into quarterly data? x= [5,8,3,4,5,6,1,2,5,3,11,8] #monthly data for Jan-Dec Desired output: [5+8+3, 4+5+6, 1+2+5, 3+11+8] #converted to quarterly data I wanted to do something like [a+b+c for a,b,c in x] but x it says x is not iterable. I don't think this is a duplicate. I am specifically looking for a list comprehension solution.
type: Question
has answer: http://stackoverflow.com/a/52346382
accepted answer: http://stackoverflow.com/a/52346382
answer count: 2
linked to: http://stackoverflow.com/q/312443
has answer: http://stackoverflow.com/a/52347036
has title: List comprehension: Creating new list by adding multiple values in single list
favorite count: 0
has comment: http://stackoverflow.com/comment/91638287
possible better answer: http://stackoverflow.com/a/52347036
downvote count: 1

http://stackoverflow.com/q/52359579
has title: Why is the print order scrambled with a mix of floats and Arabic strings?
has comment: http://stackoverflow.com/comment/91663992
tagged with: python
has comment: http://stackoverflow.com/comment/91663951
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/52359724
has comment: http://stackoverflow.com/comment/91663661
downvote count: 0
has comment: http://stackoverflow.com/comment/91663642
has body: In Python 3, this: alternates={'Qabr Ḩamdān', 'قبور حمدان', 'Qabr Hamdan', 'Qubur Hamdan', 'Qubūr Ḩamdān', 'qbwr hmdan'} for x in alternates: print(12.1, x, 13.2) produces this: 12.1 Qabr Ḩamdān 13.2 12.1 قبور حمدان 13.2 12.1 Qabr Hamdan 13.2 12.1 Qubur Hamdan 13.2 12.1 Qubūr Ḩamdān 13.2 12.1 qbwr hmdan 13.2 Notice the Arabic string in the second line is out of order. Why?
type: Question
has comment: http://stackoverflow.com/comment/91663651
has answer: http://stackoverflow.com/a/52359724
has comment: http://stackoverflow.com/comment/91663637
upvote count: 3
tagged with: printing
answer count: 1
has comment: http://stackoverflow.com/comment/91663944
tagged with: unicode
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/42556063

http://stackoverflow.com/comment/91622105
has text: Thanks, I updated the question with the information
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52337367
type: QuestionComment

http://stackoverflow.com/q/52398106
answer count: 1
has title: How to take out first 2 digit number from a string in Python
favorite count: 0
has comment: http://stackoverflow.com/comment/91741410
tagged with: python
has comment: http://stackoverflow.com/comment/91776013
has body: I have 2 strings: "SP-1-15::PROVPEC=NTK555EA,CTYPE=\"SP-2\",PEC=NTK555EA,REL= 1 ,CLEI=,SER=NNTM,MDAT=UNKNOWN,AGE=00-005-20-03,ONSC=00-005-19-50:IS-ANR,FLT" "SP-1-16::PROVPEC=NTK555FA,CTYPE=\"SP-2 Dual CPU\",PEC=NTK555FA,REL= 1 ,CLEI=,SER=NNTM,MDAT=UNKNOWN,AGE=UNKNOWN,ONSC=UNKNOWN:IS-ANR,FLT" I want 2 things: If WRK in string remove 15 and 16 from (SP-1-15 and SP-1-16) resp. If WRK is not in string, remove the odd value which in this case is 15.
type: UnansweredQuestion
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91740536
has answer: http://stackoverflow.com/a/52416955
score: 0

http://stackoverflow.com/comment/91541216
type: Comment
type: QuestionComment
has text: We are generally not fond of fixing someone's homework here. At least give some more motivation and explanation. What needs to happen, what is not happening as you like, how you tried to debug, and so on. (Also, `H3lp` isn't really working for your cause either. `;-)`)
score: 1
comment on: http://stackoverflow.com/q/52296600

http://stackoverflow.com/comment/91790149
has text: Possible duplicate of [Removing duplicates in lists](https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52423525
score: 1

http://stackoverflow.com/comment/91772772
type: AnswerComment
has text: What if I want to add a different value to each input, e.g. 5 to the first, and 8 to the second?
type: Comment
comment on: http://stackoverflow.com/a/52414413
score: 0

http://stackoverflow.com/q/52394372
linked to: http://stackoverflow.com/q/1047318
score: -2
answer count: 3
favorite count: 0
has answer: http://stackoverflow.com/a/66553767
has comment: http://stackoverflow.com/comment/91733965
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: So I'm in an intro to programming class and I need help updating the score in my "text based adventure game". What happens is you press enter, then a text appears (ex, you walk to the plane to find a monkey), then it says "Your score is 5". I want it so every time I press enter, the text appears and then my score goes up by 5. I spent a couple hours reading through my textbook and I don't know what to do. Everything is fine except the showScore function since it keeps printing my score as 5 after every step. This is an example of the code: def promptUser(): input("\n&lt;Press Enter to continue...&gt;\n") def base(): print("You approach the base with friends") def showScore(): x = 0 score = x + 5 print("Your score is now" ,score,)
has comment: http://stackoverflow.com/comment/91733915
downvote count: 3
has answer: http://stackoverflow.com/a/52394872
has title: dont know how to update score in python
has answer: http://stackoverflow.com/a/52394599
type: Question
has comment: http://stackoverflow.com/comment/91734252

http://stackoverflow.com/q/52385296
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/52385326
type: Question
linked to: http://stackoverflow.com/q/52288130
downvote count: 0
tagged with: dataframe
tagged with: pandas
has body: This question is further part of this. So I added it as new question If my dataframe B would be something like: ID category words bucket_id 1 audi a4, a6 94 2 bugatti veyron, chiron 86 3 mercedez s-class, e-class 79 4 dslr canon, nikon 69 5 apple iphone,macbook,ipod 51 6 finance sales,loans,sales price 12 7 politics trump, election, votes 77 8 entertainment spiderman,thor, ironmen 88 9 music beiber, rihana,drake 14 ........ .............. ......... ......... I want mapped category along with its corresponding column ID as dictionary. Something like:- {'id': 2, 'term': 'bugatti', 'bucket_id': 86} {'id': 3, 'term': 'mercedez', 'bucket_id': 79} {'id': 6, 'term': 'finance', 'bucket_id': 12} {'id': 7, 'term': 'politics', 'bucket_id': 77} {'id': 9, 'term': 'music', 'bucket_id': 14} edit I just want to map keywords with exact match in between two commas in column words not in between strings or along with any other words.
answer count: 1
favorite count: 0
has title: Matching keywords of list elements with pandas columns

jupyter-notebook
tags question: http://stackoverflow.com/q/52340441
tags question: http://stackoverflow.com/q/52398849
tags question: http://stackoverflow.com/q/52344406
tags question: http://stackoverflow.com/q/52283912
tags question: http://stackoverflow.com/q/52303178
tags question: http://stackoverflow.com/q/52281000
tags question: http://stackoverflow.com/q/52338926
tags question: http://stackoverflow.com/q/52302752
tags question: http://stackoverflow.com/q/52327864
tags question: http://stackoverflow.com/q/52382999
tags question: http://stackoverflow.com/q/52413246
tags question: http://stackoverflow.com/q/52373351
tags question: http://stackoverflow.com/q/52385309
tags question: http://stackoverflow.com/q/52348594
tags question: http://stackoverflow.com/q/52328595
tags question: http://stackoverflow.com/q/52383716
tags question: http://stackoverflow.com/q/52358291
tags question: http://stackoverflow.com/q/52326242
tags question: http://stackoverflow.com/q/52324192
tags question: http://stackoverflow.com/q/52287117
tags question: http://stackoverflow.com/q/52358107
tags question: http://stackoverflow.com/q/52308329
tags question: http://stackoverflow.com/q/52397069
type: Tag
tags question: http://stackoverflow.com/q/52355533
tags question: http://stackoverflow.com/q/52372686
tags question: http://stackoverflow.com/q/52335033
tags question: http://stackoverflow.com/q/52290068
tags question: http://stackoverflow.com/q/52300930
tags question: http://stackoverflow.com/q/52417794
tags question: http://stackoverflow.com/q/52278177
tags question: http://stackoverflow.com/q/52338155
tags question: http://stackoverflow.com/q/52335555
tags question: http://stackoverflow.com/q/52346525
tags question: http://stackoverflow.com/q/52378745
tags question: http://stackoverflow.com/q/52296980
tags question: http://stackoverflow.com/q/52342124
tags question: http://stackoverflow.com/q/52377462
tags question: http://stackoverflow.com/q/52414249
tags question: http://stackoverflow.com/q/52415187
tags question: http://stackoverflow.com/q/52340088
tags question: http://stackoverflow.com/q/52400814
tags question: http://stackoverflow.com/q/52374294
tags question: http://stackoverflow.com/q/52327284
tags question: http://stackoverflow.com/q/52317111
tags question: http://stackoverflow.com/q/52345449
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/52355727
tags question: http://stackoverflow.com/q/52416528
tags question: http://stackoverflow.com/q/52428467
tags question: http://stackoverflow.com/q/52300650
tags question: http://stackoverflow.com/q/52339903
tags question: http://stackoverflow.com/q/52358542
tags question: http://stackoverflow.com/q/52295849
tags question: http://stackoverflow.com/q/52349503
tags question: http://stackoverflow.com/q/52305171
tags question: http://stackoverflow.com/q/52314676
tags question: http://stackoverflow.com/q/52311063
tags question: http://stackoverflow.com/q/52331082

http://stackoverflow.com/comment/91518919
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52284965
has text: When widget.html is widget.html() -- error - > Uncaught TypeError: data.html is not a function

http://stackoverflow.com/q/52297298
has comment: http://stackoverflow.com/comment/91542643
type: AnsweredQuestion
score: 0
tagged with: mapi
has title: python win32com bulk reading outlook emails - too many open items
type: Question
tagged with: outlook
tagged with: exchange-server
has comment: http://stackoverflow.com/comment/91543085
tagged with: win32com
has body: i'm facing some issues while trying to fetch a bulk mail via python wincom32.client. Basically, it seems like there's a limit on the number of items that could be opened on a single session, and that is a server-side flag or status.. the problem is that i didn't find out any way to resume/close/re-set and i can't ask for sysadmins to do it for me.. Here's my code snippet - i know it's ugly - but i'm using it on a jupiter notebook just to experiment/play around before arranging it down properly. import win32com.client outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") def create_message_list(folder): return [{ "folder": folder.Name, "sender" : m.Sender, "recipients" : m.Recipients, "subject" : m.subject, "body":m.body } for m in folder.Items] for folder in outlook.Folders: if (folder.Name=="myfolder.name"): message_list = create_message_list(folder) and here's what i get: com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Your server administrator has limited the number of items you can open simultaneously. Try closing messages you have opened or removing attachments and images from unsent messages you are composing.', None, 0, -2147220731), None). Notice that i had my sketch code working for a while. i could fetch something like 10k messages before it messed up with that error. Things i've been trying (with no result) - try to close the folder / mapi session - running a for loop on the same items and calling the message.Close(0) - using the GetFirst() / GetLast() methods on message instead of list comprehension thanks anyone for ideas/suggestions/whatever.
possible better answer: http://stackoverflow.com/a/58521736
answer count: 3
has answer: http://stackoverflow.com/a/58521736
has answer: http://stackoverflow.com/a/52297783
has answer: http://stackoverflow.com/a/52308243
tagged with: python
accepted answer: http://stackoverflow.com/a/52308243

http://stackoverflow.com/comment/91654281
type: Comment
has text: The OP does account for case in his original code, so I didn't think it should be lost. Good point about punctuation.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52354697

http://stackoverflow.com/comment/91669400
has text: The key question here is the structure of your data. If you can't change the input format of the json data, try to transform it in to another structure that supports searching better than by iterating recursively through it. Possible solution here may be flattening out the structure or as @xnx suggested inverting the dictionary.
comment on: http://stackoverflow.com/q/52361783
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/52309878
has comment: http://stackoverflow.com/comment/91566992
downvote count: 0
has comment: http://stackoverflow.com/comment/91566884
has comment: http://stackoverflow.com/comment/91566847
type: AcceptedAnswer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/52309772
has body: Sorting seems a bit overkill. You can do it in one line just with if. x,y = (a,b) if len(a) &lt; len(b) else (b,a)
answers question: http://stackoverflow.com/q/52309772
score: 6
type: Answer

http://stackoverflow.com/q/52426195
has comment: http://stackoverflow.com/comment/91795735
has body: I have a list of integers which represent the number of applications submitted per day for a 60 day period. I need to randomly generate a list of 288 integers that sum to the number of applications per day. I have the following code: import random as r issued = [1000,200,344...] def random_sum_to(n, num_terms = None): num_terms = (num_terms or r.randint(2, n)) - 1 a = r.sample(range(1, n), num_terms) + [0, n] list.sort(a) return [a[i+1] - a[i] for i in range(len(a) - 1)] for i in issued: print(random_sum_to(i,288)) Where issued is the list of integers that are the sum of the applications submitted per day. This code works great for numbers greater than 288 but crashes for numbers less than 288. Reading on here i saw that random.choice should be used but I cannot figure out how to implement it correctly. Looking at the results it looks like 0 is never printed so that is clearly a potential source for the problem. Any suggestions?
has comment: http://stackoverflow.com/comment/91796030
tagged with: random
accepted answer: http://stackoverflow.com/a/52426574
type: AnsweredQuestion
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52429847
type: Question
score: 3
tagged with: python
possible better answer: http://stackoverflow.com/a/52429847
has title: python random sample for samples larger than population
upvote count: 3
answer count: 2
has answer: http://stackoverflow.com/a/52426574

http://stackoverflow.com/q/52343235
possible better answer: http://stackoverflow.com/a/52343914
accepted answer: http://stackoverflow.com/a/52343246
has answer: http://stackoverflow.com/a/52343914
type: Question
has body: I'm trying to concatenate strings at every n'th position from 2 lists. But I can't seem to get it to work Input: ['57', '60', '55',..., '56'] ['g', 'b', 'r',..., 'b'] Output: ['57g', '60b', '55r',..., '56b']
score: -1
answer count: 2
favorite count: 0
has title: Concatenating strings at n position from 2 lists
has answer: http://stackoverflow.com/a/52343246
downvote count: 2
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/91661429
has text: Thanks it worked after changing to numeric. How can I accept this answer? Thank you so much all for giving me pointers.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52358417

http://stackoverflow.com/comment/91723730
type: QuestionComment
has text: Check this post: https://stackoverflow.com/questions/14149422/using-pip-behind-a-proxy
comment on: http://stackoverflow.com/q/52388882
score: 0
type: Comment

http://stackoverflow.com/comment/91772015
score: 1
type: Comment
has text: Huh? Why would a *mouse button* click event have a `char` or a `keysym` attribute? What would you expect those to be?
comment on: http://stackoverflow.com/q/52414135
type: QuestionComment

http://stackoverflow.com/comment/91660836
type: Comment
has text: thank you for reply. This is what I did. But I have problem with initalizing InstabotFormView inside Instagram
comment on: http://stackoverflow.com/a/52357919
type: AnswerComment
score: 0

http://stackoverflow.com/q/52309506
tagged with: installation
tagged with: tensorflow
type: Question
has title: How to use transform_graph to optimize Tensorflow model
tagged with: bash
downvote count: 0
answer count: 1
score: 1
has body: I used to use the optimize_for_inference library in optimizing frozen Tensorflow models. However, I have read from different sources that Tensorflow no longer supports it. I came across transform_graph, and its documentation is found here: https://github.com/tensorflow/tensorflow/tree/master/tensorflow/tools/graph_transforms#strip_unused_nodes At first, I ran into errors and found out that I need to install Tensorflow from source (https://www.tensorflow.org/install/install_sources#install_the_pip_package) instead of using PIP. I already re-installed Tensorflow from source, and ran this code in bash (/tensorflor/tensorflow dir): bazel build tensorflow/tools/graph_transforms:transform_graph bazel-bin/tensorflow/tools/graph_transforms/transform_graph \ --in_graph=tensorflow_inception_graph.pb \ --out_graph=optimized_inception_graph.pb \ --inputs='Mul' \ --outputs='softmax' \ --transforms=' strip_unused_nodes(type=float, shape="1,299,299,3") fold_constants(ignore_errors=true) fold_batch_norms fold_old_batch_norms round_weights(num_steps=256)' And ran to again this error: -bash: bazel-bin/tensorflow/tools/graph_transforms/transform_graph: No such file or directory What seems to be the problem?
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52324390

http://stackoverflow.com/comment/91643445
type: AnswerComment
has text: Your solution works, but it's less attractive because 1) you still have some repetition in the `if` / `else` part itself, and 2) the calls now look like `get_next_train(params, True); get_next_train(params, False)` and you have no idea what that boolean parameter means unless you read through the function source.
comment on: http://stackoverflow.com/a/52349089
type: Comment
score: 0

http://stackoverflow.com/comment/91785580
type: Comment
type: QuestionComment
has text: @Goyo updated question with the `TemporaryFile` approach
comment on: http://stackoverflow.com/q/52399118
score: 0

http://stackoverflow.com/comment/91660433
score: 1
comment on: http://stackoverflow.com/q/52357964
type: Comment
type: QuestionComment
has text: can you post `df.to_dict()`?

http://stackoverflow.com/comment/91549304
comment on: http://stackoverflow.com/a/52300199
score: 0
type: AnswerComment
has text: already edited the answer based on your comment. Thank you. Do you know about any other option to decrease exponentially the running time?
type: Comment

http://stackoverflow.com/comment/91607947
comment on: http://stackoverflow.com/q/52327837
type: Comment
type: QuestionComment
has text: Assuming your predicates are strings: `full_predicate_string = ' and '.join(['({0} or not ({0}))'.format(predicate) for predicate in predicates])` No guarantees, but it might be worth a try to see if it helps.
score: 0

http://stackoverflow.com/a/56820746
has body: If you have anaconda install than you just need to use command: conda install PyAudio. In order to execute this command you must set thePYTHONPATH environment variable in anaconda.
upvote count: 4
has comment: http://stackoverflow.com/comment/100194857
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/52283840
type: Answer
has comment: http://stackoverflow.com/comment/115809533

http://stackoverflow.com/q/52373737
has answer: http://stackoverflow.com/a/52374017
has comment: http://stackoverflow.com/comment/91692420
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91692349
favorite count: 0
has answer: http://stackoverflow.com/a/52373872
type: UnansweredQuestion
has body: I'm working with a .csv file that lists Timestamps in one column and Wind Speeds in the second column. I need to read through this .csv file and calculate the percent of time where wind speed was above 2m/s. Here's what I have so far. txtFile = r"C:\Data.csv" line = o_txtFile.readline()[:-1] while line: line = oTextfile.readline() for line in txtFile: line = line.split(",")[:-1] How do I get a count of the lines where the 2nd element in the line is greater than 2? CSV File Sample
has title: How to count lines in a text file with specified values?
tagged with: python
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/91606262
type: QuestionComment
score: 0
has text: @pault why do you divide by `1000.` in `point.latitude + x/1000.`? 0.1km it's `100.`
comment on: http://stackoverflow.com/q/52316725
type: Comment

http://stackoverflow.com/q/52272901
score: 9
upvote count: 9
possible better answer: http://stackoverflow.com/a/52295404
answer count: 3
has answer: http://stackoverflow.com/a/68399866
has answer: http://stackoverflow.com/a/52404596
downvote count: 0
has body: Say that I want to have annotations for documents. Every document can be annotated with multiple labels. In this example, I have 2 annotators (a and b), and they each label two documents. from sklearn.metrics import cohen_kappa_score annotator_a = [ ["a","b","c"], ["d","e"] ] annotator_b = [ ["b","c"], ["f"] ] Annotator_a labels document 1 with labels a, b and c. Annotator_b labels documents 1 with labels b and c. I tried to calculate annotator agreement using: cohen_kappa_score(annotator_a, annotator_b) But this results in an error: ValueError: You appear to be using a legacy multi-label data representation. Sequence of sequences are no longer supported; use a binary array or sparse matrix instead. Any ideas on how I can calculate annotator agreement on this set?
tagged with: scikit-learn
favorite count: 0
accepted answer: http://stackoverflow.com/a/52404596
tagged with: python
tagged with: kappa
type: AnsweredQuestion
has title: Multi Label Annotator agreement with Cohen Kappa
has answer: http://stackoverflow.com/a/52295404
type: Question

http://stackoverflow.com/comment/91528567
score: 0
type: AnswerComment
has text: I mean you `return {'question': format_dict, 'answer': answer_dict}` but look up `qaPair['answers']` in gen_QAPair. (It doesn't affect what I suggested, except that with tuples you don't have to worry about the names matching at all.)
type: Comment
comment on: http://stackoverflow.com/a/52279910

http://stackoverflow.com/comment/91560410
type: Comment
comment on: http://stackoverflow.com/a/52306342
type: AnswerComment
has text: @winteralfs please, edit your question and provide a [mcve]
score: 1

http://stackoverflow.com/comment/91559709
comment on: http://stackoverflow.com/a/52304720
score: 0
has text: How do you add spacing to one side only?
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91678138
has text: @Dschoni I have put some sample test data, between T(temperature) and W(strain)
comment on: http://stackoverflow.com/q/52366673
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91709401
type: QuestionComment
has text: I see, thanks, i'll try figuring it out with those docs!
score: 0
comment on: http://stackoverflow.com/q/52347112
type: Comment

http://stackoverflow.com/q/52286538
tagged with: report
type: UnansweredQuestion
tagged with: python
tagged with: plot
has answer: http://stackoverflow.com/a/52286569
type: Question
has title: How to saving plots and model results to pdf in python?
score: 0
answer count: 1
has body: I know how to save model results to .txt files and saving plots to .png. I also found some post which shows how to save multiple plots on a single pdf file. What I am looking for is generating a single pdf file which can contain both model results/summary and it's related plots. So at the end I can have something like auto generated model report. Can someone suggest me how I can do this?
tagged with: model

http://stackoverflow.com/comment/91728132
type: QuestionComment
comment on: http://stackoverflow.com/q/52391025
has text: Why does the solution from the linked question not work in this case? Because of the bulk insert? For that you should use [`executemany`](http://initd.org/psycopg/docs/cursor.html#cursor.executemany) or [`execute_batch`](http://initd.org/psycopg/docs/extras.html#psycopg2.extras.execute_batch) if speed is important for you.
type: Comment
score: 1

http://stackoverflow.com/a/52374626
answers question: http://stackoverflow.com/q/52366855
has body: g = g.subs(a, a) can never do anything, as it's replacing a thing with itself. To replace a with something else g.subs(a, sy.symbols('alpha')) should be used. The relevant topic in SymPy docs is Assignment does not create a relation. A simpler example: a = sy.symbols('a') b = a + 3 # b is now a+3 a = 5 # b is still a+3 and it will not become 8 At the end of this code, the Python variable a has no relation to the SymPy symbol named "a". The variable is 5; the symbol is still Symbol("a") and will forever be, as SymPy expressions are immutable. Instead of a = 5 one should have done b.subs(a, 5) to perform the substitution. I am interested how the assigned name a= and the string in symbols("a") are connected. They are not connected at all. It's convenient to use Python variable a to point to a symbol named "a", that is the only reason people do that. Unfortunately the pattern then misleads them into thinking that if they put a = something new, that will have an effect on Symbol("a") -- it will not. The only effect is that Python variable now points to something else; the expressions containing Symbol("a") are unaffected.
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91696766
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91697056
accepted answer of: http://stackoverflow.com/q/52366855

http://stackoverflow.com/a/52398786
type: AcceptedAnswer
downvote count: 0
has body: That should do it. With random numbers it is often easier and even faster to just generate a new one instead of modifying the wrong one. def costum_random_sample(size): randomList = [] counter = 0 last_n = -1 while(size != counter): n = random.random() if abs(n - last_n) &lt; 0.05: continue else: randomList.append(n) counter += 1 last_n = n return randomList
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52398419
upvote count: 2
has comment: http://stackoverflow.com/comment/91741841
has comment: http://stackoverflow.com/comment/91741927
has comment: http://stackoverflow.com/comment/91741756
answers question: http://stackoverflow.com/q/52398419
has comment: http://stackoverflow.com/comment/91741920

http://stackoverflow.com/comment/91632727
type: AnswerComment
has text: Read my reply carefully. You should still not be patching at the origin module level. You should be patching where the object is being used.
comment on: http://stackoverflow.com/a/52343145
score: 0
type: Comment

http://stackoverflow.com/a/52394584
type: Answer
upvote count: 4
downvote count: 0
has body: The fine print under get_knots says: Internally, the knot vector contains 2*k additional boundary knots. That means, to get a usable knot array from get_knots, one should add k copies of the left boundary knot at the beginning of array, and k copies of the right boundary knot at the end. Here k is the degree of the spline, which is usually 3 (you asked for LSQUnivariateSpline of default degree, so that's 3). So: kn = s1.get_knots() kn = 3*[kn[0]] + list(kn) + 3*[kn[-1]] c = s1.get_coeffs() s2 = BSpline(kn, c, 3) # not "2" as in your sample; we are working with a cubic spline Now, the spline s2 is the same as s1: Equivalently, kn = 4*[x[0]] + t + 4*[x[-1]] would work: your t list contains only interior knots, so x[0] and x[-1] are added, and then each repeated k times more. The mathematical reason for the repetition is that B-splines need some room to get built, due to their inductive definition which requires (k-1)-degree splines to exist around every interval in which we define the kth degree spline.
type: AcceptedAnswer
score: 4
answers question: http://stackoverflow.com/q/52393145
accepted answer of: http://stackoverflow.com/q/52393145

http://stackoverflow.com/q/52359545
has comment: http://stackoverflow.com/comment/92551996
has answer: http://stackoverflow.com/a/52852025
type: AnsweredQuestion
score: 1
tagged with: python-requests
type: Question
tagged with: xampp
tagged with: export-to-csv
has body: My over all goal is to have an array/list of urls that don't get scraped during a website url scrape the logic as seem in the code sample below is logic for ('scrapy.py'): open url in ('source') ~> find 'a' tags from url in ('source') ~> find 'href' in 'a' tags ~> if value of 'href' is not equal to(!=) ('done') in file ('doneurls.py') ~> then write urls that aren't equal to ('done') into file ('url.py') The code i'm using is 'scrapy.py': from bs4 import BeautifulSoup import requests import csv import os import sys from os.path import dirname, join, abspath sys.path.insert(0, abspath(join(dirname(__file__), '..'))) from doneurls import done source = requests.get('http://localhost/index.php').text soup = BeautifulSoup(source, 'lxml') file = open('./url.py', 'a') csv_writer = csv.writer(file) from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self,tag,attrs): # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, print it. if name == "href": if value != done: csv_writer.writerow('b="'+value+'"') parser = MyHTMLParser() parser.feed(source) file.close() index.php: hello hello hello hello hello hello hello doneurls.py: done = "http://localhost/2.php" This code seems to work and it ignores only one url that I add to doneurls.py and works well, but what i'm looking to do is to add an array of urls to done like this done = { "http://localhost/2.php", "http://localhost/next1.php", "http://localhost/next2.php"} When I try to run 'done' as an array no urls are skipped over at all. I'm using this code to try to not have to scrape urls that I've scraped in the past.
has comment: http://stackoverflow.com/comment/92546083
accepted answer: http://stackoverflow.com/a/52852025
answer count: 1
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
has title: How to not scrape the same url twice?
upvote count: 1
tagged with: python

http://stackoverflow.com/a/52376251
has comment: http://stackoverflow.com/comment/91697470
upvote count: 1
has comment: http://stackoverflow.com/comment/91697419
has body: This method seems fine to me if you are having trouble identifying the index for each one you can use enumerate your lists and return the two indexes for the item you are locating. Although I would recommend staying with the dictionaries, which most likely should be able to accomplish your task lista = ['model taurus', 'make ford', 'color white'] for index, item in enumerate(lista): print(f"{item}: {index}") (xenial)vash@localhost:~/python/stack_overflow$ python3.7 yodish.py model taurus: 0 make ford: 1 color white: 2
has comment: http://stackoverflow.com/comment/91697387
has comment: http://stackoverflow.com/comment/91697453
accepted answer of: http://stackoverflow.com/q/52376009
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52376009
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91697356
has comment: http://stackoverflow.com/comment/91697491
has comment: http://stackoverflow.com/comment/91697380
score: 1

http://stackoverflow.com/a/52303999
downvote count: 1
type: Answer
has body: When reading JSON formatted data from an external file use json.load(file_path) like this: import json with open(file_path, 'r') as j: obj = json.load(j)
upvote count: 0
has comment: http://stackoverflow.com/comment/91571960
answers question: http://stackoverflow.com/q/52303771
score: -1

http://stackoverflow.com/comment/91799734
comment on: http://stackoverflow.com/q/52426691
has text: @brunodesthuilliers Please avoid making personal insults. They violate the SO code of conduct. If you wish to discuss the content of my comments, please address it directly.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91737055
comment on: http://stackoverflow.com/q/52395887
type: Comment
score: 0
has text: @Powerlord i was using it because the sql table is read in a seperate html file which looks for that specific name. Is there a better way to do this?
type: QuestionComment

http://stackoverflow.com/a/52298046
has body: For calculating gradients you can always use np.gradient instead of np.diff. That takes care of your boundary values as well.
type: Answer
has comment: http://stackoverflow.com/comment/91544488
has comment: http://stackoverflow.com/comment/91544181
answers question: http://stackoverflow.com/q/52297890
score: 0

http://stackoverflow.com/comment/91664153
type: Comment
type: QuestionComment
has text: `truckloads_of_asphalt() * 5 * 145`, please call the function.
comment on: http://stackoverflow.com/q/52359878
score: 5

python-3.5
tags question: http://stackoverflow.com/q/52307665
type: Tag
tags question: http://stackoverflow.com/q/52353597
tags question: http://stackoverflow.com/q/52310792
tags question: http://stackoverflow.com/q/52422953
tag name: python-3.5
tags question: http://stackoverflow.com/q/52356645
tags question: http://stackoverflow.com/q/52380638
tags question: http://stackoverflow.com/q/52283087

http://stackoverflow.com/q/52390465
has answer: http://stackoverflow.com/a/52391270
has comment: http://stackoverflow.com/comment/91726457
tagged with: html-table
has title: BeautifulSoup returns No Data Recorded when getting table from web
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91726266
has comment: http://stackoverflow.com/comment/91726742
answer count: 1
has comment: http://stackoverflow.com/comment/91726656
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/52391270
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/91726551
has comment: http://stackoverflow.com/comment/91726178
has comment: http://stackoverflow.com/comment/91726473
score: 0
has comment: http://stackoverflow.com/comment/91726730
tagged with: web-scraping
has body: New to web scraping. I need to get the Daily Observations table(the long table at the end of the page) data from the page: https://www.wunderground.com/history/daily/us/tx/greenville/KGVT/date/2015-01-05?cm_ven=localwx_history The html of the table starts from My code is: url = "https://www.wunderground.com/history/daily/us/tx/greenville/KGVT/date/2015-01-05?cm_ven=localwx_history" html = urlopen(url) soup = BeautifulSoup(html,'lxml') soup.findAll(class_="region-content-observation") And the output is: [ <city-history-observation _nghost-c34=""> Daily Observations No Data Recorded </city-history-observation> ] So it's not getting the table and returned No Data Recorded, but it did get the title. And When I tried soup.findAll(class_="tablesaw-sortable") or soup.findAll('tr') it only returned empty list. Does anyone know where went wrong?

http://stackoverflow.com/comment/91556675
type: Comment
comment on: http://stackoverflow.com/q/52304511
has text: Yep, you should be covered in that regard, then.
score: 0
type: QuestionComment

http://stackoverflow.com/q/52279286
has body: (I have no idea how to name that question. So feel free to edit) I have the following arrays : 3D array containing value for [z, y, x] 3D array containing altitude for [z, y, x] 2D array containing maximum_altitude for [y, x] z, y, x have the same length for the 3 arrays. I would like a new 2D output containing value_at_max_altitude for [y, x] The algorithm should be something like find z where altitude[z, y, x] &gt; max_altitude[y, x] value_at_max_altitude[y, x] = value[z, y, x] How would you do that with numpy? edit: Here is the solution I have actually. But I was wondering if it is possible to use numpy internal functions to avoid loop: # get index of Z for first value != False z = np.argmax(altitude &gt;= max_altitude, axis=0) # z shape is [x, y] ny, nx = z.shape # initialize empty array value_at_max_altitude = np.empty([ny, nx]) # fill value_at_max_altitude for y in range(ny): for x in range(nx): value_at_max_altitude[y, x] = value[z[y, x], y, x]
has answer: http://stackoverflow.com/a/52344013
tagged with: arrays
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91516222
has title: Values and index operations between multidimensional numpy arrays
favorite count: 0
has comment: http://stackoverflow.com/comment/91506681
has comment: http://stackoverflow.com/comment/91516254
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91511743
score: 1
has comment: http://stackoverflow.com/comment/91508694
type: Question
tagged with: numpy

http://stackoverflow.com/comment/91785644
type: Comment
has text: Sorry i meant threading! I need this code to be constantly running alongside my maincode and I've found out the way to do this is using multithreading but I just can't get it to work.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52421142

gmail
type: Tag
tags question: http://stackoverflow.com/q/52355596
tag name: gmail

matplotlib-basemap
tags question: http://stackoverflow.com/q/52295117
tag name: matplotlib-basemap
type: Tag

http://stackoverflow.com/comment/91800547
score: 0
comment on: http://stackoverflow.com/q/52277532
type: Comment
type: QuestionComment
has text: Can you provide the output of "print(df.dtypes)" . O/p for whole df and not a particular column.

http://stackoverflow.com/q/52394306
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/91734979
has title: How to add variable/conditional column in PySpark data frame
has answer: http://stackoverflow.com/a/52395597
score: 2
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/39048229
linked to: http://stackoverflow.com/q/41755003
type: Question
accepted answer: http://stackoverflow.com/a/52394837
answer count: 2
tagged with: pyspark
downvote count: 0
linked to: http://stackoverflow.com/q/39048229
possible better answer: http://stackoverflow.com/a/52395597
has body: I have a data frame which looks like this: Filename Type file1.A.txt file2.A.txt file3.B.txt file4.A.txt file5.B.txt ... I want to add another column, Type, which will depend on the filename. If there is an A in the filename, add A, if there is a B, add B. I've seen something vaguely similar to this in Add column to Data Frame conditionally in Pyspark but I can't see how I can apply this in my case. I can add constants to Spark by df = df.withColumn('NewCol', lit('a')) but how can I alter this expression, using regex, to add a certain string in some cases, and another string in other cases? This is similar to the linked question Spark Equivalent of IF Then ELSE but Michael West's answer is easier to type out and more specific to the problem. However, I think it could still solve the problem (though would be more difficult to read).
has answer: http://stackoverflow.com/a/52394837
tagged with: apache-spark
favorite count: 0
has comment: http://stackoverflow.com/comment/91734491

http://stackoverflow.com/q/52374488
tagged with: instance
linked to: http://stackoverflow.com/q/269496
has comment: http://stackoverflow.com/comment/91693864
has comment: http://stackoverflow.com/comment/91693872
duplicate of: http://stackoverflow.com/q/269496
type: Question
score: 2
has comment: http://stackoverflow.com/comment/91693863
downvote count: 0
tagged with: inheritance
favorite count: 0
has comment: http://stackoverflow.com/comment/91693999
has comment: http://stackoverflow.com/comment/91693845
has comment: http://stackoverflow.com/comment/91694024
has comment: http://stackoverflow.com/comment/91694159
tagged with: python-3.x
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91693838
tagged with: python
has title: What, if any, are the differences between implementing one class as a child of another versus having the child employ an instance of the parent?
has body: so please bear with me on this. I struggle some in understanding certain aspects of the concept of inheritance. As such, I was wondering, what would be the difference between implementing one class, say "Child", as the child of another, say "Parent", versus simply making "Child" create and utilize a "Parent" object within itself? For example, given the parent class as: class Parent: def __init__(self, arg): self.arg = arg def parent_method(self): print(self.arg) What would be the difference between making and implementing a child class: class Child(Parent): def __init__(self, arg): super().__init__(arg) Child('foo').parent_method() Versus: class Child: def __init__(self, arg): self.parent = Parent(arg) def call_method(self): self.parent.parent_method() Child('foo').call_method() Both of which simply print: foo Is the only difference here syntactical? I mean, it definitely seems more efficient to use inheritance here, but is there something else I'm missing? Thanks!

http://stackoverflow.com/q/52345293
has body: I have been working with tweepy and raspberry pi (3b) units for some time now, and I decided to reflash/repurpose my raspberry pi zero (w/ camera) to create a monitoring twitter bot. I have used tweepy on my pi 3B to gather tweets, and even do some tweet automation. But, for some reason, I have been getting the following error when I try to execute a simple test tweet script on my pi zero. Traceback (most recent call last): File "test_tweet.py", line 15, in &lt;module&gt; api.update_status("successful!") File "/usr/local/lib/python2.7/dist-packages/tweepy/api.py", line 194, in update_status )(post_data=post_data, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/tweepy/binder.py", line 250, in _call return method.execute() File "/usr/local/lib/python2.7/dist-packages/tweepy/binder.py", line 192, in execute six.reraise(TweepError, TweepError('Failed to send request: %s' % e), sys.exc_info()[2]) File "/usr/local/lib/python2.7/dist-packages/tweepy/binder.py", line 190, in execute proxies=self.api.proxy) File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 488, in request resp = self.send(prep, **send_kwargs) File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 609, in send r = adapter.send(request, **kwargs) File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 497, in send raise SSLError(e, request=request) tweepy.error.TweepError: Failed to send request: ("bad handshake: Error([('', 'osrandom_rand_bytes', 'getrandom() initialization failed.')],)",) here's my python code in test_tweet.py import tweepy def tweepy_creds(): auth = tweepy.OAuthHandler("conskeyhere", "conssecret") auth.set_access_token("accesstoken", "accesstokensecret") return tweepy.API(auth) if __name__ == "__main__": api = tweepy_creds() api.update_status("successful!") it's the first time I encountered such an error. /ogs
tagged with: python
type: Question
tagged with: raspberry-pi
linked to: http://stackoverflow.com/q/48843728
has comment: http://stackoverflow.com/comment/91637036
duplicate of: http://stackoverflow.com/q/48843728
has title: TweepError: bad handshake 'osrandom_rand_bytes'
has comment: http://stackoverflow.com/comment/91637463
score: 0
has comment: http://stackoverflow.com/comment/91637434
has comment: http://stackoverflow.com/comment/91637512
tagged with: tweepy
answer count: 0
type: UnansweredQuestion

hdf5
tags question: http://stackoverflow.com/q/52326888
tags question: http://stackoverflow.com/q/52394252
tags question: http://stackoverflow.com/q/52315663
type: Tag
tags question: http://stackoverflow.com/q/52290434
tags question: http://stackoverflow.com/q/52283402
tag name: hdf5

http://stackoverflow.com/a/52311492
score: 6
has body: Well, this is exactly the kind of question that could really do with some experiments &amp; code snippets provided... Anyway, it seems that the general answer is a firm no: not only between Python and Spark MLlib, but even between Spark sub-modules, or between Python &amp; Numpy... Here is some reproducible code, run in the Databricks community cloud (where pyspark is already imported &amp; the relevant contexts initialized): import sys import random import pandas as pd import numpy as np from pyspark.sql.functions import rand, randn from pyspark.mllib import random as r # avoid conflict with native Python random module print("Spark version " + spark.version) print("Python version %s.%s.%s" % sys.version_info[:3]) print("Numpy version " + np.version.version) # Spark version 2.3.1 # Python version 3.5.2 # Numpy version 1.11.1 s = 1234 # RNG seed # Spark SQL random module: spark_df = sqlContext.range(0, 10) spark_df = spark_df.select("id", randn(seed=s).alias("normal"), rand(seed=s).alias("uniform")) # Python 3 random module: random.seed(s) x = [random.uniform(0,1) for i in range(10)] # random.rand() gives exact same results random.seed(s) y = [random.normalvariate(0,1) for i in range(10)] df = pd.DataFrame({'uniform':x, 'normal':y}) # numpy random module np.random.seed(s) xx = np.random.uniform(size=10) # again, np.random.rand(10) gives exact same results np.random.seed(s) yy = np.random.randn(10) numpy_df = pd.DataFrame({'uniform':xx, 'normal':yy}) # Spark MLlib random module rdd_uniform = r.RandomRDDs.uniformRDD(sc, 10, seed=s).collect() rdd_normal = r.RandomRDDs.normalRDD(sc, 10, seed=s).collect() rdd_df = pd.DataFrame({'uniform':rdd_uniform, 'normal':rdd_normal}) And here are the results: Native Python 3: # df normal uniform 0 1.430825 0.966454 1 1.803801 0.440733 2 0.321290 0.007491 3 0.599006 0.910976 4 -0.700891 0.939269 5 0.233350 0.582228 6 -0.613906 0.671563 7 -1.622382 0.083938 8 0.131975 0.766481 9 0.191054 0.236810 Numpy: # numpy_df normal uniform 0 0.47…
accepted answer of: http://stackoverflow.com/q/52293899
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/52293899

distribution
tags question: http://stackoverflow.com/q/52393334
tag name: distribution
type: Tag

http://stackoverflow.com/a/52281242
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52280524
has body: You can use pd.pivot_table: res = df.pivot_table(index='ID', columns='Status', values='Country', aggfunc=', '.join) print(res) Status Go Pause Stop ID ABC USA, Egypt Japan Columbia DEF Canada None Peru
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52280524
has comment: http://stackoverflow.com/comment/91516618

http://stackoverflow.com/comment/91587788
has text: Thank you! Yes, it's a helpful link. Figsize is exactly what I needed.
comment on: http://stackoverflow.com/q/52315947
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52333540
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/91614021
tagged with: python
has answer: http://stackoverflow.com/a/52345446
has body: EDIT: Clarifying the allowed character set based on comments The allowed characters from ASCII character set are a-z, A-Z, 0-9, -, _, ., /. Any other character from ASCII set should not be allowed. Unicode characters apart from the disallowed ASCII set defined above are also allowed. End of Edit I am processing some text data where the only allowed ASCII characters are a-z, A-Z, 0-9, and -,_,.,/. Apart from these Unicode characters are also allowed. I need to make sure that the incoming data contains only these set of characters. Checking for the allowed ASCII characters is easy: from string import ascii_letters, digits VALID_CHARSET= set(ascii_letters + digits + "-_./") def is_valid_string(string): for c in string: if c not in VALID_CHARSET: return False return True But I am wondering about how to allow unicode characters apart from the above. I guess in Python-2.7 I could add a check like so: if isinstance(c, unicode) return True if c not in VALID_CHARSET: return False But strings in Python-3 are Unicode by default and there is no separate unicode type, so this would not work there. Any cleaner way of doing this which works in both the versions of Python?
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/91631347
accepted answer: http://stackoverflow.com/a/52345446
has comment: http://stackoverflow.com/comment/91614015
tagged with: unicode
has comment: http://stackoverflow.com/comment/91615402
has title: Check if a character is Unicode in a way compatible with Python 2 and 3
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/91614750
answer count: 1
has comment: http://stackoverflow.com/comment/91615103
has comment: http://stackoverflow.com/comment/91631336
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/91605270
type: Comment
comment on: http://stackoverflow.com/a/52323418
type: AnswerComment
score: 0
has text: Hello Helio, thanks for the answer but I have one more question: Can I force the file encoding of a RF file like we do in python (# -*- coding: utf-8 -*-)?

http://stackoverflow.com/q/52416370
has title: Replacing number on the edges
tagged with: pandas
tagged with: python
favorite count: 0
has body: I am having a dataframe with 0s and 127s only. The 127s are clumped together as given in the example. df = DataFrame({'f1' : [0,0,0,0,0,0], 'f2' : [0,0,0,0,0,0], 'f3' : [0,0,127,127,0,0], 'f4' : [0,127,127,127,0,0], 'f5' : [0,127,127,127,127,0], 'f6' : [0,127,127,127,127,0], 'f7' : [0,0,127,127,127,0], 'f8' : [0,0,127,127,0,0], 'f9' : [0,0,127,0,0,0], 'f10' : [0,0,0,0,0,0] }) f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 127 127 127 0 0 0 0 2 0 0 127 127 127 127 127 127 127 0 3 0 0 127 127 127 127 127 127 0 0 4 0 0 0 0 127 127 127 0 0 0 5 0 0 0 0 0 0 0 0 0 0 Given a list of numbers num_of_cells_to_del, I want to randomly clear that many cells in a particular column randomly from top or bottom. num_of_cells_to_del = [0,0,0,1,1,2,2,1,0,0] Result: f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 127 0 0 0 0 0 2 0 0 127 127 127 0 0 0 127 0 3 0 0 127 127 127 127 127 127 0 0 4 0 0 0 0 0 127 0 0 0 0 5 0 0 0 0 0 0 0 0 0 0
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/52430720
score: 1
has answer: http://stackoverflow.com/a/52417106
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/a/52305581
score: 4
answers question: http://stackoverflow.com/q/52305421
type: Answer
has body: This doesn't really explain why it was happening, but a fix is: $ conda config --add pinned_packages conda-forge::numpy
has comment: http://stackoverflow.com/comment/91600786
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/91657044
type: Comment
type: QuestionComment
has text: Possible duplicate of [Need help solving a second order non-linear ODE in python](https://stackoverflow.com/questions/19779217/need-help-solving-a-second-order-non-linear-ode-in-python)
comment on: http://stackoverflow.com/q/52354171
score: 0

discord.py
tags question: http://stackoverflow.com/q/52343245
tags question: http://stackoverflow.com/q/52358080
tags question: http://stackoverflow.com/q/52410570
tags question: http://stackoverflow.com/q/52360088
tags question: http://stackoverflow.com/q/52336409
tags question: http://stackoverflow.com/q/52416472
tags question: http://stackoverflow.com/q/52289010
tags question: http://stackoverflow.com/q/52415743
tags question: http://stackoverflow.com/q/52414070
tags question: http://stackoverflow.com/q/52287487
tags question: http://stackoverflow.com/q/52350850
tags question: http://stackoverflow.com/q/52394172
tags question: http://stackoverflow.com/q/52356984
tags question: http://stackoverflow.com/q/52355348
tags question: http://stackoverflow.com/q/52411903
tags question: http://stackoverflow.com/q/52355758
tags question: http://stackoverflow.com/q/52349101
tags question: http://stackoverflow.com/q/52276346
tags question: http://stackoverflow.com/q/52323656
tags question: http://stackoverflow.com/q/52360859
tags question: http://stackoverflow.com/q/52354841
tags question: http://stackoverflow.com/q/52334477
tags question: http://stackoverflow.com/q/52413417
tags question: http://stackoverflow.com/q/52356064
tags question: http://stackoverflow.com/q/52331065
tags question: http://stackoverflow.com/q/52298850
type: Tag
tags question: http://stackoverflow.com/q/52356043
tags question: http://stackoverflow.com/q/52428769
tags question: http://stackoverflow.com/q/52396370
tags question: http://stackoverflow.com/q/52346022
tag name: discord.py
tags question: http://stackoverflow.com/q/52348148
tags question: http://stackoverflow.com/q/52409726
tags question: http://stackoverflow.com/q/52393542

http://stackoverflow.com/q/52356956
tagged with: pycrypto
has body: I'm trying to complete this challenge online which asks to implement ourselves the AES CBC mode without using any library function that will do the job for me (ofc xD). I'm using python3.7 and PyCrypto for the AES modules (I'm a python beginner btw) I'm at a point where I feel like I found the solution but it's not the case, I don't see what I'm doing wrong. I'm entering this text: ` In september 2017 In september 2017 In september 2017 In september 2017 ` with this key: YELLOW SUBMARINE and with an 16 bytes long IV full of 0 (\x00) but my ouput differs from the different websites I can find online or when using the AES CBC mode from the PyCrypto module here's the small program that I made so far in order to generate my aes cbc encryption with comments: #!/usr/bin/env python from sys import argv from Crypto.Cipher import AES import codecs def pad(plaintext): padding_len = 16 - (len(plaintext) % 16) print(padding_len) if padding_len == 16: return plaintext padding = bytes([padding_len] * padding_len) return plaintext + padding def xor_for_char(input_bytes, key_input): index = 0 output_bytes = b'' for byte in input_bytes: if index &gt;= len(key_input): index = 0 output_bytes += bytes([byte ^ key_input[index]]) index += 1 return output_bytes class AESCBCTool: def __init__(self): self.best_occurence = 0 self.best_line = 0 def encrypt_CBC(self, enc, key): enc = pad(enc) # here I pad the text (PCKS#7 way) nb_blocks = (int)(len(enc) / 16) #calculate the number of blocks I've to iter through IV = bytearray(16) cipher = AES.new(key, AES.MODE_ECB) for i in range(nb_blocks): enc2 = xor_for_char(enc[i * 16:(i + 1) * 16], IV) #xor a block with IV IV = cipher.encrypt(enc2) # set the the IV based on the encryption of the xored text print(codecs.decode(codecs.encode(IV, 'base64')).replace("\n", ""), end='') #print the encrypted text in base 64 def main(filepath): f = open(filepath, "r") if f.mode == 'r': content = f.readlines() tool = AESCBCTool() for line_content in content: tool.…
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/91753879
favorite count: 0
has title: Python Implement AES in CBC encryption mode
tagged with: python
tagged with: aes
answer count: 0
upvote count: 3
type: UnansweredQuestion
tagged with: encryption
tagged with: cbc-mode
score: 3
has comment: http://stackoverflow.com/comment/91662592

http://stackoverflow.com/a/52385405
answers question: http://stackoverflow.com/q/52385146
score: 0
type: Answer
has body: There are a few problems with your code. The function is supposed to return a string but you declare middle_list as a list not a string. The index method returns the position in the list of its argument. You want to use [] for access. You are not retrieving the character from the item, but the item from the list. The corrected code could look like below: def get_mid_letter(a_list): middle_list = "" # declare the variable as an empty string for item in a_list: middle_index = int(len(item) / 2) # get the middle index middle_letter = item[middle_index] # get the char from the string in the list middle_list += middle_letter # concatenate the char and the string return middle_list.lower()

http://stackoverflow.com/a/52356976
downvote count: 0
has comment: http://stackoverflow.com/comment/91658658
has comment: http://stackoverflow.com/comment/91658489
has comment: http://stackoverflow.com/comment/91658969
upvote count: 2
has comment: http://stackoverflow.com/comment/91659014
has body: Hey bud you got a lot going on in here, you can simple this down using a list to store your facts, heres a better format that you can build off of. As mentioned by @JonClements we can use random.randrange(len(facts)) this will make our code more adaptable if we want to alter the amount of facts in our list. import random while True: name = input("\nHello, Who am I speaking to?\n") print(f"\nWelcome, {name}! Lets see what you rolled..." facts = [ 'Fact one', 'Fact two', 'Fact three', 'Fact four', 'Fact five', 'Fact six', 'Fact seven', 'Fact eight', 'Fact nine', 'Fact ten' ] selection = random.randrange(len(facts)) print(facts[selection])
has comment: http://stackoverflow.com/comment/91659126
has comment: http://stackoverflow.com/comment/91659040
has comment: http://stackoverflow.com/comment/91694033
has comment: http://stackoverflow.com/comment/91658527
answers question: http://stackoverflow.com/q/52356803
type: Answer
has comment: http://stackoverflow.com/comment/91658539
score: 2
has comment: http://stackoverflow.com/comment/91659085

http://stackoverflow.com/comment/91793360
has text: i'm pretty sure i've seen this problem before here on StackOverflow, let me try to find a relevant answer
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52424333
score: 0

http://stackoverflow.com/comment/91665722
comment on: http://stackoverflow.com/q/52360674
score: 0
type: Comment
type: QuestionComment
has text: You initializrd board to have the same single list as all rows. Probably something like `board = [[] * 3]` instead of `board = [[], [], []]`

http://stackoverflow.com/a/52365658
type: Answer
answers question: http://stackoverflow.com/q/52365108
has body: You can use Lable and StringVar. The Label widget is a standard Tkinter widget used to display a text or image on the screen. The label can only display text in a single font, but the text may span more than one line. In addition, one of the characters can be underlined, for example, to mark a keyboard shortcut. Here is a good explanation on how to use it check it out!. Edit If you want the user to be able to display data that the user can manipulate in place, it’s probably easier to use the Canvas widget. Hope this helps!
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52365108

configure
tags question: http://stackoverflow.com/q/52355129
tag name: configure
type: Tag

http://stackoverflow.com/q/52374591
has comment: http://stackoverflow.com/comment/91695083
tagged with: concatenation
tagged with: pandas
has comment: http://stackoverflow.com/comment/91726125
answer count: 1
favorite count: 0
tagged with: python
has title: concatenate dataframes one by one
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91712465
has comment: http://stackoverflow.com/comment/91732756
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52393920
accepted answer: http://stackoverflow.com/a/52393920
tagged with: dataframe
has body: The below code reads files saves them in data frames and then concatenates all of them and after concatenation resamples data persecond. Since this is too hard on memory. What I want is to do this piece by piece. For instance I read two files concate them resample them. then read the next file concatenate it with resultant of first two files and resample and so on for 10 files, file by file. How can I change the code. Can someone help me with that.Following is my code import pandas as pd import os #import matplotlib.pyplot as plt #df1 = pd.read_hdf("E:\examples\hdf files\conew1.h5", 'df') #df2 = pd.read_hdf("E:\examples\hdf files\conew2.h5", 'df') #df3 = pd.read_hdf("E:\examples\hdf files\conew3.h5", 'df') hdfdirectory = "E:\examples\hdf files" number_of_dfs=1 df=None for fi in os.listdir(hdfdirectory): hdfpath = os.path.join(hdfdirectory, fi) print hdfpath df1 = pd.read_hdf(hdfpath, 'df') for i in range(number_of_dfs): if df is None: df=pd.DataFrame({'timestamp':df1.timestamp , 'url' : df1.url}) dft = df.set_index('timestamp').resample('S').count() else: temp=pd.DataFrame({'timestamp':df1.timestamp , 'url' :df1.url}) tempt = temp.set_index('timestamp').resample('S').count() df=pd.concat([dft,tempt])
score: 0

http://stackoverflow.com/comment/91779771
comment on: http://stackoverflow.com/q/52418213
has text: Looks like your center of rotation is not in the center of mass or changing for each rotation step.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/57400423
type: Answer
has body: I found a decent solution here: http://chris35wills.github.io/matplotlib_diverging_colorbar/ They created a normalization class using this code: class MidpointNormalize(colors.Normalize): def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): self.midpoint = midpoint colors.Normalize.__init__(self, vmin, vmax, clip) def __call__(self, value, clip=None): # I'm ignoring masked values and all kinds of edge cases to make a # simple example... x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1] return np.ma.masked_array(np.interp(value, x, y), np.isnan(value)) The class is used by doing something like this: elev_max=3000; mid_val=0; plt.imshow(ras, cmap=cmap, clim=(elev_min, elev_max), norm=MidpointNormalize(midpoint=mid_val,vmin=elev_min, vmax=elev_max)) plt.colorbar() plt.show()
score: 4
has comment: http://stackoverflow.com/comment/101287958
answers question: http://stackoverflow.com/q/52411520
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/52303043
has answer: http://stackoverflow.com/a/52349937
has comment: http://stackoverflow.com/comment/91587931
has comment: http://stackoverflow.com/comment/91838371
score: 7
has body: I am trying to run a Flask app which consists of: Yielding API requests on the fly Uploading each request to a SQLalchemy database Run jobs 1 and 2 as a background process For that I have the following code: import concurrent.futures import queue from concurrent.futures import ThreadPoolExecutor from flask import Flask, current_app app = Flask(__name__) q = queue.Queue() def build_cache(): # 1. Yielding API requests on the fly track_and_features = spotify.query_tracks() # &lt;- a generator while True: q.put(next(track_and_features)) def upload_cache(tracks_and_features): # 2. Uploading each request to a `SQLalchemy` database with app.app_context(): Upload_Tracks(filtered_dataset=track_and_features) return "UPLOADING TRACKS TO DATABASE" @app.route("/cache") def cache(): # 3. Do `1` and `2` as a background process with concurrent.futures.ThreadPoolExecutor() as executor: future_to_track = {executor.submit(build_cache): "TRACKER DONE"} while future_to_track: # check for status of the futures which are currently working done, not_done = concurrent.futures.wait( future_to_track, timeout=0.25, return_when=concurrent.futures.FIRST_COMPLETED, ) # if there is incoming work, start a new future while not q.empty(): # fetch a track from the queue track = q.get() # Start the load operation and mark the future with its TRACK future_to_track[executor.submit(upload_cache, track)] = track # process any completed futures for future in done: track = future_to_track[future] try: data = future.result() except Exception as exc: print("%r generated an exception: %s" % (track, exc)) del future_to_track[future] return "Cacheing playlist in the background..." All of the above works, BUT NOT AS A BACKGROUND PROCESS. The app hangs when cache() is called, and resumes only when the process is done. I run it with gunicorn -c gconfig.py app:app -w 4 --threads 12 what am I doing wrong? EDIT: If simplify things in order do debug this, and write simply: # 1st background process def build_cache(): # o…
upvote count: 7
has comment: http://stackoverflow.com/comment/91588052
possible better answer: http://stackoverflow.com/a/52447979
accepted answer: http://stackoverflow.com/a/52349937
type: Question
has comment: http://stackoverflow.com/comment/91587502
has comment: http://stackoverflow.com/comment/91588218
has comment: http://stackoverflow.com/comment/91584476
has comment: http://stackoverflow.com/comment/91566707
tagged with: flask
answer count: 2
has comment: http://stackoverflow.com/comment/91584741
downvote count: 0
tagged with: concurrent.futures
tagged with: flask-sqlalchemy
favorite count: 0
has comment: http://stackoverflow.com/comment/91584097
tagged with: python
has title: Flask - job not running as a background process
has answer: http://stackoverflow.com/a/52447979
has comment: http://stackoverflow.com/comment/91587901
has comment: http://stackoverflow.com/comment/91584405
type: AnsweredQuestion

http://stackoverflow.com/comment/91586164
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52317039
type: AnswerComment
has text: Then given that you cannot share the input data to the broken program, nor the output of the broken program, nor the broken program itself, I'm afraid that all the advice that remains to give is this: ***Fix the broken program.*** Sorry, but you're in no position to ask for help given that you're unable to share anything that would enable anyone to help you.

http://stackoverflow.com/a/75774439
type: Answer
score: -2
downvote count: 2
has body: Try to install python from Microsoft stores
upvote count: 0
answers question: http://stackoverflow.com/q/52332554
has comment: http://stackoverflow.com/comment/133744263

http://stackoverflow.com/q/52416187
type: Question
has title: What does Imputer.fit with nan value do?
accepted answer: http://stackoverflow.com/a/52416271
has body: I'm learning machine learning using the scikit-learn library and I was puzzled when I see the code from Scikit-learn tutorial It has the following code: import numpy as np from sklearn.impute import SimpleImputer imp = SimpleImputer(missing_values=np.nan, strategy='mean') imp.fit([[1, 2], [np.nan, 3], [7, 6]]) X = [[np.nan, 2], [6, np.nan], [7, 6]] print(imp.transform(X)) From what I understand, imputer is used to fill in the missing values, and that it uses some strategy like mean, median or mode. But I don't understand what these 3 lines of code are doing imp.fit([[1, 2], [np.nan, 3], [7, 6]]) X = [[np.nan, 2], [6, np.nan], [7, 6]] print(imp.transform(X)) Why does it fit a matrix with np.nan ? And how these fitting affect the imp.transform(X)?
answer count: 1
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has answer: http://stackoverflow.com/a/52416271
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2

http://stackoverflow.com/a/52324233
type: Answer
answers question: http://stackoverflow.com/q/52323647
score: 2
accepted answer of: http://stackoverflow.com/q/52323647
upvote count: 2
has body: Et1["foreground"] doesn't give you a string. It gives you some tk type object. You will have to convert it to string before, like: if str(Et1["foreground"])=="green": Your full code is: #Libraries import tkinter as tk from tkinter import ttk #Class to variables win=tk.Tk() Et1=ttk.Label(win,text="Text",foreground="green") Et1.grid(column=0,row=0) if str(Et1["foreground"])=="green": print("It is green") else: print("It is not green") #Run loop win.mainloop()
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52309420
score: 5
has body: I was trying to understand what the confidences score outputted by rasa nlu(ver-0.12.3) actually are and how they are computed. I have been working on intent classification task with tensorflow embedding. Once my model is trained and I parse new/test data, I receive a confidence score along with each probable intent. But I have little to no idea of what actually this confidence score represents. As mentioned in docs, it does not represent probability. And after some observation of results, it seems to be a one-many type evaluation i.e. for a single text input, I can get multiple intents with high confidence scores. After having a quick look at the code, I think it is computed in “_tf_sim” function in “embedding_intent_classifier.py” file (Relevant code segment below) Can somebody please confirm/clarify on how it works or what exactly a confidence score means here? def _tf_sim(self, a, b): """Define similarity""" if self.similarity_type == 'cosine': a = tf.nn.l2_normalize(a, -1) b = tf.nn.l2_normalize(b, -1) if self.similarity_type == 'cosine' or self.similarity_type == 'inner': sim = tf.reduce_sum(tf.expand_dims(a, 1) * b, -1) # similarity between intent embeddings sim_emb = tf.reduce_sum(b[:, 0:1, :] * b[:, 1:, :], -1) return sim, sim_emb else: raise ValueError("Wrong similarity type {}, " "should be 'cosine' or 'inner'" "".format(self.similarity_type))
answer count: 1
downvote count: 0
favorite count: 0
tagged with: metrics
tagged with: python
has title: Rasa NLU: Confidence Score Computation
has answer: http://stackoverflow.com/a/53388890
tagged with: tensorflow
type: AnsweredQuestion
upvote count: 5
tagged with: rasa-nlu
type: Question
accepted answer: http://stackoverflow.com/a/53388890

http://stackoverflow.com/a/70952743
has body: from selenium import webdriver chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('disable-notifications') driver = webdriver.Chrome(executable_path="C:\Users\PycharmProjects\chromedriver_win32\chromedriver.exe", options=chrome_options) driver.maximize_window() This works with the right placement of code: Click here for Image-->ChromeOptions Pycharm Code Image
type: Answer
answers question: http://stackoverflow.com/q/52407331
has comment: http://stackoverflow.com/comment/125431468
score: 0

http://stackoverflow.com/comment/91625547
has text: Also, which `cv2` package are you using -- the official one or [`opencv-python`](https://pypi.org/project/opencv-python/)? Which OS and Python implementation? Are you using this from an interactive console or ipython/jupyter?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52337870
score: 0

http://stackoverflow.com/a/52323667
has comment: http://stackoverflow.com/comment/91594627
type: Answer
has comment: http://stackoverflow.com/comment/91594602
downvote count: 0
has comment: http://stackoverflow.com/comment/91594906
has body: Why can't you slice the list every time, because remove will be a costly operation list1=[i for i in range(1234)] #some huge list print(len(list1)) #1234 j=40 while(j&lt;len(list1)): new_list=list1[j-40:j] #slice the list for 40 elements print(len(new_list)) ''' add your processing here (like submitting)''' j+=40 new_list=list1[j-40:] #the last part of the list print(len(new_list)) A generalized version to break a list into even sized chunks : n=40 #In this case new_list = [my_list[i * n:(i + 1) * n] for i in range((len(my_list) + n - 1) // n )] new_list is a list of lists with each list of size 40 (Maybe except the last one)
answers question: http://stackoverflow.com/q/52323642
score: 1
has comment: http://stackoverflow.com/comment/91594843
upvote count: 1

http://stackoverflow.com/comment/121015995
has text: I have the same error, and I'm basically using .contains on a specific column of my df. I chcked it, and it does not have any NaN's. I added the na=False, and the error disappears. How could I explain the error I get, even though the column I am working with is a string with no NaNs? So I am using this line: df_main = df_main[~df_main['Category'].str.contains('|'.join(searchfor))], where searchfor is a list of words. Doing this generates the error
score: 1
type: Comment
comment on: http://stackoverflow.com/a/52297788
type: AnswerComment

http://stackoverflow.com/comment/91800968
type: Comment
has text: 'or you possible have a design issue', ok this gets to the heart of my question really. If I'm running into trouble here then its possibly a design issue (and maybe I have fallen into a bad pattern). Thanks for the help!
comment on: http://stackoverflow.com/a/52427735
score: 0
type: AnswerComment

http://stackoverflow.com/q/52347363
downvote count: 1
type: Question
has title: What does this construct in Pyramid mean?
has answer: http://stackoverflow.com/a/52349252
has comment: http://stackoverflow.com/comment/91652068
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: pyramid
has body: Construction from pyramid docs @classmethod def all(cls, request): query = request.dbsession.query(BlogRecord) return query.order_by(sa.desc(BlogRecord.created)) I don't understand what's going on in this statement. query = request.dbsession.query(BlogRecord) As I understand we create an example of a query class, but what do we get from: query(BlogRecord) inheritance from BlogRecord? request.dbsession.query I have no idea.
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/52349252

svd
type: Tag
tags question: http://stackoverflow.com/q/52334923
tag name: svd

http://stackoverflow.com/comment/91574064
score: 0
type: Comment
has text: pre is a module in Preprocessing module which creates a dataframe with 1 column(col) with a column name (cat_colss[i])
comment on: http://stackoverflow.com/q/52293749
type: QuestionComment

http://stackoverflow.com/comment/91561407
type: Comment
comment on: http://stackoverflow.com/q/52307091
type: QuestionComment
score: 2
has text: `%y` is for 2 digit years, you want `%Y`.

http://stackoverflow.com/comment/136737471
type: QuestionComment
comment on: http://stackoverflow.com/q/52338103
has text: related: https://stackoverflow.com/q/44810175
score: 0
type: Comment

http://stackoverflow.com/a/52313504
downvote count: 0
has comment: http://stackoverflow.com/comment/91662181
has comment: http://stackoverflow.com/comment/91662000
has comment: http://stackoverflow.com/comment/91676600
type: Answer
has comment: http://stackoverflow.com/comment/91662260
upvote count: 2
has comment: http://stackoverflow.com/comment/91690666
score: 2
has comment: http://stackoverflow.com/comment/91662432
accepted answer of: http://stackoverflow.com/q/52304507
has body: If you want to use Djangos ORM to build that query, you should use the relationship fields. First, I suggest you change the field to this: QUEUE = models.ForeignKey(to=Queue, on_delete=models.PROTECT) And then try something like this: import datetime from django.utils import timezone as tz now = tz.now() filter_date = now - datetime.timedelta(hours=...something...) qs = Message.objects.filter( STATUS1=0, DIRECTION=0, DATE_CREATED__gte=filter_date) You may want to look into QuerySet.annotate(). This still needs to be tweeked to fit your exact query, but my answer should but you on the right course to figure it out.
answers question: http://stackoverflow.com/q/52304507
type: AcceptedAnswer

http://stackoverflow.com/a/53346933
has body: Extracting the meaning of a sentence is a quite arbitrary task. What do you mean by the meaning? Using spaCy you can extract the dependencies between the words (which specify the meaning of the sentence), find the POS tags to check how words are used in the sentence and also find places, organizations, people using NER tagger. However, meaning of the sentence is too general even for the humans. Maybe you are searching for a specific meaning? If that's the case, you have to train your own classifier. This will get you started. If your task is summarization of a couple of sentences, consider also using gensim . You can have a look here. Hope it helps :)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52280334

http://stackoverflow.com/comment/97576783
type: Comment
comment on: http://stackoverflow.com/a/55324426
score: 0
type: AnswerComment
has text: @abhi I edited the answer to answer your questions. Namely by adding more comments to the bash script and breaking down the line we add to PAM. Let me know if you need me to explain anything else.

http://stackoverflow.com/comment/91665734
comment on: http://stackoverflow.com/q/52360674
score: 0
type: Comment
type: QuestionComment
has text: What was the expected result? And you you know that Python starts at 0?

http://stackoverflow.com/comment/91655632
score: 0
type: QuestionComment
has text: Finding C1 and C2 constants that minimize the sum of the locale failure.
type: Comment
comment on: http://stackoverflow.com/q/52355463

http://stackoverflow.com/comment/103851026
type: AnswerComment
has text: @passinger, not quite sure what you mean. Those numbers are the point estimates of the area under the ROC curve. The question just imported that from as `from sklearn.metrics import roc_auc_score`.
type: Comment
comment on: http://stackoverflow.com/a/52434908
score: 0

http://stackoverflow.com/a/52332726
has comment: http://stackoverflow.com/comment/91612999
answers question: http://stackoverflow.com/q/52332361
upvote count: 6
has comment: http://stackoverflow.com/comment/91613098
has comment: http://stackoverflow.com/comment/91612693
type: Answer
has comment: http://stackoverflow.com/comment/91612565
downvote count: 0
score: 6
has body: The attribute you put in the find_all call is the thing you have, not the thing you want to find. Here you have the class, so use that: for a in soup.find_all('a', class_="pet-card__link"): print("Found the URL:", a['href']) (Because class is a reserved word in Python, you need to use class_ here.)

http://stackoverflow.com/q/52294855
has comment: http://stackoverflow.com/comment/91540758
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91538919
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/91657123
has title: How to automatically update data without refreshing page python flask?
type: Question
tagged with: jquery
has comment: http://stackoverflow.com/comment/91537518
tagged with: flask
favorite count: 0
score: 0
has body: How to automatically update data wihtout refreshing the webpage and add a comment, say if the data keeps increasing - ON, otherwise OFF? I get my json data from a URL like this: @app.route('/data', methods=['GET']) def data(): params = { 'api_key': '{API_KEY}', } url='https://xxx.xxx.xxx.xxx:xxxx/yy/yy/' r= requests.get(url, params=params, verify=False).content return render_template('data.html', time=json.loads(r)['time']) html: {% block body %} data {% for ON in time %} {{ON["time"]}} {% endfor %}
tagged with: python
has comment: http://stackoverflow.com/comment/91671435
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91739114
has text: What does `dir \Users\xxxx\Desktop` from `cmd` show?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52397304

http://stackoverflow.com/q/52313288
tagged with: cplex
tagged with: list
has title: Insufficient memory while solving large quadratic programming problem using Cplex Python API
has comment: http://stackoverflow.com/comment/91577411
has comment: http://stackoverflow.com/comment/91583573
score: 0
tagged with: memory
has body: I am trying to solve a large quadratic programming problem using IBM Cplex Python API. I am running out memory while constructing the qMat matrix which defines the quadratic part of the problem on a Linux machine with 120 GB RAM. In the sample code below, qMat has 10 rows. In the actual problem I have about 100,000 rows. And each row has 10 - 1000 non-zero columns. The machine runs out of memory while constructing qMat which is a list of lists, each of which has two lists (one indicating columns, another indicating values). In other words, the machine runs out of memory even before it loads the problem into Cplex. It would help if you can suggest another way of developing qMat, and or loading such data into Cplex. I can of course write qMat line by line into a txt file but can such a file be loaded into Cplex? The reason the code below is as follows is because qMatIndexes need to computed only once as net is fixed. But qMat itself needs to computed many times because it depends on mDict. I basically need to run Cplex optimization many times for many mDicts, with sparse Q matrix of 100,000 times 100,000 dimension. It is this sparse Q matrix which qMat represents. from __future__ import division import copy import numpy as np import collections import cplex from cplex.exceptions import CplexError import sys import random import cjson from pympler.asizeof import asizeof from scipy.sparse import csr_matrix net = collections.OrderedDict([(1, [1, 2, 4]), (2, [2, 3, 4]), (3, [3, 4]), (4, [1, 4])]) mDict = {1:10,2:20,3:30,4:40} def write_qMat_indexes(net): i_indiciesRow = [] j_indiciesColumn = [] count = 0 for ID in net: sup = list(set(net[ID])) for s in sup: i_indiciesRow.append(count + 1) j_indiciesColumn.append(s) count += 1 with open('i_indiciesRow.txt', 'w') as file_i_indiciesRow: file_i_indiciesRow.write(cjson.encode(i_indiciesRow)) with open('j_indiciesColumn.txt', 'w') as file_j_indiciesColumn: file_j_indiciesColumn.write(cjson.encode(j_indiciesColumn)) def QMatrixD…
answer count: 0
linked to: http://stackoverflow.com/q/311775
has comment: http://stackoverflow.com/comment/91581096
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91581779
has comment: http://stackoverflow.com/comment/91582837
has comment: http://stackoverflow.com/comment/91610788
tagged with: quadratic-programming
has comment: http://stackoverflow.com/comment/91573888
has comment: http://stackoverflow.com/comment/91584320
has comment: http://stackoverflow.com/comment/91573771
type: Question
tagged with: python

http://stackoverflow.com/q/52275262
has comment: http://stackoverflow.com/comment/91507717
has comment: http://stackoverflow.com/comment/91498212
tagged with: cumulative-sum
downvote count: 1
tagged with: excel
score: 1
type: Question
has answer: http://stackoverflow.com/a/52275970
has answer: http://stackoverflow.com/a/63723709
has title: Pandas: undo accumulation (e.g. cumulative sum)
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/52275996
has body: I have received data with accumulated numbers. Is there a smart way to deaccumulate data, so I have it month by month and not stacked on top of each other? (Check the example xlsx here: https://docs.google.com/spreadsheets/d/1yELrJdZmi3CFJccYSi5U6GGDW-Awp5spHDnsDyshBe0/edit?usp=sharing.) Example input: Date SalesRep itemA itemB 01-01-2018 Jakob 5 10 01-01-2018 Adomas 10 20 01-01-2018 Thomas 15 30 01-02-2018 Jakob 50 30 01-02-2018 Adomas 100 40 01-02-2018 Thomas 150 65 Desired output: Date SalesRep itemA itemB 01-01-2018 Jakob 5 10 01-01-2018 Adomas 10 20 01-01-2018 Thomas 15 30 01-02-2018 Jakob 45 20 01-02-2018 Adomas 90 20 01-02-2018 Thomas 135 35 Best Regards, Przemyslaw P.S. UPDATE What about the case if the data is not incrementing every month? Example input: Date SalesRep itemA itemB 01-01-2018 Jakob 5 10 01-01-2018 Adomas 10 20 01-01-2018 Thomas 15 30 **01-02-2018 Jakob 50 30** 01-02-2018 Adomas 100 40 01-02-2018 Thomas 150 65 **01-03-2018 Jakob 50 30** 01-03-2018 Adomas 102 60 01-03-2018 Thomas 155 75 What about the case of Jakob who is not incrementing every month then your solutions are not working? Can I somehow specify the parameters to check that and subtract only if there is a change?
has answer: http://stackoverflow.com/a/52276185
answer count: 4
favorite count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/52290068
accepted answer: http://stackoverflow.com/a/52290091
type: Question
answer count: 2
score: 5
upvote count: 5
downvote count: 0
has title: Install jupyter notebook offline without pip
has comment: http://stackoverflow.com/comment/103526563
has answer: http://stackoverflow.com/a/63901485
tagged with: jupyter
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/52290091
favorite count: 0
possible better answer: http://stackoverflow.com/a/63901485
has body: I need to install jupyter notebook in my computer without internet network. I cannot install with anaconda with security problem. I can use pip only with .whl files because I don't have any internet access with this computer. I've downloaded notebook-master.zip file from https://github.com/jupyter/notebook But I still cannot install jupyter notebook with this zip file. Please help me install jupyter notebook. Thx
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/52371452
has comment: http://stackoverflow.com/comment/91688030
downvote count: 0
has comment: http://stackoverflow.com/comment/91689434
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91689587
has body: Are you sure you are actually running the good code? IndetationError: unexpected inden (transforms.py, line 1) ^^This tells you that you have an indentation error in transforms.py at line 1 ^^ from .transforms import Bbox, IdentityTransform, TransformedBbox, \ First of all you should remove the '.' before transforms and '\' at the end, like so: from transforms import Bbox, IdentityTransform, TransformedBbox And you says that artist.py is opening up, and that is why I'm asking if you are running the good code. It seems like you are running artist.py ? ;D
accepted answer of: http://stackoverflow.com/q/52371349
has comment: http://stackoverflow.com/comment/91689139
has comment: http://stackoverflow.com/comment/91687922
has comment: http://stackoverflow.com/comment/91687548
answers question: http://stackoverflow.com/q/52371349
type: AcceptedAnswer

http://stackoverflow.com/a/52406693
has body: You can flatten columns to DataFrame: from itertools import chain d = df['Data'].str.split(',') isdef = df['IsDef'].str.split(',') df = pd.DataFrame({ 'Data' : list(chain.from_iterable(d)), 'IsDef' : list(chain.from_iterable(isdef)), 'Id' : df['Id'].repeat(d.str.len()) }) Then use cumcount for counter per groups and filter out all rows without first 2 by boolean indexing: N = 2 df['g'] = df.groupby(['Id','IsDef']).cumcount() df = df[df['g'] &lt; N] Then reshape by set_index and unstack and add missing categories by reindex. Last is flattened MultiIndex in columns by f-strings: mux = pd.MultiIndex.from_product([['Y','N'], np.arange(N)]) df = df.set_index(['Id','IsDef', 'g'])['Data'].unstack([1,2]).reindex(columns=mux) df.columns = [f'Data{i}_{j+1}' for i, j in df.columns] print (df) DataY_1 DataY_2 DataN_1 DataN_2 Id 1 1a NaN NaN NaN 2 2d NaN 2a 2b 3 3b NaN 3a NaN
answers question: http://stackoverflow.com/q/52406340
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52406340
has comment: http://stackoverflow.com/comment/91760437

http://stackoverflow.com/comment/91636100
has text: @JonClements If you look here, code reveiw,and books the frequency option 3 is higher and would be beneficial to be more fluid with that to help keep the learning process going, but I respect your experience I'm only a month into this and just reading the points you made I agree `enumerate` is a better option and am gong to start incorporating its usage, but again I'm on here and books all day and you see `(range(len(lst))` in almost everything, so just to be on the same page while learning would help alleviate getting hung up
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52344942
score: 0

http://stackoverflow.com/a/52380953
accepted answer of: http://stackoverflow.com/q/52380847
has body: With f.readline(), your code only reads the first line that the API returns, which happens to be a blank line, so the JSON encoder complains about no data. Change f.readline().decode('utf-8') to f.read().decode('utf-8'), and you should get past this error.
upvote count: 3
answers question: http://stackoverflow.com/q/52380847
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/52333817
downvote count: 3
answers question: http://stackoverflow.com/q/52333696
score: 9
accepted answer of: http://stackoverflow.com/q/52333696
upvote count: 12
type: AcceptedAnswer
has body: Simple and straightforward. my_df.rename(columns = { '0': 'Betas', '1': 'P-values' }, inplace=True) Even nicer as borrowed from Edchum my_df.columns = ['Betas', 'P-values']
type: Answer

pykafka
tag name: pykafka
tags question: http://stackoverflow.com/q/52399764
type: Tag

http://stackoverflow.com/a/52418783
has comment: http://stackoverflow.com/comment/91781917
answers question: http://stackoverflow.com/q/52418782
score: 0
has body: tokens.annotate(phrases_with_freq_greater_than_100=Count(Q(phrases__freq__gte=100))).values('name','phrases_with_freq_greater_than_100')
type: Answer

http://stackoverflow.com/comment/120165912
type: AnswerComment
comment on: http://stackoverflow.com/a/52490127
type: Comment
has text: There's a typo, It should be : "Now, D can no longer differentiate between samples that are sampled from the real data distribution and those which are sampled from the generator." (and not G)
score: 1

http://stackoverflow.com/comment/91783946
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52420369
has text: @user10389994 - contains not working in numpy, because not implemented. `.values` convert pandas Series to numpy array.
type: AnswerComment

http://stackoverflow.com/q/52277797
linked to: http://stackoverflow.com/q/13875507
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91505517
has comment: http://stackoverflow.com/comment/91530937
answer count: 2
downvote count: 0
has title: Is there a non-math version of matplotlib.ticker.LogFormatterSciNotation?
favorite count: 0
tagged with: latex
has answer: http://stackoverflow.com/a/52340666
upvote count: 8
tagged with: python
possible better answer: http://stackoverflow.com/a/52340689
score: 8
has answer: http://stackoverflow.com/a/52340689
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91525161
has body: I am trying to plot a graph with a logarithmic y-axis using pgf_with_latex, i.e. all text formatting is done by pdflatex. In my matplotlib rc Parameters I define a font to be used. Here comes my problem: The standard matplotlib.ticker.LogFormatterSciNotation formatter used math text and therefore a math font, which does not fit the rest of the fonts (sans-serif). How can I format the y-axis labels using a formatter from matplotlib.ticker so that I get the labels formatted as powers of 10 with superscripted powers? To be more specific: How do I get these yticklabels formatted the same way but with the font from the xticklabels? I already tried using different formatters provided by matplotlib.ticker, but none of them has the exponents written the way I want. Here is an example of what I mean with a MWE below. import matplotlib as mpl mpl.use('pgf') pgf_with_latex = { "pgf.texsystem": "pdflatex", "font.family": "sans-serif", "text.usetex": False, "pgf.preamble": [ r"\usepackage[utf8x]{inputenc}", r"\usepackage{tgheros}", # TeX Gyre Heros sans serif r"\usepackage[T1]{fontenc}" ] } mpl.rcParams.update(pgf_with_latex) import matplotlib.pyplot as plt fig = plt.figure(figsize=[3, 2]) ax = fig.add_subplot(111) ax.set_yscale("log") ax.minorticks_off() ax.set_xlabel("sans-serif font label") ax.set_ylabel("math font label") plt.gca().set_ylim([1, 10000]) plt.gcf().tight_layout() plt.savefig('{}.pdf'.format("test")) Caution: A TeX distribution has to be installed on your system to run this. I used MikTex 2.9. Also Python 3.6.2 and matplotlib 2.1.2.
tagged with: formatting
has comment: http://stackoverflow.com/comment/91563238
has comment: http://stackoverflow.com/comment/91570393
tagged with: plot
accepted answer: http://stackoverflow.com/a/52340666
type: Question

http://stackoverflow.com/comment/91622555
score: 0
has text: No worries. Instead, Thank you for your time to try to help me solve my question :)
comment on: http://stackoverflow.com/a/52337191
type: Comment
type: AnswerComment

sensors
type: Tag
tag name: sensors
tags question: http://stackoverflow.com/q/52421371

http://stackoverflow.com/q/52340372
tagged with: tensorflow
type: Question
downvote count: 0
tagged with: keras
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Fit keras model without y values
score: 2
answer count: 0
upvote count: 2
has body: I'm building a model using Keras to predict a 2 week series of atmospheric pressure values. Below is the model structure I'm using: self.model = Sequential() self.model.add(CuDNNLSTM(256, return_sequences=False, input_shape=(None, 2))) self.model.add(RepeatVector(336)) # 336 corresponds to 2 weeks of hourly values (24 x 14) self.model.add(CuDNNLSTM(128, return_sequences=True)) self.model.add(TimeDistributed(Dense(2))) (NOTE: The CuDNNLSTM layer does the same as the LSTM layer in Keras, but it runs much faster on Nvidia GPUs) For training the model, x has the form [n_samples, n_time_steps, n_features], where n_samples is the number of training series (there is one for each weather station), n_time_steps is the number of hourly data points per series and n_features is the number of features per time step (in this case, the first feature is the atmospheric pressure, and the second feature is either 0 or 1 depending on the weather condition). All of the training data is normalised between -1 and 1. y has the same structure as x, but it contains hourly data for the 2 weeks following the 2 weeks of hourly data in x. The model trains and achieves a validation loss of 0.28115. When I make predictions using the model on unseen data, the predictions follow the correct pattern of rising and falling throughout the day, however, they do not reach the correct peaks and lows, since each series is slightly different. To combat this, I would normally fit the general model once on the specific series before predicting to adjust the weights a bit to that specific series. The problem is, I don't have enough data to generate x and y to feed into model.fit(), as y requires 336 time steps. Is there a way to fit a model without specifying y? I built a model that makes one hourly prediction at a time in a loop instead of all at once, which gets around the issue. However, I would like to be able to predict the whole 2 week series at once. Is there a better way to go about this? Also, is it p…
tagged with: machine-learning

http://stackoverflow.com/comment/91790233
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52421855
has text: @DhneshDhingra - No it's not
score: 0

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/52427024
tags question: http://stackoverflow.com/q/52413585
tags question: http://stackoverflow.com/q/52353954
tags question: http://stackoverflow.com/q/52346652
tags question: http://stackoverflow.com/q/52422265
type: Tag

http://stackoverflow.com/q/52402622
has answer: http://stackoverflow.com/a/52419360
accepted answer: http://stackoverflow.com/a/52404449
has answer: http://stackoverflow.com/a/52403940
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/91750709
possible better answer: http://stackoverflow.com/a/52403940
has title: requests payload encoding
has comment: http://stackoverflow.com/comment/91748978
has comment: http://stackoverflow.com/comment/91751269
has comment: http://stackoverflow.com/comment/91752272
has body: I use requests to pretend firefox and from the fiddler, I saw header is same, but the SystaxView not same payload = {'searchType':'U'} s.post(url,data=payload) but I got error 500, From the syntax view, I saw in requests it will change to searchType=U But Real browser will output searchType='U'. I tried payload = {'searchType':'\'U\''} it will becomesearchType=%27U%27 in Syntax view. any idea? I only find 1 difference, so I suspect it will trigger 500 error. import requests s=requests.Session() s.headers.update({'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0'}) s.get('http://gls.fehd.gov.hk/fehd_lgs/jsp/search/searchMainPage.jsp?lang=zh_TW') s.headers.update({'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'X-Requested-With': 'XMLHttpRequest'}) s.headers.update({'Referer': 'http://gls.fehd.gov.hk/fehd_lgs/jsp/search/searchMainPage.jsp?lang=zh_TW', 'HOST':'gls.fehd.gov.hk'}) s.headers.update({'Accept': 'application/xml, text/xml, */*; q=0.01'}) payload={'searchType':'U','deceased_surName':'','deceased_firstName':'','deceased_age':'','deceased_gender':'M','deceased_nationality':'','deathYear':'','deathMonth':'default','deathDay':'default','burialYear':'','burialMonth':'default','burialDay':'default','sectionNo':'','graveNo':''} url='http://gls.fehd.gov.hk/FEHD_LGS/util/getSearchResult.jsp' s.post(url,data=payload)
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/91751962
has answer: http://stackoverflow.com/a/52404449
has comment: http://stackoverflow.com/comment/91748958
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/135508391
type: Comment
type: QuestionComment
has text: Try installing mamba to your conda base, and use mamba instead of conda. It solves many "conda frozen" issues. https://anaconda.org/conda-forge/mamba
score: 0
comment on: http://stackoverflow.com/q/52284072

http://stackoverflow.com/a/52305649
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91559844
has body: You can use os.walk to traverse the subfolders, and if test.txt is not found, clear the directory list so os.walk won't traverse its subfolders any further: import os folderslist = [] for root, dirs, files in os.walk('c:/test'): if 'test.txt' in files: folderslist.append(root) else: dirs.clear()
type: Answer
accepted answer of: http://stackoverflow.com/q/52305557
has comment: http://stackoverflow.com/comment/91560377
answers question: http://stackoverflow.com/q/52305557
has comment: http://stackoverflow.com/comment/91559856
has comment: http://stackoverflow.com/comment/91559925
score: 0

http://stackoverflow.com/comment/91626710
type: QuestionComment
comment on: http://stackoverflow.com/q/52339528
has text: Possible duplicate of [Converting Matlab's datenum format to Python](https://stackoverflow.com/questions/13965740/converting-matlabs-datenum-format-to-python)
score: 0
type: Comment

http://stackoverflow.com/a/52435517
type: Answer
has body: Pkgs directory is somewhere to place the package downloaded and unzipped. So it is a full and complete scripts/project documents. Actually, the second one should have the file you want if you installed the package properly. I think maybe there are some problems during installing or you just install it into some sub-environment of miniconda instead of the global environment of miniconda. So there will be some left packages which are downloaded and unzipped but not installed. You could also copy and paste the file from the first location to the second one by yourself. If you could import properly, it should be ok.
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/91814596
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52412901
answers question: http://stackoverflow.com/q/52412901

http://stackoverflow.com/q/52346617
linked to: http://stackoverflow.com/q/22391433
has comment: http://stackoverflow.com/comment/91638941
has comment: http://stackoverflow.com/comment/91638855
has title: Count_values with where condition to count values of one column with respect to other
has comment: http://stackoverflow.com/comment/91639002
type: Question
has comment: http://stackoverflow.com/comment/91638809
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91638972
has answer: http://stackoverflow.com/a/52346904
accepted answer: http://stackoverflow.com/a/52346904
has body: I am doing some EDA on my data which is pandas data-frame and I am stuck at this point. I don't know how to count values of infants where party== republican or democrat. I want to apply value_counts on all columns where arty== republican or democrat. party infants water budget physician salvador religious satellite republican n y n y y y n republican n y n y y y n democrat ? y y ? y y n democrat n y y n ? y n democrat y y y n y y n Answer should be like party infants democrat. y=1, n=1, ?=1 republican y=0, n=2, ?=0 like that for all columns. I have tried something like that. infants_count = data["infants"].value_counts().where(data['party']=="democrat") infants_count.loc['y']
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91638834
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91638908
downvote count: 0
score: 1

http://stackoverflow.com/comment/91751849
type: AnswerComment
comment on: http://stackoverflow.com/a/52403611
has text: look: i just removed STATICFILES_DIRS from settings.py and changed STATIC_URL to '/static/appname/' and now styles are applied to both appname and appname2. Same happens if i make STATIC_URL='/static/appname2/'. why is that happening?
type: Comment
score: 0

http://stackoverflow.com/a/52402343
answers question: http://stackoverflow.com/q/52401976
type: Answer
has body: It's seems the answer is that : sudo systemctl set-environment SECRET_KEY=blahblahblah
score: 0

http://stackoverflow.com/comment/91798979
has text: i am sorry , i skiped one line postData = json.dumps(postData) after this i have to do that
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52426496
type: AnswerComment

http://stackoverflow.com/q/52378427
score: -2
answer count: 1
tagged with: cuda
tagged with: anaconda
downvote count: 2
has title: I have cuda installed on win10, but anaconda let me to reinstall it in the environment
accepted answer: http://stackoverflow.com/a/52382308
upvote count: 0
has body: enter image description here Is there some path I didn't add?
has comment: http://stackoverflow.com/comment/91701560
linked to: http://stackoverflow.com/q/52298146
type: AnsweredQuestion
favorite count: 0
has answer: http://stackoverflow.com/a/52382308
type: Question
has comment: http://stackoverflow.com/comment/91701320
tagged with: python

http://stackoverflow.com/comment/91727435
has text: What is the result structure that you require? Can you please add that to your question?
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52391118

http://stackoverflow.com/q/52379649
tagged with: django
has answer: http://stackoverflow.com/a/52379777
tagged with: multiprocessing
accepted answer: http://stackoverflow.com/a/52379777
type: Question
tagged with: coverage.py
has title: Python coverage does not see config file
score: 5
answer count: 1
favorite count: 0
has body: I am running python coverage for Django unit tests in parallel mode: coverage run --source='.' --concurrency=multiprocessing manage.py test --parallel It is complaining: Options affecting multiprocessing must be specified in a configuration file. But I have .coveragerc file in the same directory from which I start coverage with the following content: [run] branch = True concurrency = multiprocessing Tried to specify --rcfile option for coverage run, that did not help. What am I missing? Thank you!
upvote count: 5
tagged with: python
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/91769958
has text: It looks like dict
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52413106
score: 0

http://stackoverflow.com/comment/91687755
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52364695
has text: I notice that the "r" is missing from the word "Drive[r]" in the error message and the rest of the message is an inaccurate paraphrase of what the Access Database engine actually reports, suggesting transcription errors when composing your question. Does the error message really say "... Driver] is not a valid name ...", or does it say "... Driver] '(something)' is not a valid name ..." ?
type: Comment

http://stackoverflow.com/comment/91799220
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52427453
has text: can you explain to me what the len(board[0]) is doing? is that showing that there are 4 columns?

nan
tags question: http://stackoverflow.com/q/52429696
tags question: http://stackoverflow.com/q/52369647
tags question: http://stackoverflow.com/q/52398578
tags question: http://stackoverflow.com/q/52349507
tag name: nan
type: Tag
tags question: http://stackoverflow.com/q/52306858

http://stackoverflow.com/q/52324921
has comment: http://stackoverflow.com/comment/91596787
has comment: http://stackoverflow.com/comment/91597268
has body: I'm trying to develop a user management interface for my project using the following: Python 2.7 falcon 1.4.1 falcon-cors 1.1.7 gunicorn 19.9.0 I'm testing the login page in Google Chrome initiated by run command in Pycharm Professional. Operating System: Ubuntu 18.04 LTS import falcon from falcon_cors import CORS cors = CORS(allow_all_origins=True,allow_all_headers=True,allow_all_methods=True) class User: def __init__(self): self.name = 'Users API' def on_post(self, req, resp): try: data = urlparse.parse_qs(req.stream.read()) if "loginEmail" in data.keys() and "loginPassword" in data.keys(): email = data['loginEmail'][0] password = data['loginPassword'][0] result = self.authenticate(email, password) if result["status"]=="Success": resp.set_cookie('session', result["session"],path="/",domain="192.168.32.17:5000",secure=False) else: raise Exception, "Email or Password not provided" if len(result) <= 0: raise Exception, 'Empty Response' resp.body = json.dumps(result) except Exception as e: resp.body = json.dumps({'status': 'Error', 'message': e.message, 'details': str(e)}) def on_get(self, req, resp): try: data = req.params cookies = req.cookies if "session" in cookies.keys(): session = cookies['session'] result=self.get(session,data) if len(result) <= 0: raise Exception, 'Empty Response' else: raise Exception, "Session Terminated" resp.body = json.dumps(result) except Exception as e: resp.body = json.dumps({'status': 'Error','message': e.message,'details': str(e)}) api = falcon.API(middleware=[cors.middleware]) api.add_route('/user', User()) The basic webpage is as given below: My Project Sign in On login request I'm getting required response as given below: {"status": "Success", "message": "Session has been created successfully", "session": "F26F75C27942DE27"} But on refresh(), I'm getting following response: {"status": "Error", "message": "Session Terminated"} I also tried checking for cookie using chechCookie() method above and it returns false as well. I also tri…
answer count: 2
downvote count: 0
favorite count: 0
tagged with: rest
has comment: http://stackoverflow.com/comment/91599756
tagged with: python
has comment: http://stackoverflow.com/comment/91597296
has comment: http://stackoverflow.com/comment/91597178
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52507659
upvote count: 7
has title: Unable to set cookies using Falcon API and Python
type: Question
has comment: http://stackoverflow.com/comment/91783806
has answer: http://stackoverflow.com/a/62062067
has comment: http://stackoverflow.com/comment/91600165
has comment: http://stackoverflow.com/comment/91597717
has comment: http://stackoverflow.com/comment/91596927
tagged with: wsgi
score: 7
has comment: http://stackoverflow.com/comment/91596877
has comment: http://stackoverflow.com/comment/91771167

http://stackoverflow.com/comment/91782661
has text: @Aran-Fey I'm not sure I understand your comment. If the unmodified `run_func` is called, `locals()` returns empty dict. But when you call the modified function, it's non-empty.
comment on: http://stackoverflow.com/q/52419411
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91581258
score: 0
comment on: http://stackoverflow.com/q/52316774
type: QuestionComment
has text: Still can't understand your ask!!
type: Comment

http://stackoverflow.com/q/52388746
favorite count: 0
has title: How can I Optimize a search in pandas dataframe
has comment: http://stackoverflow.com/comment/91722761
has comment: http://stackoverflow.com/comment/91722777
type: AnsweredQuestion
score: 2
downvote count: 0
linked to: http://stackoverflow.com/q/26640129
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/52389119
accepted answer: http://stackoverflow.com/a/52389119
has body: I need to search the word 'mas' in Dataframe, the column with frase is Corpo, and the text in this column is splitted in list, for example: I like birds ---> split [I,like,birds]. So, I need search 'mas' in a portuguese frase and catch just the words after 'mas'. The code is taking to long to execute this function. df.Corpo.update(df.Corpo.str.split()) #tokeniza frase df.Corpo = df.Corpo.fillna('') for i in df.index: for j in range(len(df.Corpo[i])): lista_aux = [] if df.Corpo[i][j] == 'mas' or df.Corpo[i][j] == 'porem' or df.Corpo[i][j] == 'contudo' or df.Corpo[i][j] == 'todavia': lista_aux = df.Corpo[i] df.Corpo[i] = lista_aux[j+1:] break if df.Corpo[i][j] == 'question': df.Corpo[i] = ['question'] break
tagged with: pandas
answer count: 1
tagged with: python

http://stackoverflow.com/q/52304699
score: 0
tagged with: pandas
answer count: 1
tagged with: python
tagged with: merge
type: AnsweredQuestion
has title: Pandas merging columns by reverse compliment string
type: Question
has answer: http://stackoverflow.com/a/52304831
accepted answer: http://stackoverflow.com/a/52304831
tagged with: data-manipulation
tagged with: dataframe
has body: So I am stuck on how to approach a data manipulation technique in pandas. I have an example dataframe below with a sum of 25 counts in each row. I would like to merge column names by the reverse compliment sequence. AA CC GG AT TT 4 7 0 9 5 3 8 5 5 2 8 6 2 8 1 The columns "AA" and "TT" are reverse compliments of each other as are "CC" and "GG" AA/TT CC/GG AT 9 7 9 5 13 5 9 8 8 How can I match the reverse compliment of a column name and merge it with the name of another column. Note: I already have a function to find the reverse compliment of a string

http://stackoverflow.com/q/52354313
tagged with: django-models
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/52354402
favorite count: 0
tagged with: python-3.x
has body: Here is my model : class Movie(models.Model): genre = models.ManyToManyField(Genre) class Genre(models.Model): genre_eng = models.CharField(max_length=200) def __str__(self): return "{}".format(self.genre_eng) and here is my view method : def info(request, id): movie_info = Movie.objects.get(id=id) return render(request,'info.html', {'movie_info': movie_info}) I can already print the name of the movie like this in info.html file: genre : {{movie_info.title}} How Can I access the genre_eng in the info.html file? each movie may have multiple genres.
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52354402
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
tagged with: database
has title: How to access a table record by id of another table in many to many relationship in django?

http://stackoverflow.com/q/52295117
linked to: http://stackoverflow.com/q/52911232
score: 33
type: Question
has answer: http://stackoverflow.com/a/75831943
has answer: http://stackoverflow.com/a/53439294
has answer: http://stackoverflow.com/a/58751730
downvote count: 0
has answer: http://stackoverflow.com/a/54788001
has comment: http://stackoverflow.com/comment/92641097
has answer: http://stackoverflow.com/a/52315164
answer count: 10
tagged with: python
tagged with: matplotlib-basemap
upvote count: 33
favorite count: 0
linked to: http://stackoverflow.com/q/72428844
tagged with: python-3.x
tagged with: pycharm
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53373943
has answer: http://stackoverflow.com/a/56166983
has body: I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with from mpl_toolkits.basemap import Basemap` And the Traceback as followed: Traceback (most recent call last): File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-4-0a24a3a77efd&gt;", line 7, in &lt;module&gt; from mpl_toolkits.basemap import Basemap File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 20, in do_import module = self._system_import(name, *args, **kwargs) File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py", line 146, in &lt;module&gt; pyproj_datadir = os.environ['PROJ_LIB'] File "/Users/yupeipei/anaconda3/lib/python3.6/os.py", line 669, in __ getitem__ raise KeyError(key) from None KeyError: 'PROJ_LIB' I'm confused with this error on PyCharm, because the same script is running correctly on Jupyter or Spyder! The environment in PyCharm is ../anaconda3/lib/python3.6 where is same from anaconda. Has anyone met this error before? Could anyone can help me to solve this error?
has title: Basemap import error in PyCharm — KeyError: 'PROJ_LIB'
has comment: http://stackoverflow.com/comment/91547220
has answer: http://stackoverflow.com/a/53751941
has answer: http://stackoverflow.com/a/63091316
has answer: http://stackoverflow.com/a/53439205

http://stackoverflow.com/comment/91645057
comment on: http://stackoverflow.com/q/52347470
type: QuestionComment
has text: @DanielRoseman, Thanks. My concern is the same as my response to PM 2Ring. I will think a little bit more if I can do any better; if not, I'll either implement `__init__` from scratch or go with the `__new__` and suggest some code changes to the library via PR.
score: 0
type: Comment

http://stackoverflow.com/comment/91618411
comment on: http://stackoverflow.com/a/52335583
score: 0
type: AnswerComment
has text: My mistake, as pointed out by Chillie I was incorrectly using the $ symbol to finish the pattern. Thanks for the help anyway.
type: Comment

http://stackoverflow.com/q/52417510
type: Question
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91878917
has title: delete text with 'strikethrough' font in docx document using python
tagged with: http://stackoverflow.com/tag/xml
tagged with: http://stackoverflow.com/tag/docx
answer count: 0
tagged with: fonts
type: UnansweredQuestion
tagged with: python
tagged with: text
downvote count: 0
has body: I need to delete text with 'strikethrough' font (L̶i̶k̶e̶ ̶t̶h̶i̶s̶.) in .docx documents. I have tried to use python-docx package. However, some of the text are in textbox in the word document and python-docx cannot detect strikethrough font in textbox. Is there any other python package/method that can do this job? Thanks for the help!
score: 1

http://stackoverflow.com/comment/91716429
score: 0
comment on: http://stackoverflow.com/q/52381909
type: Comment
type: QuestionComment
has text: @fayaz Solved by method overriding

http://stackoverflow.com/q/52279094
has answer: http://stackoverflow.com/a/52279464
tagged with: python
tagged with: linear-regression
has comment: http://stackoverflow.com/comment/91506212
has comment: http://stackoverflow.com/comment/91507262
upvote count: 1
tagged with: machine-learning
downvote count: 1
accepted answer: http://stackoverflow.com/a/52279464
type: Question
has comment: http://stackoverflow.com/comment/91507622
type: AnsweredQuestion
has title: Converting an attribute having values in string form to vetor using python
score: 0
has body: I have to prepare data for training the model of linear regression. In data there is attribute 'Gender' having three values 'M','F' and 'I'. How can i convert these values to the respective (1,0,0),(0,1,0),(0,0,1) vector form?
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/91560045
comment on: http://stackoverflow.com/q/52300481
type: Comment
has text: You can always try to use pypy implementation to gain at least *some* increase in speed.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91624272
score: 0
type: AnswerComment
has text: My use involves csv files, so since the python `csv` library does not play nicely with bytes, I guess I should just stay with `s3.upload_file` for convenience.
type: Comment
comment on: http://stackoverflow.com/a/52337251

http://stackoverflow.com/comment/91563569
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52307531
type: Comment
has text: Here you go. Imagination coding is hard. Had to run it myself.

http://stackoverflow.com/q/52353914
type: Question
has comment: http://stackoverflow.com/comment/91671173
tagged with: ta-lib
score: 0
tagged with: python
answer count: 0
has body: this has been bugging me since the morning. I searched for a solution, but other people mostly had similar problems because of different initial EMAs. Here, I am using an array of 100 numbers for testing. I calculated emas by hand and with talib also (It is using SMA for the inital EMA). That part is correct. But, when I do ema12-ema26 by hand and calculate it with MACD function, the function is completely wrong. I tried using SMAs, but the result is still wrong... I'm looking at the MACD Line output ofcourse. For the EMAs I'm calling the EMA functions (timeperiods 12 and 26)), and for MACD I'm using 26 12 9. Has anyone had this problem before? EDIT: I tried it on a 1000 number example and it seems that the MACD function value is converging towards the calculated value. I guess talib.MACD is not using the talib.EMA for the calculation of EMAs and that's why I have different results...
has title: ta-lib MACD function calculating wrong on closed 100 numbers example
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/34427530
has comment: http://stackoverflow.com/comment/91654921

http://stackoverflow.com/q/52332373
has comment: http://stackoverflow.com/comment/91611460
type: Question
type: AnsweredQuestion
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52332482
tagged with: bigdata
upvote count: 1
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/52332482
has body: I am processing several data tables which have more than 20 Million rows with 30+ columns. Currently I am using python pyspark to count Null value and calculate missing rate. But it takes 40 minutes for one column check. If there is any other better way to process it to make it faster, please let me know. Appreciate it. My current code is: variables = ['A', 'B', ....] for variable in variables: column = pandas.read_sql_query('select %s from dbo.ORDERS' % (variable), con=cnxn) column_missing = column.filter(column[variable].isnull()).count() total = len(column) missing = len(column_missing) Edited Code: import pyodbc import pandas import numpy import datetime import time from pyspark.sql.functions import lit, col order_pk = pandas.read_sql_query('select %s from dbo.ORDERS' % ('ORDER_PK'), con=cnxn) summary = order_pk.describe().filter(col('ORDER_PK') == "count") summary.select(*((lit(rows)-col(c)).alias(c) for c in order_pk.columns)).show() --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-12-30285cf9f59e&gt; in &lt;module&gt;() ----&gt; 1 summary = order_pk.describe().filter(col('ORDER_PK') == "count") 2 summary.select(*((lit(rows)-col(c)).alias(c) for c in order_pk.columns)).show() c:\users\pcui\appdata\local\programs\python\python37\lib\site-packages\pyspark\sql\functions.py in _(col) 40 def _(col): 41 sc = SparkContext._active_spark_context ---&gt; 42 jc = getattr(sc._jvm.functions, name)(col._jc if isinstance(col, Column) else col) 43 return Column(jc) 44 _.__name__ = name AttributeError: 'NoneType' object has no attribute '_jvm'
downvote count: 0
tagged with: pyspark
has title: What is the fastest way to get count of missing value for Big Data in python or spark?

http://stackoverflow.com/comment/91685059
has text: I want to retrieve the documents attached to each topic. If I do this: print 'Topic 0' docs = np.argsort (document_topics [:, 0]) [:: - 1] it works but if I try to retrieve all topics and documents, it doesn't work...
type: Comment
comment on: http://stackoverflow.com/a/52365919
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91599756
type: QuestionComment
comment on: http://stackoverflow.com/q/52324921
has text: I used chrome browser debugging and I checked using javascript. Cookie wasn't there. Using the Postman cookie is created. Looks like chrome is blocking cookies or there is some problem with ajax request.
score: 0
type: Comment

http://stackoverflow.com/a/68181881
type: Answer
score: 3
downvote count: 0
upvote count: 3
answers question: http://stackoverflow.com/q/52384429
has body: Responding on a old thread. appending add_scattergo helped me solve exactly same issue. fig.add_scattergeo( locations=data_state['state_code'], ###codes for states, locationmode='USA-states', text=data_state['state_code'],` mode='text')

http://stackoverflow.com/a/52343808
score: 2
answers question: http://stackoverflow.com/q/52343735
downvote count: 0
has body: find_all returns a list, so use indexes to get the desired elements result = data_soup.find_all(attrs={"class": "product"}) print(result[1], result[3])
upvote count: 2
has comment: http://stackoverflow.com/comment/91676398
type: Answer

http://stackoverflow.com/q/52304947
score: 0
tagged with: pandas
tagged with: python
has body: I have a list of strings that contain spaces that I need to parse by the last or second to last space (dateTime). I have tried split() on the main string but the problem is that there are a lot of spaces included for description of data, so instead I deferred to using split(/n) . See below for sample list. ['Origin Time 2016/04/16 01:25:00', 'Lat. 32.753', 'Long. 130.762', 'Depth. (km) 12', 'Mag. 7.3', 'Station Code AIC001', 'Station Lat. 35.2976', 'Station Long. 136.7500', 'Station Height(m) 6', 'Record Time 2016/04/16 01:28:06', 'Sampling Freq(Hz) 100Hz', 'Duration Time(s) 120', 'Dir. N-S', 'Scale Factor 7845(gal)/8223790', 'Max. Acc. (gal) 2.327', 'Last Correction 2016/04/16 01:28:08' I'm not sure the the best angle is to split the first and last elements of this list, I would like to separate them so that I can create a pandas Dataframe from it.
has comment: http://stackoverflow.com/comment/91557549
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52305051
accepted answer: http://stackoverflow.com/a/52305051
has title: Parsing a list of string by the last occurring space python
type: Question
tagged with: split
answer count: 1

http://stackoverflow.com/comment/91553599
has text: Should I use numpy for array calculations? Some people mentioned this to me.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52302622
score: 0

http://stackoverflow.com/q/52274481
possible better answer: http://stackoverflow.com/a/52277798
has comment: http://stackoverflow.com/comment/91496609
tagged with: python
has title: Splitting DataFrames based on timestamp continuity in Pandas
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
upvote count: 2
tagged with: split
has comment: http://stackoverflow.com/comment/91496334
tagged with: dataframe
has body: I want to create a new DataFrame consisting of the rows corresponding to the value 1.0 or NaN in the last column, whereby I only take the Nans under a 1.0. However, I also want to consider the rows where the Result 0.0 as long as there are maximum two such timestamps (for instance, in the simple example below, I would take the rows where the Timestamp is 00-00-30 and 00-00-40). Timestamp Value Result 00-00-10 34567 1.0 00-00-20 45425 00-00-30 46773 0.0 00-00-40 64567 00-00-50 25665 1.0 00-01-00 25678 00-01-10 84358 00-01-20 76869 0.0 00-01-30 95830 00-01-40 87890 00-01-50 99537 00-02-00 85957 1.0 00-02-10 58840 I split it into two dataframes: df_1 = data[((data['Result'].isnull()) &amp; data['Result'].ffill() == 1) | data.Result == 1] and df_2 = data[((data['Result'].isnull()) &amp; data['Result'].ffill() == 0) | data.Result == 0] How do I split df_2 into blocks such that the Timestamp is continuous/not interrupted? (Then I can check whether each block is greater than the tolerated length, and if not, append it to df_1and sort it based on time.) I therefore want the output: Timestamp Value Result 00-00-10 34567 1.0 00-00-20 45425 00-00-30 46773 0.0 00-00-40 64567 00-00-50 25665 1.0 00-01-00 25678 00-01-10 84358 00-02-00 85957 1.0 00-02-10 58840
has answer: http://stackoverflow.com/a/52277798
has answer: http://stackoverflow.com/a/52277853
accepted answer: http://stackoverflow.com/a/52277853
answer count: 2
tagged with: pandas
favorite count: 0

http://stackoverflow.com/q/52365633
has comment: http://stackoverflow.com/comment/91675937
has comment: http://stackoverflow.com/comment/91676138
type: Question
has body: This is really fast: 1 in range(100000000000000) This is really slow: 1.5 in range(100000000000000) Why does the full range have to be generated to know that 1.5 isn't in range(X) when step has to be an integer?
score: 3
has comment: http://stackoverflow.com/comment/91681383
upvote count: 3
accepted answer: http://stackoverflow.com/a/52365949
has comment: http://stackoverflow.com/comment/91675627
answer count: 1
has comment: http://stackoverflow.com/comment/91678224
linked to: http://stackoverflow.com/q/13092267
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91675542
has comment: http://stackoverflow.com/comment/91675877
has answer: http://stackoverflow.com/a/52365949
tagged with: python
has title: Why does python have to generate the full range to test if float in range?
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/91763079
score: 0
type: Comment
type: QuestionComment
has text: @LaurentMazuel, updated. I'll post in their issues as well.
comment on: http://stackoverflow.com/q/52409379

http://stackoverflow.com/comment/91804069
comment on: http://stackoverflow.com/a/52428999
type: AnswerComment
score: 0
type: Comment
has text: Hey, you had suggested something to try can you please write it for me again.

http://stackoverflow.com/q/52296750
linked to: http://stackoverflow.com/q/13272453
has comment: http://stackoverflow.com/comment/91542127
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52297938
tagged with: python
has title: How to do efficient matrix multiplication between a dense numpy matrix and a sparse scipy vector?
upvote count: 1
tagged with: scipy
downvote count: 1
has comment: http://stackoverflow.com/comment/91541924
tagged with: matrix-multiplication
type: Question
has body: Multiplying a dense numpy matrix with a sparse scipy vector using @ is incredibly inefficient . It seems like it doesn't make use of the sparsity of the vector at all. Say we have A = np.eye(5000) x = np.eye(5000)[333] x = scipy.sparse.coo_matrix(x).T # make it a sparse vector Then multiplication using @ yields: %timeit A @ x 8 ms ± 78.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) Let's write an incredibly crappy sparse multiplication ourselves: def mult_dense_with_sparse(A, x): return (A[:,x.nonzero()[0]] @ x.toarray()[x.nonzero()[0]]).T[0] Lo and behold: %timeit mult_dense_with_sparse(A, x) 50.3 µs ± 45.3 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) It's much faster! Even though this implementation first creates a dense vector by adding all the zeros again, and then removes all the zeros again... So I'm wondering, if not @, how can I multiply a dense numpy matrix with a sparse scipy vector efficiently? Surely such a basic operation is part of scipy? Edit: provided solution in other question is not helpful as it is just as inefficient as @: %timeit scipy.sparse.csr_matrix.dot(A, x) 7.97 ms ± 113 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) Edit 2 in responaw Hameer Abbasi: Line # Hits Time Per Hit % Time Line Contents ============================================================== 101 @profile 102 def ratio(self, n): 103 80 51.0 0.6 0.0 s = n + 1 104 80 11401854.0 142523.2 16.1 self.sfpc = self.scolPCA(s) # sparse first principal component 106 80 351898.0 4398.7 0.5 wSums = (self.signals[:,self.sfpc.nonzero()[0]] @ self.sfpc.toarray()[self.sfpc.nonzero()[0]]).T[0] 108 80 56487433.0 706092.9 79.7 wSums = self.sfpc.T.dot(self.signals.T)[0] 110 80 2521189.0 31514.9 3.6 self.Flag, self.threshold, self.incline, self.deltaVar = self.actFunctOpt(list(wSums)) 111 80 160.0 2.0 0.0 return self.deltaVar / (2 + s) Here you can see that our 'hack' takes about 0.5% of the time of this function, while using dot takes 79.7% of the time in this…
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/91547247
answer count: 1
tagged with: sparse-matrix
favorite count: 0

http://stackoverflow.com/q/52367258
tagged with: dictionary
type: AnsweredQuestion
score: 1
type: Question
possible better answer: http://stackoverflow.com/a/52367328
answer count: 2
has body: I am trying to create default dictionary from my pandas DataFrame, but to_dict() method creates unwanted square brackets around values of the columns i want to write. The example code is as follows: # Create DF my_df = pd.DataFrame({'numbers': (1, 2, 3, 4, 5), 'letters': ('a', 'b', 'c', 'd', 'e')}) # Create dictionary from the DF my_dict = my_df.set_index('numbers').T.to_dict('list') # Create collections dictionary my_collections_dict = collections.defaultdict(int, my_dict) results in: defaultdict(int, {1: ['a'], 2: ['b'], 3: ['c'], 4: ['d'], 5: ['e']}) what i want is: defaultdict(int, {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}) how to obtain 'pure' column values?
tagged with: pandas
upvote count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52367337
accepted answer: http://stackoverflow.com/a/52367337
favorite count: 0
has title: to_dict() creates brackets around values
has comment: http://stackoverflow.com/comment/91678706
tagged with: python
has answer: http://stackoverflow.com/a/52367328

http://stackoverflow.com/q/52282223
has title: Extracting text around specific word from PDF
tagged with: python
has answer: http://stackoverflow.com/a/52283783
tagged with: pypdf
has body: I am basic level python user and I am trying to create a program that gives the text before and after (like 50 words before and 50 words after) a specific word that I use. So far I managed to create a program that gives which page of PDF is word mentioned. How can I write into CVS these additional 100 words? import PyPDF2 import re import os ... for pdfName in pdffiles: pdfFull = pdfFolder + pdfName pdfFileObj = open(pdfFull, mode='rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) number_of_pages = pdfReader.numPages pages_text = [] words_start_pos = {} words = {} csvFolder = newpath csvName = pdfName.replace('pdf', 'csv') csvFull = csvFolder + csvName with open(csvFull, 'w') as f: f.write('{0},{1},{2}\n'.format("Sheet Number", "Search Word", "File Name")) for word in searchwords: for page in range(number_of_pages): pages_text.append(pdfReader.getPage(page).extractText()) words_start_pos[page] = [dwg.start() for dwg in re.finditer(word, pages_text[page].lower())] words[page] = [pages_text[page][value:value + len(word)] for value in words_start_pos[page]] for page in words: for i in range(0, len(words[page])): if str(words[page][i]) != 'nan': f.write('{0},{1},{2}\n'.format(page + 1, words[page][i], pdfFull))
type: Question
score: 0
tagged with: http://stackoverflow.com/tag/pdf
answer count: 1
type: UnansweredQuestion

discord
tags question: http://stackoverflow.com/q/52287487
tags question: http://stackoverflow.com/q/52394172
tags question: http://stackoverflow.com/q/52356984
tags question: http://stackoverflow.com/q/52355758
tags question: http://stackoverflow.com/q/52349101
tags question: http://stackoverflow.com/q/52323656
type: Tag
tags question: http://stackoverflow.com/q/52396370
tags question: http://stackoverflow.com/q/52346022
tags question: http://stackoverflow.com/q/52360859
tags question: http://stackoverflow.com/q/52354841
tags question: http://stackoverflow.com/q/52348148
tags question: http://stackoverflow.com/q/52343245
tags question: http://stackoverflow.com/q/52358080
tags question: http://stackoverflow.com/q/52298850
tags question: http://stackoverflow.com/q/52356043
tags question: http://stackoverflow.com/q/52372170
tag name: discord
tags question: http://stackoverflow.com/q/52393542
tags question: http://stackoverflow.com/q/52414070
tags question: http://stackoverflow.com/q/52289010
tags question: http://stackoverflow.com/q/52415743

http://stackoverflow.com/comment/91566541
has text: Your answer was the solution. Thank you! I refactored it :) If anyone wants the solution I used, I can post it in here.
comment on: http://stackoverflow.com/a/52280204
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91903794
type: Comment
has text: And in order to add a user to the database I also need to `from test import session ` and then >>>`session.add(ed_user)` and >>>`session.commit()`
comment on: http://stackoverflow.com/a/52481099
score: 0
type: AnswerComment

http://stackoverflow.com/comment/127436390
has text: Indeed @ForceBru. While this is not clear in my post, the numpy solution still works with array.array elements. `np.savetxt('todel;txt',L)` and `M2,N2 = np.genfromtxt(file)` will yield the wanted result. For the classical way you would just change the indexing with [i][k] : `file2='test2.txt' form="%i %i %i \n" with open(file2,'w') as f: for i in range(len(data)): f.write(form % (data[i][0],data[i][1],data[i][2]))`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52335893

http://stackoverflow.com/q/52372187
score: 7
upvote count: 7
type: Question
has body: Is there a way to log waitress-serve output into a file? The current command I use is: waitress-serve --listen=localhost:8080 --threads=1 my_app_api:app The application we used was not written with waitress in mind earlier, so we choose to serve it with command line to avoid change (for now at least).
has title: Logging with command line waitress-serve
has comment: http://stackoverflow.com/comment/91724970
tagged with: wsgi
linked to: http://stackoverflow.com/q/4760215
has comment: http://stackoverflow.com/comment/91726805
has answer: http://stackoverflow.com/a/65251472
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91749239
has comment: http://stackoverflow.com/comment/91726088
favorite count: 0
tagged with: python-3.x
tagged with: waitress
tagged with: python
tagged with: logging
has comment: http://stackoverflow.com/comment/91726316
type: UnansweredQuestion

http://stackoverflow.com/a/52304272
has comment: http://stackoverflow.com/comment/91581107
type: Answer
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52304023
answers question: http://stackoverflow.com/q/52304023
score: 4
has comment: http://stackoverflow.com/comment/91580127
has comment: http://stackoverflow.com/comment/91584703
type: AcceptedAnswer
has body: Let's use stack + extract: df['D'] = df.stack().str.extract(r'(.* oil)').groupby(level=0).first()[0] df A B C D 0 dirty gas crude oil dirty water crude oil 1 dirty water fuel gas dirty gas NaN 2 dirty water fuel gas dirty oil dirty oil 3 fuel oil crude water crude gas fuel oil 4 dirty water fuel oil dirty water fuel oil 5 crude oil fuel water dirty oil crude oil 6 fuel water crude gas crude water NaN

http://stackoverflow.com/comment/91492062
score: 1
has text: I think the line `ax = fig.add_axes([0,0,1,1])` is the problem -- it uses all figure space for the plot and leaves none for the axes. Try `ax=fig.add_subplot(111)` instead.
comment on: http://stackoverflow.com/q/52272393
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91756745
has text: Just updated with my code
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52406323

http://stackoverflow.com/comment/114404780
comment on: http://stackoverflow.com/a/52431519
type: AnswerComment
type: Comment
has text: @Swapnil I am not aware of any other approach.
score: 0

http://stackoverflow.com/comment/91669446
has text: @FHTMitchell of all the syntax errors in this (while loop coming at the end of code with no conditions, no ':' anywhere besides after `def`, this is the one you choose :P
comment on: http://stackoverflow.com/q/52362419
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/91644184
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52349410
has text: @Kamikaze_goldfish what does `type(' '.join(street))` say?

http://stackoverflow.com/q/52332281
has body: In the event of an IndexError, is there a way to tell which object on a line is 'out of range'? Consider this code: a = [1,2,3] b = [1,2,3] x, y = get_values_from_somewhere() try: a[x] = b[y] except IndexError as e: .... In the event that x or y is too large and IndexError gets caught, I would like to know which of a or b is out of range (so I can perform different actions in the except block). Clearly I could compare x and y to len(a) and len(b) respectively, but I am curious if there is another way of doing it using IndexError.
has answer: http://stackoverflow.com/a/52332572
has answer: http://stackoverflow.com/a/52332941
has answer: http://stackoverflow.com/a/52332403
upvote count: 9
tagged with: index-error
answer count: 5
has answer: http://stackoverflow.com/a/52335119
has title: How can I find out which index is out of range?
has answer: http://stackoverflow.com/a/52332478
possible better answer: http://stackoverflow.com/a/52332572
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question
score: 9
tagged with: exception
accepted answer: http://stackoverflow.com/a/52335119
tagged with: python

http://stackoverflow.com/q/52384307
score: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/91713618
has answer: http://stackoverflow.com/a/52384340
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91713818
has comment: http://stackoverflow.com/comment/91712628
accepted answer: http://stackoverflow.com/a/52384340
upvote count: 1
type: Question
has title: Extract values from tuple inside an object instantiation
tagged with: pep8
downvote count: 0
has body: I have the following code that doesn't work: def call_row(body_part): row = self.__call__()[body_part].loc[str(row_index)].tolist() return row[0], row[1] vector_centre = Vector2D(x, y = call_row(body_part_centre)) I know I can solve the issue by changing it to something like this: def call_row(body_part): row = self.__call__()[body_part].loc[str(row_index)].tolist() return row[0], row[1] x, y = call_row(body_part_centre) vector_centre = Vector2D(x, y) Yes, Vector2D is a custom class defined by myself. I don't find this solution that elegant. Is this the most "zen of python" style as it gets or can we make this better? I want to follow PEP8. The most explicit version of my question would be: Is there a way to extract values from a tuple inside an object instantiation without sacrificing elegance?
answer count: 1

http://stackoverflow.com/comment/91561714
type: QuestionComment
has text: yeah but the index zero has the object which is en empty tuple so something is there
score: 0
comment on: http://stackoverflow.com/q/52307224
type: Comment

http://stackoverflow.com/comment/91754634
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52403381
score: 1
has text: [As per the documentation](https://seaborn.pydata.org/generated/seaborn.boxenplot.html#seaborn.boxenplot), the use of boxen plot has been extensively discussed in [the paper introducing the concept](https://vita.had.co.nz/papers/letter-value-plot.html)

http://stackoverflow.com/comment/91629282
has text: Hmm. I might have Windows-1252. I sourced the string from a log, so the double-backslash probably got escaped.. And I do know the user is entering strings from Windows.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52341175
score: 0

http://stackoverflow.com/comment/91745360
comment on: http://stackoverflow.com/q/52397069
has text: I don't believe so. Never did anything to explicitly start Anaconda. Just did a pip install of jupyter notebook and launched it. I have python3 installed on machine as well. Anything else I need to do?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52296719
has comment: http://stackoverflow.com/comment/91541348
type: Answer
score: 0
has body: problem fixed &amp; loop optimized - the problem you encountered was the extra brackets () around your input-function. the loop is now optimized because your whole buying cycle is now inside this while True: loop. it will be repeated again and again until the user inputs something different then "yes" at the other question. while True: menu=["apple","water","juice"] apple=50 water=80 juice=100 money=int(input("How much money in pennies do you have?")) if money&gt;=100: print("We have the following items you can buy: apple, water, juice") elif money&gt;=80 and money&lt;=100: print("We have the following items you can buy: apple, water") elif money&gt;=50 and money&lt;=80: print("We have the following item you can buy: apple") else: print("Sorry, you can't buy anything.") buy=input("What do you want to buy?") if buy=="apple": print("You have",money-50) elif buy=="water": print("You have",money-80) else: print("You have",money-100) other=input("Do you want to buy anything else?") if other=="yes": continue else: break
answers question: http://stackoverflow.com/q/52296600

http://stackoverflow.com/comment/91630503
has text: how does `-30.00` become `x =90.71` and `y = -43.01` is there some geometry/trig involved?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52341422

http://stackoverflow.com/q/52421443
tagged with: beagleboneblack
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/62000543
upvote count: 1
has body: I need to power OFF the Beaglebone black from a Python Code directly without using any gpio buttons or any hardware intervention. There is the command line shutdown -h now but this command won't work on a python code since it requires a sudo password .... Any idea how can i interract with beaglebone black system ( linux command line without sudo ) in order to power off the board please ? Thank you .
accepted answer: http://stackoverflow.com/a/52424873
type: Question
possible better answer: http://stackoverflow.com/a/62000543
tagged with: power-off
score: 1
answer count: 2
downvote count: 0
favorite count: 0
has title: Power OFF the Beaglebone Black without Button or hardware intervention
tagged with: linux
has answer: http://stackoverflow.com/a/52424873
tagged with: python

http://stackoverflow.com/q/52341055
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91630245
has answer: http://stackoverflow.com/a/52341070
accepted answer: http://stackoverflow.com/a/52341120
downvote count: 0
favorite count: 0
has title: Most Efficiently Iterating Large List of Dictionaries in Python
possible better answer: http://stackoverflow.com/a/52341070
tagged with: python
tagged with: dictionary
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91645071
score: 1
has comment: http://stackoverflow.com/comment/91629131
has answer: http://stackoverflow.com/a/52341120
upvote count: 1
has comment: http://stackoverflow.com/comment/91629067
type: Question
has body: I have seen some answers for similar questions but I am not sure that they were the best way to fix my problem. I have a very large table (100,000+ rows of 20+ columns) being handled as a list of dictionaries. I need to do a partial deduplication of this list using a comparison. I have simplified an example of what I am doing now below. table = [ { "serial": "111", "time": 1000, "name": jon }, { "serial": "222", "time": 0900, "name": sal }, { "serial": "333", "time": 1100, "name": tim }, { "serial": "444", "time": 1300, "name": ron }, { "serial": "111", "time": 1300, "name": pam } ] for row in table: for row2 in table: if row != row2: if row['serial'] == row2['serial']: if row['time'] &gt; row2['time']: action This method does work (obviously simplified and just wrote "action" for that part) but the question I have is whether there is a more efficient method to get to the "row" that I want without having to double iterate the entire table. I don't have a way to necessarily predict where in the list matching rows would be located, but they would be listed under the same "serial" in this case. I'm relatively new to Python and efficiency is the goal here. As of now with the amount of rows that are being iterated it is taking a long time to complete and I'm sure there is a more efficient way to do this, I'm just not sure where to start. Thanks for any help!
has comment: http://stackoverflow.com/comment/91629049
has answer: http://stackoverflow.com/a/52341117
has answer: http://stackoverflow.com/a/52349965
has comment: http://stackoverflow.com/comment/91629446

http://stackoverflow.com/comment/91530931
comment on: http://stackoverflow.com/q/52290821
type: QuestionComment
type: Comment
has text: are you getting the same error ??
score: 0

http://stackoverflow.com/q/52307149
has comment: http://stackoverflow.com/comment/91561494
has body: i am using nested serializers concept in python django.For get() method i used a serializer as below class MusicianSerializer(serializers.ModelSerializer): album_musician = AlbumSerializer(many=True) class Meta: model = Musician fields = ('id', 'first_name', 'last_name', 'instrument', 'album_musician') but how can i write a nested serializer concept for the post and update concept without overriding update and create.
has comment: http://stackoverflow.com/comment/91561474
type: Question
has answer: http://stackoverflow.com/a/52336903
downvote count: 0
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/91561446
has comment: http://stackoverflow.com/comment/91561581
answer count: 1
tagged with: python
has title: Nested serializer concept for post and update
favorite count: 0
upvote count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/28078092
has comment: http://stackoverflow.com/comment/91561429
score: 2

http://stackoverflow.com/q/52358600
has title: \r\n Are showing up as is, not creating new lines
has answer: http://stackoverflow.com/a/52358905
possible better answer: http://stackoverflow.com/a/52358905
type: Question
has answer: http://stackoverflow.com/a/52373798
accepted answer: http://stackoverflow.com/a/52373798
has comment: http://stackoverflow.com/comment/91661608
score: 0
answer count: 2
has body: When I input a command such as "dir" through my python program it prints out what it should except that instead of being neat and organised, its all a continuous line and spammed with either \r or \n . Does anyone know the solution for that? Client: import socket import subprocess def execute_sys_command(command): return subprocess.check_output((command).decode(), shell=True) connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connection.connect(("127.0.0.1", 4444)) while True: command = connection.recv(1024) command_result = execute_sys_command(command) connection.send(command_result) connection.close() Btw, I get the input from another program remotely. Thanks in advance. Here is the Server. import socket listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listener.bind(("127.0.0.1", 4444)) listener.listen(0) print("[+] Waiting for incoming connections") connection, address = listener.accept() print("[+] Connection received from " + str(address)) while True: command = input("&gt;&gt; ").encode() connection.send(command) result = connection.recv(1024) command = (command).decode("utf-8") print(result) At the end, its printing the result from the previous one.
has comment: http://stackoverflow.com/comment/91661658
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91661746
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/91631829
has text: Thanks SIM for suggestion.. I am new to python as well as stack over flow. try to learning and solving ..
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52342362
type: Comment

http://stackoverflow.com/comment/91800530
has text: @StephenRauch Well, I think i knew that, but I like explicitly wrapping them in parentheses just so I can see at a glance. To be honest, I've never tried it without.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52416719
type: Comment

http://stackoverflow.com/q/52426857
has body: I have a python script that output's configuration for my hadoop/spark cluster. I am using following command to output the configuration file. python generateHadoopConfig.py How do I pipe this output to a temp file in same directory, for my EMR cluster to fetch it for updating the configuration.
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91796940
answer count: 1
has comment: http://stackoverflow.com/comment/91796935
favorite count: 0
downvote count: 5
has answer: http://stackoverflow.com/a/52426909
accepted answer: http://stackoverflow.com/a/52426909
tagged with: python
has title: Generating configuration file using python
type: AnsweredQuestion
upvote count: 0
score: -5
type: Question

http://stackoverflow.com/comment/91755812
comment on: http://stackoverflow.com/q/52406045
score: 1
has text: i have a same problem like this.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52273542
accepted answer: http://stackoverflow.com/a/52273675
type: Question
has answer: http://stackoverflow.com/a/52273675
tagged with: python
score: 0
has body: I am using python and have a training set of data that i need to 'subtract the mean and scale by inverse standard deviation'. Subtracting the mean would just be subtracting the mean from each value in each column i assume, but i have no idea what i am meant to do when it says to 'scale by inverse standard deviation'. I have googled it but nothing has come up in relation to python or neural networks so i'm not sure how to continue. Thanks EDIT: Would this be correct? scaled_train = (train - train_mean) / train_std_deviation
tagged with: standard-deviation
answer count: 1
tagged with: neural-network
tagged with: training-data
has title: Scale training set by inverse standard deviation using python
type: AnsweredQuestion

http://stackoverflow.com/comment/91519267
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52285181
type: Comment
has text: Possible duplicate of [DataError: No numeric types using mean aggregate function but not sum?](https://stackoverflow.com/questions/50091321/dataerror-no-numeric-types-using-mean-aggregate-function-but-not-sum)

http://stackoverflow.com/comment/91653849
type: QuestionComment
comment on: http://stackoverflow.com/q/52345195
type: Comment
has text: @SebasSBM No, it doesn't show any error in command-line's output...
score: 0

http://stackoverflow.com/a/52307204
upvote count: 3
answers question: http://stackoverflow.com/q/52307127
score: 3
downvote count: 0
has body: 1) Print result not test 2) You cannot add a character and int directly. Use built in function ord instead class solution(): def to_lowercase(self, str1): new_str="" for i in range(0, len(str1)): if ord(str1[i]) &gt;= 65 and ord(str1[i]) &lt;= 90: new_str+=chr(ord(str1[i]) + 32) return new_str test = solution() str1 = "AKASH" result = test.to_lowercase(str1) print(result) #akash
type: Answer

http://stackoverflow.com/a/54058584
has comment: http://stackoverflow.com/comment/94980810
has comment: http://stackoverflow.com/comment/107171423
has body: Found myself here a few times and eventually found my own solution. See https://bugreports.qt.io/browse/PYSIDE-842 This issue seems to occur when your pyside2 was installed via pip but your Qt was installed by the system (Manjaro/Arch in my case). This is what I got when using the pip version of pyside2: &gt;&gt;&gt; from PySide2.QtWidgets import QStyleFactory &gt;&gt;&gt; print(QStyleFactory.keys()) [u'Windows', u'Fusion'] When using the pyside2 packaged by arch linux I get: &gt;&gt;&gt; from PySide2.QtWidgets import QStyleFactory &gt;&gt;&gt; print(QStyleFactory.keys()) ['Adwaita-Dark', 'Adwaita', 'Breeze', 'bb10dark', 'bb10bright', 'kvantum-dark', 'kvantum', 'cleanlooks', 'gtk2', 'cde', 'motif', 'plastique', 'qt5ct-style', 'Oxygen', 'Windows', 'Fusion'] Using the pyside2 package that came with my system instead (sudo pacman -S pyside2) solved this for me. My pyside2 app now uses the system Qt theme.
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/52426437
downvote count: 0

regex
tags question: http://stackoverflow.com/q/52323258
tags question: http://stackoverflow.com/q/52329718
tags question: http://stackoverflow.com/q/52319319
tags question: http://stackoverflow.com/q/52358284
tags question: http://stackoverflow.com/q/52273054
tags question: http://stackoverflow.com/q/52415829
tags question: http://stackoverflow.com/q/52415351
tags question: http://stackoverflow.com/q/52323301
tags question: http://stackoverflow.com/q/52304663
tags question: http://stackoverflow.com/q/52413407
tags question: http://stackoverflow.com/q/52284786
tags question: http://stackoverflow.com/q/52411660
tags question: http://stackoverflow.com/q/52302474
tags question: http://stackoverflow.com/q/52302060
tag name: regex
tags question: http://stackoverflow.com/q/52368514
tags question: http://stackoverflow.com/q/52297574
tags question: http://stackoverflow.com/q/52340594
tags question: http://stackoverflow.com/q/52289999
tags question: http://stackoverflow.com/q/52416031
tags question: http://stackoverflow.com/q/52428537
tags question: http://stackoverflow.com/q/52281533
tags question: http://stackoverflow.com/q/52353500
tags question: http://stackoverflow.com/q/52301215
tags question: http://stackoverflow.com/q/52396923
tags question: http://stackoverflow.com/q/52355260
tags question: http://stackoverflow.com/q/52406347
tags question: http://stackoverflow.com/q/52313383
tags question: http://stackoverflow.com/q/52398043
tags question: http://stackoverflow.com/q/52378652
tags question: http://stackoverflow.com/q/52424232
tags question: http://stackoverflow.com/q/52388601
tags question: http://stackoverflow.com/q/52284968
tags question: http://stackoverflow.com/q/52416610
tags question: http://stackoverflow.com/q/52368431
tags question: http://stackoverflow.com/q/52418270
tags question: http://stackoverflow.com/q/52335490
tags question: http://stackoverflow.com/q/52356890
tags question: http://stackoverflow.com/q/52339236
tags question: http://stackoverflow.com/q/52347891
tags question: http://stackoverflow.com/q/52368556
tags question: http://stackoverflow.com/q/52425137
tags question: http://stackoverflow.com/q/52391099
tags question: http://stackoverflow.com/q/52331758
tags question: http://stackoverflow.com/q/52361751
tags question: http://stackoverflow.com/q/52280099
tags question: http://stackoverflow.com/q/52373255
tags question: http://stackoverflow.com/q/52358493
tags question: http://stackoverflow.com/q/52392375
tags question: http://stackoverflow.com/q/52370902
tags question: http://stackoverflow.com/q/52315717
tags question: http://stackoverflow.com/q/52324439
tags question: http://stackoverflow.com/q/52416189
tags question: http://stackoverflow.com/q/52315558
tags question: http://stackoverflow.com/q/52359897
tags question: http://stackoverflow.com/q/52373013
tags question: http://stackoverflow.com/q/52358691
tags question: http://stackoverflow.com/q/52412177
tags question: http://stackoverflow.com/q/52283938
tags question: http://stackoverflow.com/q/52358923
tags question: http://stackoverflow.com/q/52310425
tags question: http://stackoverflow.com/q/52359541
tags question: http://stackoverflow.com/q/52365257
tags question: http://stackoverflow.com/q/52286030
tags question: http://stackoverflow.com/q/52398206
tags question: http://stackoverflow.com/q/52351217
tags question: http://stackoverflow.com/q/52308649
tags question: http://stackoverflow.com/q/52339941
tags question: http://stackoverflow.com/q/52283976
tags question: http://stackoverflow.com/q/52406825
tags question: http://stackoverflow.com/q/52422680
tags question: http://stackoverflow.com/q/52306754
tags question: http://stackoverflow.com/q/52355664
tags question: http://stackoverflow.com/q/52272831
tags question: http://stackoverflow.com/q/52318351
tags question: http://stackoverflow.com/q/52357281
tags question: http://stackoverflow.com/q/52416339
tags question: http://stackoverflow.com/q/52303613
tags question: http://stackoverflow.com/q/52355858
tags question: http://stackoverflow.com/q/52354178

http://stackoverflow.com/comment/91619107
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52335953
has text: @MattBouvier `sum` can handle everything you can throw at it. But the problem requires something more than just generating those two sequences of numbers
score: 0

http://stackoverflow.com/a/52432030
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52409422
has body: It is a bug in ptvsd that will be fixed in its next release which will be included in the next release of the Python extension for VS Code.
accepted answer of: http://stackoverflow.com/q/52409422
type: Answer

http://stackoverflow.com/comment/91776168
comment on: http://stackoverflow.com/q/52300976
score: 0
type: Comment
type: QuestionComment
has text: Hi,does my answer helps you?Any progress now?

http://stackoverflow.com/q/52350313
duplicate of: http://stackoverflow.com/q/1098643
downvote count: 1
type: Question
tagged with: list
score: 1
has answer: http://stackoverflow.com/a/52350334
has title: python for loop create a list
tagged with: for-loop
answer count: 3
has body: Ok guys, Why does this simple for-loop fail to fill a list? Here is what I have: axx = [] for i in range(1,7): axx.append('ax'+str(i)) print(axx[i]) I am getting an error: Traceback (most recent call last): File "./bin_data2.py", line 57, in &lt;module&gt; print(axx[i]) IndexError: list index out of range This should pretty simple and straightforward, isn't it? Sorry, coming from Fortran background!
favorite count: 0
has answer: http://stackoverflow.com/a/65431922
has answer: http://stackoverflow.com/a/52350381
tagged with: python
linked to: http://stackoverflow.com/q/1098643
upvote count: 2
type: UnansweredQuestion

pyqtgraph
tags question: http://stackoverflow.com/q/52378875
tags question: http://stackoverflow.com/q/52362966
tags question: http://stackoverflow.com/q/52423155
tag name: pyqtgraph
tags question: http://stackoverflow.com/q/52410731
type: Tag
tags question: http://stackoverflow.com/q/52294677

http://stackoverflow.com/comment/97864220
score: 0
type: AnswerComment
type: Comment
has text: I am using the same script file you have provided with the only change to the python file path. I have not made any change to the verbose setting. What should I do next?
comment on: http://stackoverflow.com/a/55324426

http://stackoverflow.com/a/52372012
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52371716
has comment: http://stackoverflow.com/comment/91689166
upvote count: 1
has body: Instead of appending just the product (your variable ns), you could append a tuple/list/object which contains not only the palindromic number but also the two multiples. Then all you need to change further down is the sorting function. Quick and dirty example: ns_list = [] ns_list_to_int = [] #outside for loop with first 3-digit 'num' and inside loop with second 3-digit 'i' for num in range (100,1000): for i in range(100,1000): n = i*num #need to convert to string &amp; check if reverse of string == string, if so append to list ns = str(n) if ns[::-1] == ns: pint = int(ns) # convert palindrome to int t = (i,num,pint) # all the info you need for later ns_list.append(t) #sort in descending order and call the first number ns_list_to_int = sorted(ns_list, key=lambda x:x[2], reverse=True) # sorting by the palindrome ns_list_to_int[0]

http://stackoverflow.com/q/52282649
has comment: http://stackoverflow.com/comment/91543275
has body: def take_screenshot(hwnd): left, top, right, bot = win32gui.GetClientRect(hwnd) #left, top, right, bot = win32gui.GetWindowRect(hwnd) width = right - left height = bot - top wDC = win32gui.GetWindowDC(hwnd) dcObj=win32ui.CreateDCFromHandle(wDC) cDC=dcObj.CreateCompatibleDC() dataBitMap = win32ui.CreateBitmap() dataBitMap.CreateCompatibleBitmap(dcObj, width, height) cDC.SelectObject(dataBitMap) cDC.BitBlt((0, 0), (width, height), dcObj, (0, 0), win32con.SRCCOPY) im = dataBitMap.GetBitmapBits(True) img = np.frombuffer(im, dtype='uint8') img.shape = (height,width,4) cv2.cvtColor(img, cv2.COLOR_RGB2BGR) dcObj.DeleteDC() cDC.DeleteDC() win32gui.ReleaseDC(hwnd, wDC) win32gui.DeleteObject(dataBitMap.GetHandle()) return img[:,:,:3] I'm using this code at the moment. Is there any way to make it faster= I want to be able to capture 1080 at 60 fps live. Can I use my gpu for this problem? I have gtx 1070.
has title: Fastest way to take screenshot of a window
score: 0
has comment: http://stackoverflow.com/comment/91515140
tagged with: windows
answer count: 0
has comment: http://stackoverflow.com/comment/91515925
type: UnansweredQuestion
tagged with: python
tagged with: screenshot
has comment: http://stackoverflow.com/comment/91515968
has comment: http://stackoverflow.com/comment/91513604
type: Question

http://stackoverflow.com/comment/91519443
has text: Hint: You forgot a term when calculating `secondes`. I bet that your `secondes` is off by a multiple of 3600.
score: 0
comment on: http://stackoverflow.com/q/52284800
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91524622
score: 0
type: Comment
type: QuestionComment
has text: The txt file you provided has 2 colums. Is this the right dataset?
comment on: http://stackoverflow.com/q/52286971

http://stackoverflow.com/comment/91618135
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52335321
type: Comment
has text: Not sure I understand your question. Elasticsearch is just a piece of software written in Java, a search engine. You can build any type of web interface and query elasticsearch through basic HTTP calls. You can use any tech stack on your backend that will allow for HTTP calls to be made to your Elasticsearch instance. Most programming languages have a Elasticsearch client library that will help you do this if you don't want to use plain HTTP calls, have a look at this page to get an idea https://www.elastic.co/guide/en/elasticsearch/client/index.html

scintilla
type: Tag
tag name: scintilla
tags question: http://stackoverflow.com/q/52354989

http://stackoverflow.com/comment/91563299
type: Comment
comment on: http://stackoverflow.com/a/52307988
score: 0
type: AnswerComment
has text: Traceback (most recent call last): File "C:\Users\David\eclipse-workspace\Kaplin\password_cracker.py", line 2, in <module> for i in f: File "C:\Users\David\AppData\Local\Programs\Python\Python37\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 753: character maps to <undefined>

http://stackoverflow.com/q/52416580
tagged with: convolution
has comment: http://stackoverflow.com/comment/91784184
tagged with: python
has answer: http://stackoverflow.com/a/52508180
has comment: http://stackoverflow.com/comment/91811386
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52419930
upvote count: 1
has title: Differences between Python and Julia convolutions?
tagged with: julia
has body: I'm trying to convert a section of code from Python to Julia and I'm having a hard time understanding the output differences between the following convolutions: Python: conc = [10,100,1000,5,2000,200,20] conc_filter = [1,2,3] sp.ndimage.convolve1d(conc, conc_filter,axis=0,mode='constant') Output:[ 120, 1230, 2305, 5010, 4215, 6420, 640] Julia: conc = [10,100,1000,5,2000,200,20] conc_filter = [1,2,3] conv(conc,conc_filter) Output: [10, 120, 1230, 2305, 5010, 4215, 6420, 640, 60] Can anyone explain why the output lengths are different? In an attempt to recreate the Python output, I've tried to come up with a logical formula that relates the input/filter sizes with the index range required to slice the conv output and obtain the same result. However, I haven't had much luck. Is there a Julia function that can produce the same output?
type: Question
has comment: http://stackoverflow.com/comment/91778180
score: 1
has comment: http://stackoverflow.com/comment/91813667
accepted answer: http://stackoverflow.com/a/52508180
has comment: http://stackoverflow.com/comment/91776997
answer count: 3
possible better answer: http://stackoverflow.com/a/52420187
downvote count: 0
has answer: http://stackoverflow.com/a/52420187
has comment: http://stackoverflow.com/comment/91798931
favorite count: 0
has comment: http://stackoverflow.com/comment/91815036
has comment: http://stackoverflow.com/comment/91780165

http://stackoverflow.com/comment/91635749
type: QuestionComment
has text: Possible duplicate of https://stackoverflow.com/questions/4260280/if-else-in-pythons-list-comprehension
comment on: http://stackoverflow.com/q/52344932
score: 0
type: Comment

http://stackoverflow.com/comment/91492582
type: QuestionComment
has text: @shuttle87 Because `pytest.fail()` doesn't make difference when called in fixture it still gives an **Error**. Have you tested your solutions or I get the wrong idea?
score: 0
comment on: http://stackoverflow.com/q/52271750
type: Comment

http://stackoverflow.com/q/52337602
has comment: http://stackoverflow.com/comment/91622507
type: UnansweredQuestion
tagged with: python
has title: Python TypeError: 'str' object is not callable image
has body: test_image = image.load_img('dataset/kot/cat.4003.jpg', target_size = (64, 64)) test_image = image.img_to_array('cat.4003.jpg'(64, 64)) test_image = np.expand_dims('dataset/kot/cat.4003.jpg', axis = 0) Hi guys, Could you tell me what's wrong with this code? I'm really new in this, And i got this error as you can see above. Maybe you can see more mistakes. I would be grateful for that.
type: Question
has answer: http://stackoverflow.com/a/52337628
score: 0
answer count: 1

http://stackoverflow.com/a/52305061
has body: You don't need the index=str bit, this will work unless your column is your index: new="new_name" df.rename(columns={'old_name':new}) input: ID1 old_name Date 0 1 2 1/1/2018 1 1 2 3/1/2018 2 1 2 4/5/2018 output: ID1 new_name Date 0 1 2 1/1/2018 1 1 2 3/1/2018 2 1 2 4/5/2018 if you want to save it: df = df.rename(columns={'old_name':new}) if you want to rename index: df.index.rename(new, inplace=True) output: ID1 ID2 Date new_name 0 1 2 1/1/2018 1 1 2 3/1/2018 2 1 2 4/5/2018
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52304992
score: 3
answers question: http://stackoverflow.com/q/52304992
type: Answer
upvote count: 3

http://stackoverflow.com/comment/91513386
type: QuestionComment
has text: What happens now when the square hits the ball?
comment on: http://stackoverflow.com/q/52280054
type: Comment
score: 0

http://stackoverflow.com/q/52390125
score: 23
favorite count: 0
answer count: 6
has comment: http://stackoverflow.com/comment/91725184
type: Question
has answer: http://stackoverflow.com/a/52390265
tagged with: python
possible better answer: http://stackoverflow.com/a/52390201
has comment: http://stackoverflow.com/comment/91725261
upvote count: 23
has answer: http://stackoverflow.com/a/52390201
tagged with: list
has comment: http://stackoverflow.com/comment/91725512
has answer: http://stackoverflow.com/a/52390215
has answer: http://stackoverflow.com/a/52390400
has comment: http://stackoverflow.com/comment/92201909
has title: Associating two item in a list
has answer: http://stackoverflow.com/a/52390332
has body: I am comparing two lists for common strings and my code currently works to output items in common from two lists. list1 ['5', 'orange', '20', 'apple', '50', 'blender'] list2 ['25', 'blender', '20', 'pear', '40', 'spatula'] Here is my code so far: for item1 in list1[1::2]: for item2 in list2[1::2]: if item1 == item2: print(item1) This code would return blender. What I want to do now is to also print the number before the blender in each list to obtain an output similar to: blender, 50, 25 I have tried to add two new lines to the for loop but did not have the desired output: for item1 in list1[1::2]: for item2 in list2[1::2]: for num1 in list1[0::2]: for num2 in list2[0::2]: if item1 == item2: print(item1, num1, num2) I know now that making for loops is not the answer. Also trying to call item1[-1] does not work. I am new to Python and need some help with this! Thank you
accepted answer: http://stackoverflow.com/a/52390332
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52390273
downvote count: 0

http://stackoverflow.com/a/52391898
answers question: http://stackoverflow.com/q/52391765
has body: You can use: N = 5 result = '\n'.join( # space delimited numbers from 1 to current loop ' '.join(str(i) for i in range(1, j)) # for everything for 1..2, 1..3, 1..4 etc... # since range(1,1) is empty and we're starting from 2, # we use N+2 to ensure all loops are counted for j in range(2, N + 2) ) Which'll give you: '1\n1 2\n1 2 3\n1 2 3 4\n1 2 3 4 5' ​
score: 0
type: Answer

http://stackoverflow.com/comment/91784924
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52408502
has text: Xitrum, Thanks for that but unfortunately that has also not improved the result, the accuracies diverge when the validation accuracy reaches ~0.68 - 0.7. We had a call this morning and are looking at some feature boosting techniques and to create a relevant, yet different target variable - I know that normally addresses bias, but our thinking is to try looking at different techniques if this is not working as we need it to. Thanks
score: 0

http://stackoverflow.com/comment/91560657
type: AnswerComment
comment on: http://stackoverflow.com/a/52306398
type: Comment
has text: So my original file computes the 2 columns and then outputs them in the txt file. I was hoping to have ~60 columns of data in the single txt file is my point. It loops through all dump files and adds a new column of data. Or is there a way to write a new txt file for each dump file iterated through?
score: 0

http://stackoverflow.com/comment/91517040
comment on: http://stackoverflow.com/a/52283347
type: AnswerComment
score: 0
type: Comment
has text: You're welcome. However, I think your path from csv to plot is optimizable. I'm certainly not sure if I understand your data and your task completely correct, but I'll try to give you some additional hints in a further edit.

http://stackoverflow.com/comment/91699892
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52377617
has text: Check this out: https://stackoverflow.com/questions/11522933/python-floating-point-arbitrary-precision-available

http://stackoverflow.com/q/52346175
has body: I'm trying to modify my lists using another list which has the channel and the position in that channel I want to change(I want to change 128 to 0). redchannel = [128, 128, 128, 128, 128] greenchannel = [128, 128, 128, 128, 128] bluechannel = [128, 128, 128, 128, 128] index = [['b', 0], ['g', 1], ['r', 2], ['r', 4]] I want to do this: redchannel = [128, 128, 0, 128, 0] greenchannel = [128, 0, 128, 128, 128] bluechannel = [0, 128, 128, 128, 128] I'm trying to iterate index and apply the changes that each item is showing
answer count: 1
has answer: http://stackoverflow.com/a/52346202
accepted answer: http://stackoverflow.com/a/52346202
has comment: http://stackoverflow.com/comment/91638195
favorite count: 0
has comment: http://stackoverflow.com/comment/91638005
has title: Modifying lists using another list
upvote count: 0
tagged with: python
downvote count: 1
type: AnsweredQuestion
score: -1
type: Question

http://stackoverflow.com/a/52389590
has comment: http://stackoverflow.com/comment/91730524
has comment: http://stackoverflow.com/comment/91747758
has body: It won't work because of the self parameter. Instead, define it like this: class A(object): def method1(self, input): return method1(input)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52389511

http://stackoverflow.com/comment/91776606
comment on: http://stackoverflow.com/a/52402501
score: 0
type: AnswerComment
type: Comment
has text: This could be a great solution. Though each column will have its own LUT because they all use different offset/gain value. It would be just a larger LUT but same principle.

http://stackoverflow.com/comment/91788229
comment on: http://stackoverflow.com/q/52415933
has text: What are you using scapy3 (do you mean kamene?) for, that doesn't work in mainline Scapy?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52370310
has comment: http://stackoverflow.com/comment/91685361
has comment: http://stackoverflow.com/comment/91685217
tagged with: list
has comment: http://stackoverflow.com/comment/91685640
has comment: http://stackoverflow.com/comment/91685239
has answer: http://stackoverflow.com/a/52372249
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91685850
has comment: http://stackoverflow.com/comment/91686289
has comment: http://stackoverflow.com/comment/91685516
has title: Find repeated element in a nested list
has comment: http://stackoverflow.com/comment/91686092
score: 0
has comment: http://stackoverflow.com/comment/91685433
has comment: http://stackoverflow.com/comment/91685651
has answer: http://stackoverflow.com/a/52371825
has comment: http://stackoverflow.com/comment/91685352
linked to: http://stackoverflow.com/q/7961363
favorite count: 0
has comment: http://stackoverflow.com/comment/91685727
has body: I have a nested list of elements: employee_list = [ ['Name', '=', 'John'], ['Age', '=', '32'], ['Weight', '=', '60'], ['Name', '=', 'Steve'], ['Weight', '=', '85'] ] I want to create two lists of elements: one which has repeated elements and another with unique elements. But I also wanted the repetition to be maintained unique_list = 'Age', '=', '32' repeated_list = [ ['Name', '=', 'John'], ['Weight', '=', '60'], ['Name', '=', 'Steve'], ['Weight', '=', '85'] ] Uniqueness or repetition is determined by the first element of every sub list. For example: 'Name', 'Weight'. If there are two sub lists where the first element is 'Name' I consider it as repetition. Can anyone suggest an easy way to do this?
has comment: http://stackoverflow.com/comment/91685437
has answer: http://stackoverflow.com/a/52370509
tagged with: nested-lists
has answer: http://stackoverflow.com/a/52370516
answer count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91685127
has comment: http://stackoverflow.com/comment/91685245
has comment: http://stackoverflow.com/comment/91685527
has answer: http://stackoverflow.com/a/52370738
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91685386

http://stackoverflow.com/q/52339890
has body: file1.txt neighbor 192.168.3.1 remote-as 200 neighbor 192.168.4.1 remote-as 300 neighbor 192.168.15.1 remote-as 400 neighbor 192.168.16.1 remote-as 500 neighbor 20.249.208.165 remote-as 200 neighbor 80.249.208.165 remote-as 100 neighbor 192.168.5.1 remote-as 400 file2.txt neighbor 26.24.1.165 remote-as 200 neighbor 90.239.208.165 remote-as 100 neighbor 192.168.3.1 remote-as 200 neighbor 192.168.4.1 remote-as 300 neighbor 192.168.5.1 remote-as 400 neighbor 192.168.6.1 remote-as 500 neighbor 192.168.15.1 remote-as 400 neighbor 192.168.16.1 remote-as 500 i have these two files!!!! i want to compare each line of file1.txt with all lines from file2.txt and print the lines which doenst match. i have tried a lot of mothods, sometime having problem to use variables outside of for loops! can anyone help me !!! Thanks
has title: python compare two texts files en print the output to another file
duplicate of: http://stackoverflow.com/q/40029985
tagged with: python
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52340052
type: Question
has comment: http://stackoverflow.com/comment/91627106
linked to: http://stackoverflow.com/q/40029985
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52340052

http://stackoverflow.com/a/52415457
type: Answer
score: 2
downvote count: 0
has body: You can use find_threshold_by_max_metric model.find_threshold_by_max_metric('f1', train=True, valid=False, xval=False)
accepted answer of: http://stackoverflow.com/q/52410238
has comment: http://stackoverflow.com/comment/91797627
answers question: http://stackoverflow.com/q/52410238
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/52281786
tags question: http://stackoverflow.com/q/52280487
tags question: http://stackoverflow.com/q/52356087
tags question: http://stackoverflow.com/q/52370547
tags question: http://stackoverflow.com/q/52350801
tags question: http://stackoverflow.com/q/52401504
tags question: http://stackoverflow.com/q/52410410
tags question: http://stackoverflow.com/q/52359617
tags question: http://stackoverflow.com/q/52293389
tags question: http://stackoverflow.com/q/52417265
tags question: http://stackoverflow.com/q/52331845
tags question: http://stackoverflow.com/q/52390447
tags question: http://stackoverflow.com/q/52401433
tags question: http://stackoverflow.com/q/52292589
tags question: http://stackoverflow.com/q/52280712
tags question: http://stackoverflow.com/q/52353743
tags question: http://stackoverflow.com/q/52317379
tags question: http://stackoverflow.com/q/52405799
tags question: http://stackoverflow.com/q/52297481
tags question: http://stackoverflow.com/q/52387762
tags question: http://stackoverflow.com/q/52361783
tags question: http://stackoverflow.com/q/52286056
tags question: http://stackoverflow.com/q/52331628
tags question: http://stackoverflow.com/q/52326223
tags question: http://stackoverflow.com/q/52386447
type: Tag
tags question: http://stackoverflow.com/q/52371472
tags question: http://stackoverflow.com/q/52328155
tags question: http://stackoverflow.com/q/52418478
tags question: http://stackoverflow.com/q/52346113
tags question: http://stackoverflow.com/q/52380080
tags question: http://stackoverflow.com/q/52325727
tags question: http://stackoverflow.com/q/52294855
tags question: http://stackoverflow.com/q/52404476
tags question: http://stackoverflow.com/q/52371966
tags question: http://stackoverflow.com/q/52397920
tags question: http://stackoverflow.com/q/52337216
tags question: http://stackoverflow.com/q/52393610
tags question: http://stackoverflow.com/q/52391631
tags question: http://stackoverflow.com/q/52427123
tags question: http://stackoverflow.com/q/52335559
tags question: http://stackoverflow.com/q/52424772
tags question: http://stackoverflow.com/q/52314854
tags question: http://stackoverflow.com/q/52428921
tag name: json
tags question: http://stackoverflow.com/q/52327692
tags question: http://stackoverflow.com/q/52327740
tags question: http://stackoverflow.com/q/52426475
tags question: http://stackoverflow.com/q/52418205
tags question: http://stackoverflow.com/q/52318675
tags question: http://stackoverflow.com/q/52420866
tags question: http://stackoverflow.com/q/52303771
tags question: http://stackoverflow.com/q/52281671
tags question: http://stackoverflow.com/q/52382206
tags question: http://stackoverflow.com/q/52279153
tags question: http://stackoverflow.com/q/52415948
tags question: http://stackoverflow.com/q/52404565
tags question: http://stackoverflow.com/q/52363163
tags question: http://stackoverflow.com/q/52282221
tags question: http://stackoverflow.com/q/52314186
tags question: http://stackoverflow.com/q/52354640
tags question: http://stackoverflow.com/q/52362148
tags question: http://stackoverflow.com/q/52388586
tags question: http://stackoverflow.com/q/52290693
tags question: http://stackoverflow.com/q/52337872
tags question: http://stackoverflow.com/q/52374941
tags question: http://stackoverflow.com/q/52387812
tags question: http://stackoverflow.com/q/52378831
tags question: http://stackoverflow.com/q/52366901
tags question: http://stackoverflow.com/q/52314576
tags question: http://stackoverflow.com/q/52413106
tags question: http://stackoverflow.com/q/52380847
tags question: http://stackoverflow.com/q/52343860
tags question: http://stackoverflow.com/q/52388348
tags question: http://stackoverflow.com/q/52413563
tags question: http://stackoverflow.com/q/52342412
tags question: http://stackoverflow.com/q/52389696
tags question: http://stackoverflow.com/q/52291863

http://stackoverflow.com/q/52336196
type: AnsweredQuestion
score: 2
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: pickle
tagged with: python
tagged with: pygame
has title: How to save object using pygame.Surfaces to file using pickle
has answer: http://stackoverflow.com/a/52337061
upvote count: 2
answer count: 1
has body: If I have created my own class which has some attributes that are pygame.Surfaces and I would like to save this object to a file, how can I do this as an error occurs when I try. The class which I have created is an object which is essentially the following (Item class is included because the player has items which have attributes that are pygame.Surfaces): class Item: def __init__(self,name,icon): self.name = name self.icon = pygame.image.load(icon) class Player(pygame.Sprite): def __init__(self,{some_attrs}) skins = [{a pygame.Surface from a load image},{another}] self.money = 0 self.items = [{Item object}] Then when I try to save, I use the following: with open('save.dat','wb') as file: pickle.dump(player , file , protocol = 4) #I have also tried without the protocol argument But I get the following error: Traceback (most recent call last): File "{file path}", line 883, in &lt;module&gt; save_progress() File "{file path}", line 107, in save_progress pickle.dump(player,file,protocol=4) TypeError: can't pickle pygame.Surface objects FYI, Everything that I have put in curly braces ({ and }) is just something that I have abbreviated or left out because it wasn't needed If you need any more detail, I can easily add it if you reply what you need
has comment: http://stackoverflow.com/comment/91619471
tagged with: pygame-surface
accepted answer: http://stackoverflow.com/a/52337061

http://stackoverflow.com/a/52330774
has body: Dataset: spi = Dataset('spi3_6_12_1deg_cru_ts_3_21_1949_2012.nc') lats = spi.variables['lat'][:] lons = spi.variables['lon'][:] time = spi.variables['time'][:] spi3 = spi.variables['spi3'][:] spi6 = spi.variables['spi6'][:] spi12 = spi.variables['spi12'][:] ds = xr.open_dataset('spi3_6_12_1deg_cru_ts_3_21_1949_2012.nc') ds_mlw = ds.sel(lon=slice(33,37), lat=slice(-18,-13), time=slice("2002-01-01", "2017-11-01")) spi_avg_1 = ds_mlw.mean(dim=('lon', 'lat')) The script is as follows: def line_intersection(line1, line2): xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0]) ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]) #Typo was here def det(a, b): return a[0] * b[1] - a[1] * b[0] div = det(xdiff, ydiff) if div == 0: return None d = (det(*line1), det(*line2)) x = det(d, xdiff) / div y = det(d, ydiff) / div return x, y def near(a, b, rtol=1e-5, atol=1e-8): return abs(a - b) &lt; (atol + rtol * abs(b)) def crosses(line1, line2): """ Return True if line segment line1 intersects line segment line2 and line1 and line2 are not parallel. """ (x1,y1), (x2,y2) = line1 (u1,v1), (u2,v2) = line2 (a,b), (c,d) = (x2-x1, u1-u2), (y2-y1, v1-v2) e, f = u1-x1, v1-y1 denom = float(a*d - b*c) if near(denom, 0): # parallel return False else: t = (e*d - b*f)/denom s = (a*f - e*c)/denom # When 0&lt;=t&lt;=1 and 0&lt;=s&lt;=1 the point of intersection occurs within the # line segments return 0&lt;=t&lt;=1 and 0&lt;=s&lt;=1 spi_avg_1['spi3'].plot(label='SPI 3- monthly') plt.axhline(y=-1, color='r', linestyle='-', linewidth=0.5) #threshold spi idicicator of drought plt.title('SPI 3-monthly') yys = [-1] xx, yy = [], [] xo,yo = [k for k in range(200)],spi_avg_1['spi3'] for i in range(1,len(spi_avg_1['spi3'])): for k in yys: p1 = np.array([xo[i-1],yo[i-1]],dtype='float') p2 = np.array([xo[i],yo[i]],dtype='float') k1 = np.array([xo[i-1],k],dtype='float') k2 = np.array([xo[i],k],dtype='float') if crosses((p2,p1),(k1,k2)): seg = line_intersection((p2,p1),(k1,k2)) plt.scatter(…
has comment: http://stackoverflow.com/comment/91908982
answers question: http://stackoverflow.com/q/52329570
score: 0
type: Answer

http://stackoverflow.com/q/52333598
has comment: http://stackoverflow.com/comment/91620393
has body: Have been facing this issue for a while now. Trying to execute my test suite involving db creations, schema creations and deletions using sqlalchemy throws this error: (psycopg2.ProgrammingError) must be a member of the role whose process is being terminated Code in which error is thrown: from sqlalchemy_utils import drop_database drop_database(TEST_URI) It is confusing and annoying at the same time. Rerunning the test suite might give me a success so there is not a fixed pattern. Wondering if the solution(a hacky one) mentioned here is the only way one could escape from this error. Any help is appreciated.
tagged with: postgresql
has comment: http://stackoverflow.com/comment/91620097
has title: Intermittent sqlalchemy drop_database error (psycopg2.ProgrammingError) must be a member of the role whose process is being terminated
has comment: http://stackoverflow.com/comment/91620362
has comment: http://stackoverflow.com/comment/91619812
favorite count: 0
has comment: http://stackoverflow.com/comment/91619902
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
upvote count: 1
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/91620304
has comment: http://stackoverflow.com/comment/91619982
downvote count: 0

http://stackoverflow.com/comment/103914968
comment on: http://stackoverflow.com/q/52310689
has text: See answer in [How to set ipython/jupyter as the default python terminal for vscode?](https://stackoverflow.com/questions/52615414/how-to-set-ipython-jupyter-as-the-default-python-terminal-for-vscode)
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52382444
has comment: http://stackoverflow.com/comment/91709214
downvote count: 0
has answer: http://stackoverflow.com/a/52383460
favorite count: 0
has comment: http://stackoverflow.com/comment/133394498
type: Question
accepted answer: http://stackoverflow.com/a/52383460
tagged with: python
has body: I have a string 27AAGCB5913L2ZF. If any of A or J or K appear in the string then it I need to change them to all possible combinations of the three letters. If I pass the above string input to the program then the output should be like this 27AAGCB5913L2ZF 27AJGCB5913L2ZF 27AKGCB5913L2ZF 27JAGCB5913L2ZF 27KAGCB5913L2ZF 27KJGCB5913L2ZF 27JKGCB5913L2ZF 27JJGCB5913L2ZF 27KKGCB5913L2ZF The letters may be present anywhere in string. If just a single letter is present then it must be replaced by A, J and K in turn. For example the output for the string 27ABGCB5913L2ZF should be as follows 27ABGCB5913L2ZF 27JBGCB5913L2ZF 27kBGCB5913L2ZF I can search for a given character with code like this while ( $string =~ /(B)/g ) { say $1, ' at ', pos $string; } How can I produce all possible strings if there could be any number of A, J, or K in any positions?
score: 4
has title: Replace combinations of characters
linked to: http://stackoverflow.com/q/14841652
has answer: http://stackoverflow.com/a/52384810
possible better answer: http://stackoverflow.com/a/52384216
has answer: http://stackoverflow.com/a/52384216
tagged with: combinations
has answer: http://stackoverflow.com/a/52384917
has comment: http://stackoverflow.com/comment/133394130
linked to: http://stackoverflow.com/q/533905
tagged with: replace
upvote count: 4
answer count: 4
type: AnsweredQuestion
tagged with: perl

http://stackoverflow.com/q/52357812
answer count: 0
tagged with: autoencoder
has title: Improve convergence rate of Keras autoencoder
has body: I want to train a convolutional autoencoder on (pretty noisy) images. For that I build a training_generator and a validation_generator that both produce batches of 120 images. I use 111 batches per epoch for training and 47 batches per epoch for validation. The images have three colors with values from 0 to 255 per channel (color), but the generator turns them into values between 0 and 1 by using images = images.astype('float32') / 255.0. The architecture is from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D from keras.models import Model input_img = Input(shape=(152, 360, 3)) # adapt this if using `channels_first` image data format x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img) #1 x = MaxPooling2D((2, 2), padding='same')(x) #2 x = Conv2D(8, (3, 3), activation='relu', padding='same')(x) #3 x = MaxPooling2D((2, 2), padding='same')(x) #4 x = Conv2D(8, (3, 3), activation='relu', padding='same')(x) #5 encoded = MaxPooling2D((2, 2), padding='same')(x) #6 # at this point the representation is autoencoder.layers[6].output_shape = (None, 19, 45, 8) x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded) #7 x = UpSampling2D((2, 2))(x) #8 x = Conv2D(8, (3, 3), activation='relu', padding='same')(x) #9 x = UpSampling2D((2, 2))(x) #10 x = Conv2D(16, (3, 3), activation='relu', padding='same')(x) #11 x = UpSampling2D((2, 2))(x) #12 decoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x) #13 autoencoder = Model(input_img, decoded) autoencoder.compile(optimizer='adadelta', loss='mean_squared_error') autoencoder.fit_generator( generator=training_generator, validation_data=validation_generator, use_multiprocessing=True, workers=2, epochs=2) I oriented myself according to https://blog.keras.io/building-autoencoders-in-keras.html but changed the loss from "binary_crossentropy" to "mean_squared_error", because the values of the images are not just 0 or 1, as it is the case for the MNIST dataset, but between 0 and 1 (afte…
has comment: http://stackoverflow.com/comment/91675899
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/91660710
has comment: http://stackoverflow.com/comment/91676404
type: Question
has comment: http://stackoverflow.com/comment/91660929
has comment: http://stackoverflow.com/comment/91669516
has comment: http://stackoverflow.com/comment/91660674
tagged with: keras
has comment: http://stackoverflow.com/comment/91661373
has comment: http://stackoverflow.com/comment/91675377
score: 0
has comment: http://stackoverflow.com/comment/91675838
has comment: http://stackoverflow.com/comment/91660825
has comment: http://stackoverflow.com/comment/91661033
has comment: http://stackoverflow.com/comment/91677353
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/91676463

http://stackoverflow.com/comment/91680443
type: Comment
type: QuestionComment
has text: Can you please put this into your question?
comment on: http://stackoverflow.com/q/52367566
score: 0

http://stackoverflow.com/comment/91733150
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52390790
has text: @Jeremy Hhh ,very strange. because when i also just make it in new default notebook, it was also, ok , but in my whole example ,it's not working, i will try to provide whole code

http://stackoverflow.com/a/52346251
has comment: http://stackoverflow.com/comment/91638156
accepted answer of: http://stackoverflow.com/q/52346113
score: 2
has body: The following JSON file: {"lesson 1": {"part one": [ {"question": "What is the meaning of 'ست' ?", "transliteration": "sit", "answer": "woman" } ], "part two": [ ], "part three": [ {"question": "What is the meaning of '3test2'?", "transliteration": "phonix2", "answer": "32" } ]} } with the following python code: import json with open("test.json", "r", encoding = "utf-8-sig") as read_file: data = json.load(read_file) for i in data["lesson 1"]["part one"]: print (i["question"]) for i in data["lesson 1"]["part two"]: print (i["answer"]) works as expected. print(data["lesson 1"]["part two"]) works as well. You need to remove the square brackets after "lesson1: and sort out your indexing of the variables
answers question: http://stackoverflow.com/q/52346113
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91647563
type: Answer
downvote count: 0

http://stackoverflow.com/comment/91570916
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52299186
type: AnswerComment
has text: but I get an error : Traceback (most recent call last): File "test3.py", line 32, in <module> startnum = int(times_pairs_str.index(str2)) ValueError: 'Fajr' is not in list

http://stackoverflow.com/q/52378288
tagged with: sorting
type: Question
type: AnsweredQuestion
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52378903
tagged with: python
answer count: 1
downvote count: 1
upvote count: 3
has comment: http://stackoverflow.com/comment/91701197
accepted answer: http://stackoverflow.com/a/52378903
score: 2
has title: How exactly does the loop within a bubble sort algorithm work? (Python 3)
tagged with: nested-loops
has comment: http://stackoverflow.com/comment/91701127
has body: Example code: def bubble_sort(my_list): n = len(my_list) for i in range(n): for j in range(0, n - 1 - i): if my_list[j] &gt; my_list[j + 1]: my_list[j], my_list[j + 1] = my_list[j + 1], my_list[j] my_list = [94, 17, 5, 28, 7, 63, 44] bubble_sort(my_list) print(my_list) In the code above, I am confused about the for for __ in range() part of the nested loop. What does this do and how does it do it? Also, how does my_list[j], my_list[j+1] = my_list[j+1], my_list[j] rearrange the the list values? Sorry if this sounds dumb, but I want to understand the logic behind the syntax I'm writing, and I couldn't find a place that explained the logic well, so hopefully someone who sees this can. Thanks for any help!
tagged with: bubble-sort

http://stackoverflow.com/q/52395695
has answer: http://stackoverflow.com/a/64785969
possible better answer: http://stackoverflow.com/a/53777112
score: 24
tagged with: google-cloud-platform
upvote count: 24
has answer: http://stackoverflow.com/a/52395801
accepted answer: http://stackoverflow.com/a/52395801
favorite count: 0
tagged with: gunicorn
tagged with: google-app-engine
has answer: http://stackoverflow.com/a/53777112
has answer: http://stackoverflow.com/a/62647741
tagged with: python
answer count: 4
type: AnsweredQuestion
downvote count: 0
tagged with: django
has title: ModuleNotFoundError - No module named 'main' when attempting to start service
has body: Context: I created a Django application using Python 3.7. I am (attempting) to use the 2nd generation Google App Engine standard environment. My application performs flawlessly when I run it via python manage.py runserver. Yet it comes to a sudden halt when I attempt to deploy it to Google App Engine. Traceback (most recent call last): File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app __import__(module) ModuleNotFoundError: No module named 'main' I've gone through numerous threads and I cannot find the problem. (For reference the dev_appserver.py emulator produces the same problem, which is a good thing). Following is my app.yaml runtime: python37 env: standard handlers: - url: /static static_dir: static/ - url: .* script: demosite.wsgi.main My wsgi.py file is located in the following path: demosite/wsgi.py and it's contents look like this: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'demosite.settings') main = get_wsgi_application() My settings.py file: import os class AppSettings(object): GoogleCloudProject = os.getenv('GOOGLE_CLOUD_PROJECT') BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'say what?'…
type: Question

http://stackoverflow.com/comment/91733274
comment on: http://stackoverflow.com/q/52394009
score: 2
type: QuestionComment
has text: This *should* work. Chances are something else is going wrong (e.g. a typo when you move the file)
type: Comment

http://stackoverflow.com/comment/91639744
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52347131
has text: `self.p1` is a string. How do you expect it to "move"?
score: 1

http://stackoverflow.com/q/52345919
upvote count: 1
tagged with: user-interface
has answer: http://stackoverflow.com/a/52354370
accepted answer: http://stackoverflow.com/a/52354370
favorite count: 0
tagged with: python
tagged with: qt
type: AnsweredQuestion
has title: Eric IDE, Qt File Dialog: show hidden files
downvote count: 0
score: 1
type: Question
tagged with: eric-ide
answer count: 1
has body: How am I supposed to handle hidden files like .gitignore in my Eric project? Open Dialog does not seem to have an option to show hidden files; I couldn't find any such option anywhere in settings or configurations. Is there a solution?

http://stackoverflow.com/q/52382503
type: Question
has answer: http://stackoverflow.com/a/52383448
has comment: http://stackoverflow.com/comment/91752238
tagged with: dataframe
score: -1
tagged with: pandas
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/91710146
has title: Pandas: cumsum by group across time, resampled to entire dataframe
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: cumsum
has body: I have a time series data frame. I'm interested in plotting the cumulative sums across time, by groups of [column1, column2]. So far I can only plot the cumulative sum at the points where the group combination existed. What I want is the cumulative sum for each group at every single timestamp in the original data frame, so I can easily plot the total cumulative sum on the same plot as the group cumulative sums. [EDIT] I got it working by doing this, for each group I'm interested in: values = np.where((df.column1==someVal) &amp; (df.column2==someVal), df.column3, 0).cumsum() plt.plot(df.timestamp, values)
downvote count: 2

http://stackoverflow.com/comment/91800784
type: Comment
type: QuestionComment
has text: Something in `itertools` should be able to generate all the combinations.
comment on: http://stackoverflow.com/q/52428601
score: 1

http://stackoverflow.com/comment/91610592
type: QuestionComment
comment on: http://stackoverflow.com/q/52331867
score: 0
has text: Is the images in the last line your output? And do you want to parallelize step 3-4?
type: Comment

http://stackoverflow.com/q/52408644
has answer: http://stackoverflow.com/a/52489739
tagged with: sqlalchemy
type: Question
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52489739
tagged with: python
has body: I am working on an application where my database objects often have multiple parents and multiple children, and would like to create a SQLAlchemy query that will return all descendants of an object. Realizing that I am basically trying to store a graph in a SQL database, I found that setting up a self-referential many-to-many schema got me most of the way there, but I am having trouble writing the query to return all descendants of a node. I tried to follow SQLA's recursive CTE example, which looks like the right approach, but have been running into problems getting it to work. I think my situation is different from the example because in my case, queries to Node.child (and Node.parent) return instrumented lists and not ORM objects. In any case, the code below will set up a simple directed acyclic disconnected graph that looks like this (where the direction is inferred to be from the higher row to the lower one): a b c \ / \ | d e f |\ / g h | i And what I'm looking for is some help writing a query that will give me all descendants of a node. get_descendants(d) should return g, h, i get_descendants(b) should return d, e, g, h, i Example code: from sqlalchemy.orm import aliased from sqlalchemy import Column, ForeignKey, Integer, Table, Text from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///:memory:', echo=True) Session = sessionmaker(bind=engine) session = Session() Base = declarative_base() association_table = Table('association_table', Base.metadata, Column('parent_id', Integer, ForeignKey('node.id'), primary_key=True), Column('child_id', Integer, ForeignKey('node.id'), primary_key=True)) class Node(Base): __tablename__ = 'node' id = Column(Integer, primary_key=True) property_1 = Column(Text) property_2 = Column(Integer) # http://docs.sqlalchemy.org/en/latest/orm/join_conditions.html#self-referential-many-to-ma…
upvote count: 3
has title: How can I write a SQLAlchemy query that will return all descendants of a node in a graph?
tagged with: orm
tagged with: graph
type: AnsweredQuestion
score: 3
tagged with: many-to-many

http://stackoverflow.com/q/52330887
has comment: http://stackoverflow.com/comment/133614115
has comment: http://stackoverflow.com/comment/133614249
has comment: http://stackoverflow.com/comment/116329203
has answer: http://stackoverflow.com/a/75715876
has body: I am looking to extract some text from a meter display using Python 3 and OpenCV. I have had some success with a lot of help from SO on the code below, and I can print text from a basic and 'tidy' image file. However when I look to extract from the attached dot matrix image the script is unable to pick out any text at all. Is there a limitation to extracting in this kind of dot matrix text? Here's what I am working with: import cv2 import numpy as np import pytesseract from PIL import Image from cv2 import boundingRect, countNonZero, cvtColor, drawContours, findContours, getStructuringElement, \ imread, morphologyEx, pyrDown, rectangle, threshold img = imread('test.JPG') # down sample and use it for processing adjusted = pyrDown(img) # gray-scale image img_gray = cvtColor(adjusted, cv2.COLOR_BGR2GRAY) # morph gradient morph_kernel = getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) grad = morphologyEx(img_gray, cv2.MORPH_GRADIENT, morph_kernel) # change to binary and morph _, bw = threshold(src=grad, thresh=0, maxval=255, type=cv2.THRESH_BINARY+cv2.THRESH_OTSU) morph_kernel = getStructuringElement(cv2.MORPH_RECT, (9, 1)) connected = morphologyEx(bw, cv2.MORPH_CLOSE, morph_kernel) applyMask = np.zeros(bw.shape, np.uint8) # get contours im2, contour, hierarchy = findContours(connected, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) # filter contours for index in range(0, len(hierarchy[0])): rect = x, y, rectangle_width, rectangle_height = boundingRect(contour[index]) # draw contour mask = drawContours(applyMask, contour, index, (255, 255, 2555), cv2.FILLED) # find non-zero pixels ratio r = float(countNonZero(applyMask)) / (rectangle_width * rectangle_height) if r &gt; 0.5 and rectangle_height &gt; 8 and rectangle_width &gt; 8: rec_img = rectangle(adjusted, (x, y+rectangle_height), (x+rectangle_width, y), (0, 255, 0), 3) text = pytesseract.image_to_string(Image.fromarray(rec_img)) print(text) And here's the image I am trying to extract from:
downvote count: 0
has answer: http://stackoverflow.com/a/52334074
favorite count: 0
has answer: http://stackoverflow.com/a/59701886
tagged with: python
answer count: 4
tagged with: ocr
linked to: http://stackoverflow.com/q/7838487
score: 2
upvote count: 2
has title: Reading OCR text from a dot matrix display image with Python and OpenCV
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/75741680
type: Question
tagged with: opencv

http://stackoverflow.com/comment/92080353
type: Comment
comment on: http://stackoverflow.com/q/52397069
score: 0
type: QuestionComment
has text: I started running into that same problem today.. with notebooks that worked until a few days ago. I didn't upgrade any conda packages.. hmm..

http://stackoverflow.com/q/52350011
has comment: http://stackoverflow.com/comment/91645768
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91645382
score: 1
upvote count: 3
downvote count: 2
linked to: http://stackoverflow.com/q/40676085
type: Question
accepted answer: http://stackoverflow.com/a/52350026
has body: Basically my title is the question: Example: &gt;&gt;&gt; l=[1,2,3] &gt;&gt;&gt; *l SyntaxError: can't use starred expression here &gt;&gt;&gt; print(*l) 1 2 3 &gt;&gt;&gt; Why is that???
tagged with: printing
answer count: 2
has answer: http://stackoverflow.com/a/52350527
has title: Why python shell only allows `print` to output unpacked - python
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52350026
possible better answer: http://stackoverflow.com/a/52350527
tagged with: python

http://stackoverflow.com/a/52390893
has comment: http://stackoverflow.com/comment/91727124
score: 1
has comment: http://stackoverflow.com/comment/91726942
has comment: http://stackoverflow.com/comment/91726962
downvote count: 0
has comment: http://stackoverflow.com/comment/91727364
answers question: http://stackoverflow.com/q/52389801
has comment: http://stackoverflow.com/comment/91727229
has comment: http://stackoverflow.com/comment/91727260
type: Answer
has comment: http://stackoverflow.com/comment/91726983
has body: There is a built in .count method that works well for this c = [] for item in (b): num = a.count(b) item.append(num) c.append(item) print(c) (xenial)vash@localhost:~/python/stack_overflow$ python3.7 nest_list.py [['a', 1, 'A', 0], ['a', 2, 'A', 0], ['b', 1, 'B', 0]]
has comment: http://stackoverflow.com/comment/91727026
upvote count: 1
has comment: http://stackoverflow.com/comment/91727406
has comment: http://stackoverflow.com/comment/91727085

http://stackoverflow.com/comment/91544983
type: Comment
has text: Just out of curiosity how does this check for length 2 instead of just checking the first two character of the string...
comment on: http://stackoverflow.com/a/52298448
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91541489
has text: `plucked = df['two']` or possibly even `plucked = df['two'].tolist()` ?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52296757
type: Comment

http://stackoverflow.com/q/52325230
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52325273
downvote count: 0
accepted answer: http://stackoverflow.com/a/52325273
tagged with: pandas
answer count: 1
favorite count: 0
has body: What is a better way to create the same column mentioned below: col_new = [] for r1 in df['col_A']: if r1==1: for r2 in df['col_B']: if r2!='None': col_new.append('col_new') df['col_new'] = col_new My dataframe is huge (120k * 22) and running the above code is hanging the notebook. Is there a faster and more efficient way to create this column where it represents all the non-null values of col_B when col_A is 1.
linked to: http://stackoverflow.com/q/19473185
tagged with: python
has comment: http://stackoverflow.com/comment/91597418
type: AnsweredQuestion
score: 1
has title: Better way to create a new column based on values of other columns

http://stackoverflow.com/comment/91681542
has text: OH MY GOD! Is the @ operator new?! I thought the only way to perform dot product was np.array.dot or np.dot which are both terribly ugly! (must have read it on a book that these where the only two alternatives)
comment on: http://stackoverflow.com/a/52368287
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91652483
type: Comment
has text: Yeah. I know that ascending=False will give me values in descending order, but I wanted to know how to get the output given in this answer in descending order.
comment on: http://stackoverflow.com/a/52324776
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91546193
has text: This is a very clever solution
comment on: http://stackoverflow.com/a/52298826
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/91611411
comment on: http://stackoverflow.com/q/52332258
type: QuestionComment
has text: so you want all the student information which matches at least one interest of a tutor?
type: Comment
score: 0

http://stackoverflow.com/comment/91591225
has text: This should work. If I get rid of the extension and first part of the path leaving me only the name. Thanks!
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52313172

http://stackoverflow.com/comment/91726350
type: QuestionComment
comment on: http://stackoverflow.com/q/52389183
type: Comment
score: 1
has text: The relevant section on testing user input and the database can be found here: https://www.obeythetestinggoat.com/book/chapter_post_and_database.html

http://stackoverflow.com/comment/91814964
type: Comment
has text: this is precisely what I was looking for. You deserve more than just a check mark... Thank you sir! =)
comment on: http://stackoverflow.com/a/52427897
type: AnswerComment
score: 0

vertica
tag name: vertica
type: Tag
tags question: http://stackoverflow.com/q/52400010

http://stackoverflow.com/q/52373167
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91696797
has comment: http://stackoverflow.com/comment/91725526
score: 1
tagged with: scipy
tagged with: numpy
upvote count: 1
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91802319
tagged with: spline
has title: How to define a higher-degree spline using python?
favorite count: 0
has body: I am using the Scipy CubicSpline interpolation based on a certain number of points as shown in the diagram below: My problem is, the second derivative of the Cubic Splive function looks a little bit edgy: In order to smooth the second curve I need a higher degree of spline interpolation. Is there a Scipy build in function (similar to CubicSpline) or an easy way to do that? (A b-spline function want work)
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52398743
accepted answer: http://stackoverflow.com/a/52398743
type: Question

http://stackoverflow.com/a/52430102
answers question: http://stackoverflow.com/q/52429910
score: 0
has body: You can use Pytesser or Tesseract as your OCR. Try to Google "OCR - Python" and you will find many Python - OCR libraries or programs that can achieve what you want. Here's an example using pytesser: from PIL import Image from pytesser import * temp_img = Image.open('your_image.jpg') your_digit = image_to_string(temp_img) print your_digit
type: Answer

http://stackoverflow.com/comment/92324283
has text: Oh, but that's because you supposed to have consecutive evals over the training period. Play a bit around with the `tf.estimator.EvalSpec()` arguments, especially `start_delay_secs`, `throttle_secs` and `steps`. Read more about it here: https://www.tensorflow.org/api_docs/python/tf/estimator/EvalSpec
score: 1
comment on: http://stackoverflow.com/q/52428553
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52299048
has comment: http://stackoverflow.com/comment/91545862
answer count: 1
favorite count: 0
score: -3
tagged with: python
accepted answer: http://stackoverflow.com/a/52302755
type: AnsweredQuestion
tagged with: matplotlib
downvote count: 3
has title: plotting contours from a three column array
has body: I have a three column array, contains two parameters which are the x and y axes, and the Chi-square of these two parameters. I should make a meshgrid of these two parameters and then plot 1-sigma, 2-sigma, and 3-sigma contours, considering the Chi-square values. How can I do it in matplotlib? Here is my code: x (which is the second column in the "1.txt" file) and y (which is the third column) should be arranged from min to max, in order to make x and y axes, I thought it can be done using meshgrid. And z (the first column in the "1.txt" file) is the Chi-square. import numpy as np import matplotlib.pyplot as plt from matplotlib.mlab import griddata x = np.genfromtxt('1.txt', usecols=(1)) y = np.genfromtxt('1.txt', usecols=(2)) z = np.genfromtxt('1.txt', usecols=(0)) plt.figure() X, Y = np.meshgrid(x,y) Z= griddata(x,y,z,X,Y) contour=plt.contour(X,Y,Z) plt.show() this code confront with the error: "RuntimeError: To use interp='nn' (Natural Neighbor interpolation) in griddata, natgrid must be installed. Either install it from http://github.com/matplotlib/natgrid or use interp='linear' instead." When I use interp='linear', running the code would last a long time without any result. Is there any way to solve this problem?
type: Question
tagged with: contour
upvote count: 0
has answer: http://stackoverflow.com/a/52302755

http://stackoverflow.com/comment/91503554
type: QuestionComment
score: 1
has text: What is reverse instance ?
type: Comment
comment on: http://stackoverflow.com/q/52277772

http://stackoverflow.com/comment/91619559
comment on: http://stackoverflow.com/a/52332478
type: Comment
score: 1
has text: Knowing the key might still not be enough, e.g. `x = a[key] + b[key]`.
type: AnswerComment

http://stackoverflow.com/a/52320250
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91588767
type: Answer
has comment: http://stackoverflow.com/comment/91588950
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52320080
answers question: http://stackoverflow.com/q/52320080
score: 1
has body: I think that there are some problems with this code: You seem to make use of an __equal field lookup, but this lookup does not exists in the list of standard field lookups [Django-doc], the closest is __exact, but it is probably not necessary here; you use a "blanket exception" (!), this is a severe anti-pattern: if something fails, then you will never get informed about that. Like the Zen of Python says: never pass exceptions silently, unless silenced explicitly. A post-delete means that the delete already took place, hence at that moment, the instance is no longer in the database, as is specified in the documentation: Note that the object will no longer be in the database, so be very careful what you do with this instance. The last item thus means that you probably want to check if the count is zero (hence that no Order with that user_id exists anymore): @receiver(post_save, sender=Orders) def delete_reverse(sender, instance, **kwargs): if not Order.objects.filter(user_id=instance.user_id).exists(): instance.user.delete() Note however that even by doing this, there are still scenario's where the database can contain Users without any Orders: for example when we change the user_id of an Order, then it is possible that the previous user no longer has anymore, but this function will not get triggered. So it might be worth to periodically check the database for such cases. Furthermore I do not know if removing the User is a good idea anyway. If this is the authentication model in Django it can result in the fact that the admin user is removed if for example by accident an order was put on their name and that order is removed later. Furthermore removing a user can result in a large cascade of removals (of all kinds of "entities" in which that user is involved). Note: a Django model normally has a singular name, so I adivce, like I did in the answer, to rename the Orders model to Order.

http://stackoverflow.com/comment/91758555
has text: @Jason In looking for why, I found another question here that goes into more detail, so you should check that out as well.
comment on: http://stackoverflow.com/a/52407430
type: AnswerComment
score: 0
type: Comment

sdk
tags question: http://stackoverflow.com/q/52292879
tags question: http://stackoverflow.com/q/52328493
tag name: sdk
type: Tag

http://stackoverflow.com/q/52338156
upvote count: 1
tagged with: scrapy
answer count: 1
has comment: http://stackoverflow.com/comment/91623756
has body: I have this HTML code: &gt; &lt;div class="predictions"&gt; &lt;div class = "competition" id = "07675"&gt; &lt;div '&gt;, &lt;div &gt; class = "competition"&gt; &lt;div class = "hea"&gt; &lt;div class = "competition" &gt; &lt;div class = "hea '&gt;, &lt;div class =" competition "&gt; &lt;div class =" &gt; class = "competition" id = "07560"&gt; &lt;div '&gt;, I'm trying to read the tag id from the html. I´m using the code below, but it does not work. response.css ('.//div[@class = "predictions"]/div[id] :: attr (id)')
has comment: http://stackoverflow.com/comment/91623973
has answer: http://stackoverflow.com/a/52338282
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91623642
downvote count: 0
score: 1
has title: How to read div id
favorite count: 0
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/52338282

http://stackoverflow.com/a/52381550
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52381397
answers question: http://stackoverflow.com/q/52381397
score: 1
has body: First of all you need to take the values into respective arrays by spitting lines in file then pass them to the function. content = ['2.449,14.651,-0.992,', '6.833,13.875,-1.021,', '8.133,17.431,-1.150,', '3.039,13.724,-0.999,', '16.835,9.456,-1.031,', '16.835,9.457,-1.031,', '15.388,5.893,-0.868,', '13.743,25.743,-1.394,', '14.691,24.988,-1.387,', '15.801,25.161,-1.463,', '14.668,23.056,-1.382,', '22.378,20.268,-1.457,', '21.121,17.041,-1.353,', '19.472,13.555,-1.192,', '22.498,20.115,-1.436,', '13.344,-33.672,-0.282,', '13.329,-33.835,-0.279,', '13.147,-30.690,-0.305,', '13.097,-28.407,-0.339,', '13.251,-28.643,-0.366,', '13.527,-25.067,-0.481,', '19.433,-33.137,-0.408,', '19.445,-29.501,-0.345,', '20.592,-28.004,-0.312,', '19.109,-26.512,-0.380,', '18.521,-24.155,-0.519,', '22.837,48.245,-2.201,', '23.269,50.129,-2.282,', '23.499,46.652,-2.297,', '23.814,48.646,-2.271,', '30.377,46.501,-2.214,', '29.869,44.479,-2.143,', '29.597,41.257,-2.018,', '28.134,40.291,-2.159,', '-40.932,-0.320,-1.390,', '-36.808,0.442,-1.382,', '-30.831,0.548,-1.288,', '-29.404,1.235,-1.300,', '-26.453,1.424,-1.261,', '-30.559,2.775,-1.249,', '-27.714,3.439,-1.201,'] import numpy as np import matplotlib.pyplot as plt #with open("measurements.txt") as f: #content = f.read().splitlines() #print content #for value in content: # x, y, z = value.split(',') x = [float(i.split(',')[0]) for i in content] y = [float(i.split(',')[1]) for i in content] z = [float(i.split(',')[2]) for i in content] #print(x, y, z) fig = plt.figure() ax = plt.axes(projection='3d') ax.scatter(x, y, z) fig.savefig('scatterplot.png') output
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91550829
comment on: http://stackoverflow.com/a/52301474
score: 2
type: AnswerComment
type: Comment
has text: That should work, but probably more appropriate to use either of the `os.path.isfile` or `os.path.isdir` functions: https://docs.python.org/3.6/library/os.path.html

http://stackoverflow.com/q/52328004
has comment: http://stackoverflow.com/comment/91626725
score: 0
answer count: 1
tagged with: vnc-server
type: UnansweredQuestion
tagged with: encryption
has body: I am trying to connect with a VNC server (Vino) using VNC authentication. Reading the RFC 6143 - The Remote Framebuffer Protocol, we can see how VNC authentication works. It is using a challenge-response protocol where the server sends a challenge of 16 bytes and the client answer with the challenge encrypted with his key. The encryption is using DES algorithm. Using TigerVNC and Wireshark I have sniffed this process in order to do this process with Python. E.g. This is the traffic which I have sniffed with Wireshark between Vino and TigerVNC. It works. Server Client |------------------ Server protocol version: 003.007 -----------------&gt;| |&lt;----------------- Client protocol version: 003.007 --------------| |------------------ Security types: 2 ---------------------&gt;| |&lt;----------------- Security type selected: VNC (2) ------------------| |------------------- Authentication result: OK ---------&gt;| |----- Authentication challenge: b4a7257a443426527dd9d987fa6b099f -----&gt;| |&lt;---- Authentication response: 4838c102d8cbb1decd38ecdbec533bc7 ------| The challenge and response are bytes, not hex strings. But when I encrypt the authentication challenge with Python, I got different results. I have tryed using differents block cipher mode of operations, without success. E.g. &gt;&gt;&gt; from pydes import des &gt;&gt;&gt; challenge = "\xb4\xa7\x25\x7a\x44\x34\x26\x52\x7d\xd9\xd9\x87\xfa\x6b\x09\x9f" &gt;&gt;&gt; key = "testingg" &gt;&gt;&gt; d = des() &gt;&gt;&gt; ciphered = d.encrypt(key,challenge,padding=True) &gt;&gt;&gt; import binascii &gt;&gt;&gt; ciphered = d.encrypt(key,challenge) &gt;&gt;&gt; binascii.hexlify(ciphered) '4f16bc072bf34903e753b3f968b1aa56' Or with another Python module: &gt;&gt;&gt; import pyDes &gt;&gt;&gt; des = pyDes.des("testingg") &gt;&gt;&gt; challenge = "\xb4\xa7\x25\x7a\x44\x34\x26\x52\x7d\xd9\xd9\x87\xfa\x6b\x09\x9f" &gt;&gt;&gt; e = des.encrypt(challenge) &gt;&gt;&gt; binascii.hexlify(e) '4f16bc072bf34903e753b3f968b1aa56' &gt;…
tagged with: python
has title: DES algorithm in VNC authentication with Python
has comment: http://stackoverflow.com/comment/91609390
has answer: http://stackoverflow.com/a/77422746
type: Question
tagged with: vnc
tagged with: des

ubuntu
tags question: http://stackoverflow.com/q/52282175
tags question: http://stackoverflow.com/q/52272285
tags question: http://stackoverflow.com/q/52369398
tags question: http://stackoverflow.com/q/52306134
tags question: http://stackoverflow.com/q/52353483
tags question: http://stackoverflow.com/q/52318845
tags question: http://stackoverflow.com/q/52422629
tags question: http://stackoverflow.com/q/52294071
tags question: http://stackoverflow.com/q/52338103
tags question: http://stackoverflow.com/q/52396300
tags question: http://stackoverflow.com/q/52375305
tags question: http://stackoverflow.com/q/52310217
tag name: ubuntu
tags question: http://stackoverflow.com/q/52429743
tags question: http://stackoverflow.com/q/52327864
tags question: http://stackoverflow.com/q/52303085
tags question: http://stackoverflow.com/q/52349807
tags question: http://stackoverflow.com/q/52358107
type: Tag
tags question: http://stackoverflow.com/q/52288382
tags question: http://stackoverflow.com/q/52304492

http://stackoverflow.com/comment/91771580
has text: You can't multiply a string by a float. What would `"abc" * 1.5` mean?
comment on: http://stackoverflow.com/q/52413906
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/52273546
upvote count: 45
downvote count: 0
duplicate of: http://stackoverflow.com/q/44598708
tagged with: typeerror
score: 45
answer count: 1
has body: I am trying to make a simple box plot of a variable 'x' contained in two dataframes, df1 and df2. To do this I am using the following code: fig, axs = plt.subplots() axs[0, 0].boxplot([df1['x'], df2['x']]) plt.show(); However, I get this: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-108-ce962754d553&gt; in &lt;module&gt;() ----&gt; 2 axs[0, 0].boxplot([df1['x'], df2['x']]) 3 plt.show(); 4 TypeError: 'AxesSubplot' object is not subscriptable Any ideas?
favorite count: 0
has title: Matplotlib: TypeError: 'AxesSubplot' object is not subscriptable
has answer: http://stackoverflow.com/a/52273900
tagged with: python
type: AnsweredQuestion
tagged with: matplotlib
type: Question
accepted answer: http://stackoverflow.com/a/52273900
linked to: http://stackoverflow.com/q/44598708

http://stackoverflow.com/comment/91673231
type: AnswerComment
score: 0
type: Comment
has text: I have just one more question. I want to display that the user's choices in my project details page. How can I do it in my HTML page?
comment on: http://stackoverflow.com/a/52363562

http://stackoverflow.com/a/52285732
score: 0
has comment: http://stackoverflow.com/comment/91520002
accepted answer of: http://stackoverflow.com/q/52285705
type: Answer
has body: To add for example the constant 1 to all the values: df = pd.read_csv('filename.csv') cols = [1,2,3,4,5,6,7] df[cols] = df[cols].add(1) Change 1 in add(1) to whatever constant you want. If you want to save your updated dataframe, use: df.to_csv('filename_edited.csv')
answers question: http://stackoverflow.com/q/52285705
has comment: http://stackoverflow.com/comment/91520527
has comment: http://stackoverflow.com/comment/91520570
has comment: http://stackoverflow.com/comment/91520781
has comment: http://stackoverflow.com/comment/91520617
has comment: http://stackoverflow.com/comment/91520627
has comment: http://stackoverflow.com/comment/91519931
has comment: http://stackoverflow.com/comment/91520660
has comment: http://stackoverflow.com/comment/91520300
type: AcceptedAnswer

http://stackoverflow.com/q/52415754
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52415803
type: Question
has title: Ignore A Row When Reading CSV In Pandas
has body: Having problems when performing calculations in a Pandas dataframe... Here's a sample CSV (see picture): My problem is that since it reads the row in italics e.g. Data Type (row 2), it treats all values as strings instead of their correct data type i.e. float, degrees, etc. Is there a way I can get it to ignore this row when reading the CSV e.g. df = pd.read_CSV('sample CSV', ignore row 2) That way it will read in like this (see other picture) and assume correct data types:
has answer: http://stackoverflow.com/a/52415815
score: 0
answer count: 3
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/52415816

http://stackoverflow.com/comment/91570831
score: 0
type: QuestionComment
type: Comment
has text: Fair enough. All the same, always post an attempted solution when you ask this sort of thing. It shows that you've at least spent the effort that you're demanding of others yourself on the problem.
comment on: http://stackoverflow.com/q/52311560

http://stackoverflow.com/q/52277725
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52280428
tagged with: python
type: AnsweredQuestion
tagged with: snakemake
has body: I have a simple Snakefile and I have a rule that use Conda enviroment defined in YAML configuration file. However, when running this Snakefile, Snakemake does not activate the Conda enviroment and returns this error: Error in rule read_file: jobid: 0 conda-env: /data/projects/testproject/.snakemake/conda/805d8d2a RuleException: CalledProcessError in line 5 of /data/projects/testproject/scripts/snake/process.snake: Command 'source activate /data/projects/testproject/.snakemake/conda/805d8d2a; set -euo pipefail; emirge ' returned non-zero exit status 2 File "/data/projects/testproject/scripts/snake/process.snake", line 5, in __rule_read_file File "/usr/lib/python3.5/concurrent/futures/thread.py", line 55, in run Shutting down, this might take some time. Exiting because a job execution failed. Look above for error message I tried to activate Conda enviroment (the one created by SnakeMake) manually by using both source activate 805d8d2a and conda activate 805d8d2a with no success (error message implies that there is no enviroment with said name, however, conda info --envs lists it as existing). To further test Conda functionality, I have manually created a Conda enviroment and was able to activate it with the latter command (command source activate testenv does not work). My question is: How can I manage to automatically activate Conda enviroment from my SnakeMake script? Conda version: 4.5.11 SnakeMake version: 5.2.4 Snakefile: rule my_rule: conda: "emirge.yaml" shell: "emirge" Emirge.yaml: channels: - bioconda dependencies: - emirge=0.61.1 Edit: I am running Snakemake with command: snakemake --use-conda
type: Question
accepted answer: http://stackoverflow.com/a/52280428
has title: SnakeMake does not activate conda enviroment
tagged with: conda

http://stackoverflow.com/comment/91506002
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52278988
type: AnswerComment
has text: @jpp edited it, thanks!

http://stackoverflow.com/comment/91758925
score: 0
type: AnswerComment
type: Comment
has text: It works like that, but for some reason is stating that the password is incorrect, when it shouldn't be, as the password is "admins".
comment on: http://stackoverflow.com/a/52406932

http://stackoverflow.com/comment/91714501
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52385242
has text: There are multiple ways of doing this. My preferred way would be using pandas dataframe.
score: 0

http://stackoverflow.com/comment/95459465
type: Comment
score: 1
has text: thanks - that actually works very well. For a year's worth of dates, it runs about 10x faster than checking .isoweekday()
type: AnswerComment
comment on: http://stackoverflow.com/a/54264187

http://stackoverflow.com/q/52416314
downvote count: 0
score: 1
type: Question
has answer: http://stackoverflow.com/a/52416331
accepted answer: http://stackoverflow.com/a/52416331
has body: In Oracle, I can use merge into to select rows from one or more sources for update , like this: merge into table_A A using table_B B on A.id = B.id when matched then update set A.name = B.name Is there a way to get the same result using Pandas DataFrame?
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has title: How to rewrite Oracle merge into in Pandas?

http://stackoverflow.com/comment/91779834
has text: That's probably because you have visited the page before. When I click it it takes me to a web page. You should simulate the same behaviour using requests. Scraping is hard.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52417686

http://stackoverflow.com/q/52309407
has comment: http://stackoverflow.com/comment/91607425
tagged with: python
favorite count: 0
has title: Python 'corrupts' downloaded pdf file
score: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/91566712
type: UnansweredQuestion
tagged with: wikipedia
tagged with: python-requests
type: Question
has body: I am writing a program to automatically download a Wikipedia page as pdf, using their embedded tool. I was able to fix a problem where I wasn't able to retrieve the data from a submit button. The new problem is, that I can download the file (I used open() and also urllib.request.urlretrieve(), but I'm not able to open it manually then. It seems like the file is being corrupted while being downloaded (I think it's an encoding failure). This disables opening the PDF.. (unsupported datatype or corrupted file= This is the code I use: import requests import urllib.request base_url = 'https://de.wikipedia.org/wiki/' def createURL(base): title = 'Rektifikation (Verfahrenstechnik)' name = title.replace(" ", "_") url = (base + name).replace('(', '%28').replace(')', '%29') print(url) getPDF(url, title) def getPDF(url, title): r = requests.get(url, allow_redirects=True) open('{}.pdf'.format(title), 'wb').write(r.content) urllib.request.urlretrieve('https://de.wikipedia.org/w/index.php?title=Spezial:ElectronPdf&amp;page=Rektifikation+%28Verfahrenstechnik%29&amp;action=show-download-screen)', '{}_vl.pdf'.format(title)) createURL(base_url) I hardcoded most of the stuff for debugging reasons. Feel free to help me improve the code, but note that this isn't my main purpose, please. My question now is: What could I possibly do to stop the file from getting corrupted (encode it the right way) This is the link (click the button) I'm trying to download from. Note: It's an instant download link with a redirect. Thanks for your help, if you need any more information just ask me. EDIT: Opening the PDF via Word lets me see, that the data (texts, paragraphs..) is available. So the PDF contains the data and the download itself seems to be successful. The sizes of the downloaded files differ, maybe someone can have a look at this problem too: open: 58KB urllib: 18KB manually: 239KB
has comment: http://stackoverflow.com/comment/91566523
tagged with: urllib
upvote count: 2
tagged with: encoding

http://stackoverflow.com/q/52374356
has answer: http://stackoverflow.com/a/52399943
has body: Cartopy can't draw virtually anything. Even a simple example results in a segfault. Segmentation fault is all Python 3.7.0 says before crashing. So does Python 3.6.6. The faulty line appear to be ax.coastlines(). ax.gridlines() gives the same silent segfault as well. matplotlib is 2.2.3. Cartopy is the most recent by the date, 0.16.0, installed with pip. All the requirements (six, pyshp, setuptools, shapely, numpy) are met. Reinstalling with pip doesn't help. Installing the same Cartopy version from repo doesn't help either. The OS is Debian 10 (beta). The same outcome is with Cartopy 0.15.1. What else can I check to find the cause of the segfault? Just in case, matplotlib.rcParams are the following: _internal.classic_mode: False agg.path.chunksize: 0 animation.avconv_args: [] animation.avconv_path: avconv animation.bitrate: -1 animation.codec: h264 animation.convert_args: [] animation.convert_path: convert animation.embed_limit: 20.0 animation.ffmpeg_args: [] animation.ffmpeg_path: ffmpeg animation.frame_format: png animation.html: none animation.html_args: [] animation.writer: ffmpeg axes.autolimit_mode: data axes.axisbelow: line axes.edgecolor: k axes.facecolor: w axes.formatter.limits: [-7, 7] axes.formatter.min_exponent: 0 axes.formatter.offset_threshold: 4 axes.formatter.use_locale: False axes.formatter.use_mathtext: False axes.formatter.useoffset: True axes.grid: False axes.grid.axis: both axes.grid.which: major axes.hold: None axes.labelcolor: k axes.labelpad: 4.0 axes.labelsize: medium axes.labelweight: normal axes.linewidth: 0.8 axes.prop_cycle: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']) axes.spines.bottom: True axes.spines.left: True axes.spines.right: True axes.spines.top: True axes.titlepad: 6.0 axes.titlesize: large axes.titleweight: normal axes.unicode_minus: True axes.xmargin: 0.05 axes.ymargin: 0.05 axes3d.grid: True backend: TkAgg backend.qt4: None backend.qt5: Non…
accepted answer: http://stackoverflow.com/a/52399943
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
type: Question
score: 14
tagged with: cartopy
tagged with: python-3.6
upvote count: 14
tagged with: python-3.7
has title: Cartopy examples produce a Segmentation fault
answer count: 1

http://stackoverflow.com/comment/91688607
comment on: http://stackoverflow.com/q/52371865
type: QuestionComment
has text: I mean if the same code occurs in different folders I do not account it as a duplicate. Only if a code occurs at least two or more times in the same folder I consider it as a duplicate.
score: 0
type: Comment

http://stackoverflow.com/a/52344064
score: 0
answers question: http://stackoverflow.com/q/52330472
type: Answer
has body: I'm not sure that it will be faster because the way videos formats (mp4, flv, etc.) zipped. As I understand it the algorithms should first unzip it (full frame) and then only crop it, but maybe I'm wrong. Anyway have a look on crop function of ffmpeg. You can find ffmpeg-python library: https://pypi.org/project/ffmpeg-python/ https://github.com/kkroening/ffmpeg-python Waiting to hear if it's helpful.

http://stackoverflow.com/comment/91641757
has text: Plus, you have too much units in the first Dense layer. It is highly prone to overfitting. Reduce it to something like 1000 or even lower. Further, don't forget to pass the `input_dim=10000` argument to the first Dense layer. It means each training sample is a vector of length 10000.
score: 0
comment on: http://stackoverflow.com/q/52347906
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52358241
type: Question
has comment: http://stackoverflow.com/comment/91662388
has comment: http://stackoverflow.com/comment/91662319
has answer: http://stackoverflow.com/a/52358325
tagged with: deep-learning
downvote count: 0
answer count: 1
tagged with: keras
favorite count: 0
has title: keras argmax has none for gradients. How to define gradient for argmax?
has comment: http://stackoverflow.com/comment/91662270
type: UnansweredQuestion
has body: I am using Keras.Backend.armax() in a gamma layer. The model compiles fine but throws an error during fit(). ValueError: An operation has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval. My model: latent_dim = 512 encoder_inputs = Input(shape=(train_data.shape[1],)) encoder_dense = Dense(vocabulary, activation='softmax') encoder_outputs = Embedding(vocabulary, latent_dim)(encoder_inputs) encoder_outputs = LSTM(latent_dim, return_sequences=True)(encoder_outputs) encoder_outputs = Dropout(0.5)(encoder_outputs) encoder_outputs = encoder_dense(encoder_outputs) encoder_outputs = Lambda(K.argmax, arguments={'axis':-1})(encoder_outputs) encoder_outputs = Lambda(K.cast, arguments={'dtype':'float32'})(encoder_outputs) encoder_dense1 = Dense(train_label.shape[1], activation='softmax') decoder_embedding = Embedding(vocabulary, latent_dim) decoder_lstm1 = LSTM(latent_dim, return_sequences=True) decoder_lstm2 = LSTM(latent_dim, return_sequences=True) decoder_dense2 = Dense(vocabulary, activation='softmax') decoder_outputs = encoder_dense1(encoder_outputs) decoder_outputs = decoder_embedding(decoder_outputs) decoder_outputs = decoder_lstm1(decoder_outputs) decoder_outputs = decoder_lstm2(decoder_outputs) decoder_outputs = Dropout(0.5)(decoder_outputs) decoder_outputs = decoder_dense2(decoder_outputs) model = Model(encoder_inputs, decoder_outputs) model.summary() Model summary for easy visualizing: _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_7 (InputLayer) (None, 32) 0 _________________________________________________________________ embedding_13 (Embedding) (None, 32, 512) 2018816 _________________________________________________________________ lstm_19 (LSTM) (None, 32, 512) 2099200 ________________________________________________________…
tagged with: python
has comment: http://stackoverflow.com/comment/91662497
tagged with: nlp
score: 1
has comment: http://stackoverflow.com/comment/91662349
upvote count: 1
linked to: http://stackoverflow.com/q/45123263
tagged with: tensorflow

http://stackoverflow.com/comment/91670360
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52362742
has text: I looked at some of this Babylonian methods but they confuse me so i was trying to find an alternative

http://stackoverflow.com/comment/91530375
type: Comment
type: QuestionComment
score: 0
has text: You're right ! I will edit my title and could you post the answer ? I will validate it ;)
comment on: http://stackoverflow.com/q/52291141

http://stackoverflow.com/comment/91546871
type: QuestionComment
has text: Please take a look at [Correlated Subquery Relationship Hybrid](http://docs.sqlalchemy.org/en/latest/orm/extensions/hybrid.html#correlated-subquery-relationship-hybrid) of the official documentation. Create a hybrid property (with the `.expression` version) from the example, replacing `sum` with `max` and adding `order_by(...)`. Then you can query both: `q = session.query(User, User.latest_report_date)` and `q` will return tuples of form `(User, date)`
score: 1
comment on: http://stackoverflow.com/q/52274882
type: Comment

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/52344871
tags question: http://stackoverflow.com/q/52304263
tag name: kivy-language

http://stackoverflow.com/comment/91595646
type: QuestionComment
has text: Without judging: Using `&` in `bash` just means "run in background". The default behavior for `subprocess.Popen` is to run the process in the background, so `subprocess.Popen(['some_command'])` should behave the same, except with fewer layers of processes, and without losing the connection between Python and `some_command` (the connection having been lost because `bash` exits and orphans `some_command`; you're seeing `bash`'s exit code).
type: Comment
comment on: http://stackoverflow.com/q/52324228
score: 2

http://stackoverflow.com/a/52324643
answers question: http://stackoverflow.com/q/52324464
has body: Vamsi, I noticed you are using numpy and pandas. While, I'm working on debugging I did want to recommend one more awesome package, sci-kit learn. They have an implementation of KNN already built in: http://scikit-learn.org/stable/modules/neighbors.html EDIT: I beleive there is a casting issue on line 26. It appears you are trying to subtract 2 strings. I think this may solve your issue if yout are working with integer data def euclideanDistance(instance1, instance2, length): distance = 0 for x in range(length): distance += pow((int(instance1[x]) - int(instance2[x])), 2) return math.sqrt(distance) If you are working with floating point data than the following would work: distance += pow((float(instance1[x]) - float(instance2[x])), 2)
score: 0
has comment: http://stackoverflow.com/comment/91596312
type: Answer

http://stackoverflow.com/comment/91641475
comment on: http://stackoverflow.com/q/52344305
score: 0
type: QuestionComment
type: Comment
has text: When passing the url with the encoded data to the "parse_qs" method (%E7%E9%F4%E4 for that matter) I get a dictionary like you said but with '����' as value for the decoded info. The number of these question marks is the correct number of of letters that the hebrew name would have. But still not the actual hebrew name. If I use the library output on the other hand - %D7%97%D7%99%D7%A4%D7%94, I get the right name (חיפה)

http://stackoverflow.com/comment/91574016
has text: ok just wait a moment .
comment on: http://stackoverflow.com/q/52313457
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52358608
has comment: http://stackoverflow.com/comment/91661710
linked to: http://stackoverflow.com/q/7961363
has title: Python List Comprehensions: Create list b from list a, excluding repeats
has comment: http://stackoverflow.com/comment/91661672
duplicate of: http://stackoverflow.com/q/7961363
tagged with: python
has answer: http://stackoverflow.com/a/52358622
score: 0
has body: I'm trying to solve this problem using list comprehensions. I want to take the list: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and create a new list b containing all the numbers from a that are below 5, excluding repeats. I can do this using a for loop: b = list() for i in a: if i &lt; 5 and i not in b: b.append(i) which gives me [1, 2, 3], but when I try this using a list comprehension: b = list() b = [i for i in a if i not in b and i &lt; 5] I get a list with repeated values: [1, 1, 2, 3] Is there a way to exclude repeated values when using list comprehensions?
accepted answer: http://stackoverflow.com/a/52358622
has answer: http://stackoverflow.com/a/52358658
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52358658
tagged with: list-comprehension
duplicate of: http://stackoverflow.com/q/480214
answer count: 2

http://stackoverflow.com/q/52409306
accepted answer: http://stackoverflow.com/a/52410207
has title: pandas.DataFrame.plot() not showing x axis after update
answer count: 1
tagged with: matplotlib
has body: import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.style.use('seaborn-white') burndown dataframe: Forecast Actual Baseline 11422 11422 February 2018 11422 11325 March 2018 11420 10717 April 2018 11415 10272 May 2018 11393 8771 June 2018 11382 7750 July 2018 10069 6940 August 2018 6330 6038 September 2018 6153 4998 used to produce chart with x axis by calling: burndown_data.plot(figsize=(15,3),grid=True,title=title,marker='o') but after upgrading to newest pandas x axis is lost. How to fix this? When I'm trying this approach: Matplotlib:: Not Showing all x-axis data frame variable I have an error:
tagged with: pandas
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/32572419
has answer: http://stackoverflow.com/a/52410207
type: Question
tagged with: python
score: 0

http://stackoverflow.com/q/52310981
has answer: http://stackoverflow.com/a/52311123
favorite count: 0
upvote count: 1
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52311120
accepted answer: http://stackoverflow.com/a/52311087
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52311045
has comment: http://stackoverflow.com/comment/91569119
score: 1
possible better answer: http://stackoverflow.com/a/52311120
has comment: http://stackoverflow.com/comment/91569246
has body: I want to randomly pick 1000 dictionary key, value pairs whose values is 'Zero'. The dictionary keys are in alphabetic order at the moment. It has thousands of entries, below is part of it [('2014','Zero'), ('2015','Zero'), ('2016','Zero') ('2017','NotZero')] I successfully pick up 1000 'Zero' entries. Zero = [] cnt = 0 for j in range(len(DIC)): if list(DIC.values())[j] == 'Zero': Zero.append(list(DIC.items())) cnt += 1 if cnt == 1000: break But I cannot find a way to randomize them. It's bias to pick the first 1000 lines because they are in alphabetic order. Any suggestions on solving this problem? Thank you!
type: Question
has title: Pick dictionary keys:values randomly
has answer: http://stackoverflow.com/a/52311087
downvote count: 0

http://stackoverflow.com/comment/91547634
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52299913
score: 0
has text: you could use the iris dataset example to classify the roots, but not sure of measuring the lengths

http://stackoverflow.com/q/52411230
type: Question
tagged with: python-itertools
score: -1
has comment: http://stackoverflow.com/comment/91766229
has body: I want to combine a generator of generators so that when I call list() on said generator I get a list of the elements of the generators all toghether, not a list of generators. For example, I am currently doing: list(itertools.chain((i for i in range(j)) for j in range(3))) which is returning: [&lt;generator object &lt;genexpr&gt;.&lt;genexpr&gt; at 0x7fc48921e200&gt;, &lt;generator object &lt;genexpr&gt;.&lt;genexpr&gt; at 0x7fc48921eeb8&gt;, &lt;generator object &lt;genexpr&gt;.&lt;genexpr&gt; at 0x7fc48921e7d8&gt;] But i want it to return something like: [0, 0, 1, 0, 1, 2]
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91766095
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52411312
upvote count: 0
has title: How to combine generator of generators?

http://stackoverflow.com/comment/91606380
type: AnswerComment
comment on: http://stackoverflow.com/a/52329029
type: Comment
has text: Okay, I transposed the csv file I received using the link above and got the desired result. Could you now guide me how to do it in a more correct way?
score: 0

http://stackoverflow.com/a/52359718
downvote count: 0
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/52358489
upvote count: 1
has body: The trick is here to realize that what you are doing it taking successive transposes of the matrix of your cards and printing them where the size of the matrix you preform the operation on is the number of items you want to be displayed. We can get a transpose using zip in python. def display(deck, number_of_columns): col = 0 while col &lt; len(deck): temp = deck[col:col+number_of_columns] temp = zip(*temp) for x in temp: for y in x: print(y, end=" ") print() col += number_of_columns display(deck, 3) print() display(deck, 4) Output 1 5 9 2 6 10 3 7 11 4 8 12 a e i b f j c g k d h l 1 5 9 a 2 6 10 b 3 7 11 c 4 8 12 d e i f j g k h l
answers question: http://stackoverflow.com/q/52358489
type: AcceptedAnswer

http://stackoverflow.com/a/52372681
answers question: http://stackoverflow.com/q/52372636
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52372636
type: Answer
upvote count: 1
has body: You need to import redirect from django.shortcut with from django.shortcuts import redirect This is well documented in the Django's shortcut documentation.

http://stackoverflow.com/comment/91735809
has text: Thanks for your quick help!
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52392876

http://stackoverflow.com/a/52292096
has body: Send the graph_mode value in context with the associated action to the graph view, for example { 'graph_mode': 'pie' }
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52275449
accepted answer of: http://stackoverflow.com/q/52275449
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52302599
accepted answer: http://stackoverflow.com/a/52303318
favorite count: 0
tagged with: python
tagged with: kivy
type: AnsweredQuestion
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/52303318
score: 3
has title: Properly using .kv Files for Kivy and importing them to your Python script
has body: I am following tutorials for Kivy and I haven't been able to properly load properties from .kv files. For some reason, I am able to sometimes pull .kv files via a for kv in listdir(kv_path): Builder.load_file(kv_path+kv), but I can't do it by simply putting the kv files in the same root directory and letting it "import by itself?" As an example, when using the files: main.py from kivy.app import App from kivy.uix.label import Label from kivy.uix.widget import Widget class Widgets(Widget): pass class SimpleKivy3(App): def build(self): return Widgets() if __name__ == "__main__": SimpleKivy3().run() SimpleKivy3.kv &lt;Button&gt;: font_size: 40 size: 170,75 color: 0,1,0,1 &lt;Widgets&gt;: Button: pos: root.x, root.top - self.height text: "Kivy" Button: pos: 170,0 text: "Tutorials" I obtain the following output on my Terminal: $ python main.py [INFO ] [Logger ] Record log in /home/nickshu/.kivy/logs/kivy_18-09-12_58.txt [INFO ] [Kivy ] v1.11.0.dev0, git-038acbf, 20180912 [INFO ] [Python ] v3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56) [GCC 7.2.0] [INFO ] [Factory ] 195 symbols loaded [INFO ] [Image ] Providers: img_tex, img_dds, img_sdl2, img_pil, img_gif (img_ffpyplayer ignored) [INFO ] [Text ] Provider: sdl2 [INFO ] [Window ] Provider: sdl2(['window_egl_rpi'] ignored) [INFO ] [GL ] Using the "OpenGL" graphics system [INFO ] [GL ] Backend used &lt;gl&gt; [INFO ] [GL ] OpenGL version &lt;b'3.0 Mesa 18.0.5'&gt; [INFO ] [GL ] OpenGL vendor &lt;b'Intel Open Source Technology Center'&gt; [INFO ] [GL ] OpenGL renderer &lt;b'Mesa DRI Intel(R) HD Graphics P630 (Kaby Lake GT2) '&gt; [INFO ] [GL ] OpenGL parsed version: 3, 0 [INFO ] [GL ] Shading version &lt;b'1.30'&gt; [INFO ] [GL ] Texture max size &lt;16384&gt; [INFO ] [GL ] Texture max units &lt;32&gt; [INFO ] [Window ] auto add sdl2 input provider [INFO ] [Window ] virtual keyboard not allowed, single mode, not docked [INFO ] [ProbeSysfs ] device match: /dev/input/event6 [INFO ] [MTD ] Read event from &lt;/dev/inpu…
answer count: 1
downvote count: 0

http://stackoverflow.com/a/52281878
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52281784
type: Answer
score: 2
upvote count: 2
has body: This seems like a homework question, but as an example: def determine_increase(num1, num2): if num2 &gt; num1: return num2 - num1 else: return 0 Then you would call it as: salaryincrease = determine_increase(salary1, salary2) bonusincrease = determine_increase(bonus1, bonus2) benefitsincrease = determine_increase(benefits1, benefits2) This takes the logic you were performing repetitively and condenses it to one function so you only have to change it in one spot if say you wanted to make the increase a percent you would only modify one function instead of all 3 instances in your original code.
answers question: http://stackoverflow.com/q/52281784

http://stackoverflow.com/comment/91691928
comment on: http://stackoverflow.com/q/52373464
type: Comment
type: QuestionComment
has text: @FanMan seems fairly clear? For each date I'm adding, I need to copy all the row data for the last day of the previous month
score: 0

http://stackoverflow.com/comment/91551646
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52283084
has text: @Theminer Checkout my updated answer and let me know the status

http://stackoverflow.com/comment/91740331
score: 0
type: Comment
has text: https://raspberrypi.stackexchange.com/a/18223/66692
type: QuestionComment
comment on: http://stackoverflow.com/q/52397999

http://stackoverflow.com/a/52309969
accepted answer of: http://stackoverflow.com/q/52309415
answers question: http://stackoverflow.com/q/52309415
score: 7
has body: Inserting the line: ax.xaxis.set_major_locator(md.HourLocator(interval = 1)) appears to have made all the difference, as it sets the tick mark frequency. Full example below: import matplotlib.pyplot as plt import matplotlib.dates as md import pandas as pd df = pd.DataFrame({'toronto_time': ['2018-09-08 00:00:50', '2018-09-08 01:01:55', '2018-09-08 05:02:18', '2018-09-08 07:05:24', '2018-09-08 16:05:34', '2018-09-08 23:06:33'], 'description': ['STATS', 'STATS', 'DEV_OL', 'STATS', 'STATS', 'CMD_ERROR']}) df['toronto_time'] = pd.to_datetime(df['toronto_time'], format='%Y-%m-%d %H:%M:%S') fig, ax = plt.subplots(figsize=(8,6)) plt.plot('toronto_time', 'description', data=df) ax.set_xlim(df['toronto_time'].min()-pd.Timedelta(1,'h'), df['toronto_time'].max()+pd.Timedelta(1,'h')) ax.xaxis.set_major_locator(md.HourLocator(interval = 1)) ax.xaxis.set_major_formatter(md.DateFormatter('%H:%M:%S')) fig.autofmt_xdate() plt.show() I've also added the fig.autofmt_xdate() line before the plt.show() to help format the hourly frequency to prevent overlapping timestamps on the x-axis. This yields:
upvote count: 7
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/q/52331396
tagged with: python
has title: Is there a way to reflect changes on S3 quickly?
has comment: http://stackoverflow.com/comment/91610631
answer count: 0
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/91616951
has comment: http://stackoverflow.com/comment/91616843
type: Question
has body: I've been working on Django project. Recently sometimes I have a trouble updating static files on S3. The changes on S3 cannot be reflected quickly. Also the speed of reflecting the changes depends on the browser. It takes more time to reflect the changes on Chrome than Edge for me. Is there a preferable way to prevent this? I just did python manage.py collectstatic so static files can be updated. when I use Chrome, the files are still not updated even though two hours passed.
has comment: http://stackoverflow.com/comment/91614973
score: 0
has comment: http://stackoverflow.com/comment/91616918
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91614618
tagged with: django

http://stackoverflow.com/q/52413147
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91770018
possible better answer: http://stackoverflow.com/a/52413870
has comment: http://stackoverflow.com/comment/91770107
upvote count: 1
has body: I'm sure what I'm asking is simple question but have yet to figure it out. I have a panda df and I want to run this basic query on it Select a,b,c FROM TABLE WHERE (TABLE.time &gt;= x ) &amp;&amp; (TABLE.time &lt;= y) GROUP BY c so if I have a table A B time a b time1 c d time2 e f time3 I would want only to return the a,b,c where the time is greater or less than the ones in the query. Also would this query on a Dataframe give me another df if I assign the query to a variable say something like df2 = df.query() I hope this makes sense
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52413761
accepted answer: http://stackoverflow.com/a/52413761
tagged with: dataframe
has title: select rows from a query in DataFrame in Pandas
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52413870
downvote count: 0
has comment: http://stackoverflow.com/comment/91770398
favorite count: 0
tagged with: pandas
tagged with: sql

http://stackoverflow.com/q/52378519
has body: I wrote a code using tkinter to switch between frames after a few seconds. The problem is: All the application must run in fullscreen. Here is the code. from tkinter import * N_TRIALS = 3 COUNT=-2 N_INTERVALS = 2*N_TRIALS + 1 RELAXING_TIME = 2000 RESTING_TIME = 2000 TASKING_TIME = 2000 start_btn_state = False def raise_frame(frame): frame.tkraise() global COUNT COUNT+=1 print(COUNT) if (frame == f3 and COUNT==N_INTERVALS): frame.after(RESTING_TIME,lambda:raise_frame(f5)) elif(frame == f5): frame.after(RELAXING_TIME,lambda:raise_frame(f6)) elif frame == f2: frame.after(RELAXING_TIME, lambda:raise_frame(f3)) elif frame == f3: frame.after(RESTING_TIME, lambda:raise_frame(f4)) elif frame == f4: frame.after(TASKING_TIME, lambda:raise_frame(f3)) elif frame==f6: root.destroy() def finish(): root.destroy() def start(): start_btn_state=True raise_frame(f2) root = Tk() f1 = Frame(root) f2 = Frame(root) f3 = Frame(root) f4 = Frame(root) f5 = Frame(root) f6 = Frame(root) for frame in (f1, f2, f3, f4, f5,f6): frame.grid(row = 0, column = 0, sticky='nsew') lb0=Label(f1, text="blablabla",font=("Arial Bold",10)) lb0.pack(padx = 10, pady=10) lb1=Label(f1, text="blablabla",font = ("Arial Bold",10),fg = "black") lb1.pack(padx = 10, pady=10) lb2 = Label(f1, text="blablabla",font = ("Arial Bold",10),fg = "green") lb2.pack(padx = 10, pady=10) lb3 = Label(f1, text="blablabla",font = ("Arial Bold",10),fg = "blue") lb3.pack(padx = 10, pady=10) lb4 = Label(f1, text="blablabla",font = ("Arial Bold",10),fg = "red") lb4.pack(padx = 10, pady=10) start_value=BooleanVar() btn_start=Button(f1, text="Start",font = ("Arial Bold",20), command = start) btn_start.pack(padx=10,pady=30) close_value=BooleanVar() btn_close=Button(f1, text="CLOSE",font = ("Arial Bold",20), command=finish) btn_close.pack(padx=10,pady=30) Label(f2, text='ACTION 1').pack() #Button(f2, text='Go to frame 3', command=lambda:raise_frame(f1)).pack() f2.config(bg='red') Label(f3, text='ACTION2').pack(side='left') f3.config(bg='green'…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91717491
accepted answer: http://stackoverflow.com/a/52381359
type: Question
has title: Multiple frames with tkinter - How to make them run on fullscreen mode
score: 0
answer count: 1
tagged with: python
tagged with: python-3.x
tagged with: tkinter
has answer: http://stackoverflow.com/a/52381359
has comment: http://stackoverflow.com/comment/91716254

http://stackoverflow.com/q/52333573
has title: Python Pandas Dataframe perpetual cumprod
score: 0
has comment: http://stackoverflow.com/comment/91616090
tagged with: pandas
has comment: http://stackoverflow.com/comment/91625633
tagged with: python
has answer: http://stackoverflow.com/a/52336500
linked to: http://stackoverflow.com/q/8305199
type: UnansweredQuestion
type: Question
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91625957
has comment: http://stackoverflow.com/comment/91652428
has body: I have the following sample of the Dataframe (population rows 100k+): In: official delta 0 0.000201567 0 0.000194400 0 0.000151906 62.94957331 0.000144387 64.06471633 0.000125152 64.51335098 0.000133459 64.4101024 0.000120795 0 0.000146456 but receive the following output: official delta result 0 0.000201567 0 0 0.0001944 0 0 0.000151906 0 62.94957331 0.000144387 0 64.06471633 0.000125152 0 64.51335098 0.000133459 0 64.4101024 0.000120795 0 0 0.000146456 0 Desired solution: official delta result 0 0.000201567 0 0 0.0001944 0 0 0.000151906 0 62.94957331 0.000144387 62.94957331 64.06471633 0.000125152 64.06471633 64.51335098 0.000133459 64.51335098 64.4101024 0.000120795 64.4101024 0 0.000146456 63.76600137 I tried the following code although it seems that it does not work correctly. I do not understand why it gives a fault result. When I execute it in a demo dataframe, everything is fine. The code should pick up the 'official' element when mask is True otherwise multiply its previous element with 0.99 . The issue here is that when the mask is True, the code does not pick the 'official' element. mask = (df['official']&lt;51) &amp; (df['delta']&gt;0) df['result'] = df['official'].where(mask,0.99).groupby(~mask.cumsum()).cumprod()
answer count: 1

http://stackoverflow.com/comment/91710146
has text: A minimal code example of the problem you are trying to solve would be helpful.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52382503

http://stackoverflow.com/comment/91655103
score: 1
has text: `df.iloc[df.index.get_loc(20):df.index.get_loc(30)+1]` (unlike loc, iloc excludes the last element so you need to add 1).
comment on: http://stackoverflow.com/q/52355225
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91838371
type: Comment
comment on: http://stackoverflow.com/q/52303043
has text: What do you mean by "yield API requests on the fly"? And by "upload every request to a DB"? Are you trying to log every API call to your server, or trying to cache the result of you API calls to Spotify, so you don't need to call them again?
score: 0
type: QuestionComment

mysql
tags question: http://stackoverflow.com/q/52284029
tags question: http://stackoverflow.com/q/52361941
tags question: http://stackoverflow.com/q/52351833
tags question: http://stackoverflow.com/q/52274856
tags question: http://stackoverflow.com/q/52289683
tags question: http://stackoverflow.com/q/52365608
tag name: mysql
tags question: http://stackoverflow.com/q/52425073
tags question: http://stackoverflow.com/q/52328776
tags question: http://stackoverflow.com/q/52364483
tags question: http://stackoverflow.com/q/52400913
tags question: http://stackoverflow.com/q/52366891
tags question: http://stackoverflow.com/q/52336365
tags question: http://stackoverflow.com/q/52293504
tags question: http://stackoverflow.com/q/52378074
tags question: http://stackoverflow.com/q/52392959
tags question: http://stackoverflow.com/q/52421289
tags question: http://stackoverflow.com/q/52341148
type: Tag
tags question: http://stackoverflow.com/q/52399907
tags question: http://stackoverflow.com/q/52323278
tags question: http://stackoverflow.com/q/52315405
tags question: http://stackoverflow.com/q/52386964
tags question: http://stackoverflow.com/q/52308349
tags question: http://stackoverflow.com/q/52310853
tags question: http://stackoverflow.com/q/52300733
tags question: http://stackoverflow.com/q/52357407
tags question: http://stackoverflow.com/q/52340979
tags question: http://stackoverflow.com/q/52425038
tags question: http://stackoverflow.com/q/52282726
tags question: http://stackoverflow.com/q/52376424
tags question: http://stackoverflow.com/q/52355446
tags question: http://stackoverflow.com/q/52327311
tags question: http://stackoverflow.com/q/52313203
tags question: http://stackoverflow.com/q/52384084
tags question: http://stackoverflow.com/q/52380528
tags question: http://stackoverflow.com/q/52285458
tags question: http://stackoverflow.com/q/52319964
tags question: http://stackoverflow.com/q/52407890

cgi
tags question: http://stackoverflow.com/q/52373722
tags question: http://stackoverflow.com/q/52335195
type: Tag
tag name: cgi

http://stackoverflow.com/q/52395579
has answer: http://stackoverflow.com/a/52395721
score: 0
tagged with: matrix
answer count: 1
tagged with: readfile
type: UnansweredQuestion
tagged with: python
has title: Trying to read a txt file of multiple matrices and store as multiple arrays
has comment: http://stackoverflow.com/comment/91736384
type: Question
tagged with: arrays
has body: I am trying to take a .txt file which holds multiple matrices, and then store each matrix as an array. I am starting with just 2, and can work my way up from there. I have a feeling there is just a tiny thing wrong with my logic but I can't seem to get it right to sort the 2 arrays separately. If anyone has any suggestions or advice that would be greatly appreciated thank you! Here is my code for it so far: A = [] B = [] f = open("matrix.txt") while True: line = f.readline() if not line: #if end of file is reached, close print("end of file has been reached") break if line == '\n': #when there is a blank line f.readline() if not line: # if end of file is reached, close print("end of file has been reached") break else: B.append(list(map(int, line.split()))) np.array(B) else: A.append(list(map(int, line.split()))) np.array(A) print("Matrix A") print(A) print("Matrix B") print(B)

http://stackoverflow.com/comment/91625010
has text: the code should run, it is only missing the music and an incomplete GUI. And thank you for your response.
type: Comment
comment on: http://stackoverflow.com/a/52338704
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91599621
type: AnswerComment
has text: thank you sir, you have been doing a great work. I just started exploring things need to learn alot from people like you :-)
comment on: http://stackoverflow.com/a/52325876
type: Comment
score: 1

http://stackoverflow.com/a/52350004
type: Answer
score: 6
accepted answer of: http://stackoverflow.com/q/52346447
has body: After some digging in the sources of the scripts and the linux kernel, I have managed to fix the issue. The problem lies in this commit which replaced the module_core pointer with a module_layout struct in the include/linux/module.h header. The change had been apparently pulled into kernel 4.4.0 but was not accounted for in the helper scripts until a later version. This had been dealt with a while later (specifically - in this commit), so all kernel versions between 4.4.0 and 4.6-rc1 will have this bug. The solution is to download the scripts from the aforementioned commit and place them in the relevant directories. This is certainly a rare edge-case but I hope this answer will be helpful to somebody someday.
downvote count: 0
upvote count: 6
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52346447

http://stackoverflow.com/a/52293478
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52291509
has body: This error code results from an attempt to cast a numpy array to float, which has length > 1: Example: float(np.array([3,2,1])) Traceback (most recent call last): File "&lt;ipython-input-22-e396216bb2ea&gt;", line 1, in &lt;module&gt; float(np.array([3,2,1])) TypeError: only length-1 arrays can be converted to Python scalars but: float(np.array([3])) : 3.0 So this error occurs in your line (44, to cite the error message) y.append(float(list_temp2)) in case of list_temp2 has more than one entry. So it should have nothing to do with how many files you process. However: Like Georgy already mentioned - let's say your code is a little more complicated than the task requires. Here just a few thoughts of mine... if you need a list of all csv-files in a directory, did you have alook at python's glob-module? It's capable of searching subdirectories, too... You iterate over a file for reading, again for writing without lines which contain "Date" and then again you read it it again...? That's too much, IIUC. Couldn't you just use the last loop and put your list_temp-stuff there in a conditional, which tests for "contains 'Date'"? Why do you fig = pyplot.figure(figsize=(10,10)) right before plt.show() at the end? This should lead to an unused empty figure. headerremover.py combined with your loop and if 'Date' not in row looks like if there are many header lines, also in the middle, in your files - is that true? Because if you just would have a header section of n lines at the top of each file, there would be again much simpler ways to skip these lines...
answers question: http://stackoverflow.com/q/52291509
type: AcceptedAnswer

http://stackoverflow.com/q/52411916
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: opencv
tagged with: video
has body: I try to read a video, flip the frames and then save it, but the output video windows says its corrupted and wont play. import cv2 as cv cap = cv.VideoCapture('wtf.avi') assert cap.isOpened() fourcc = cv.VideoWriter_fourcc(*'DIVX') out = cv.VideoWriter('output.avi', fourcc, 20.0, (640,480)) assert out.isOpened() while True: ret, frame = cap.read() if not ret: break frame = cv.flip(frame, 0) # write the flipped frame out.write(frame) cv.imshow('frame', frame) if cv.waitKey(35) == ord('q'): break # Release everything if job is finished cap.release() out.release() cv.destroyAllWindows()
upvote count: 1
has answer: http://stackoverflow.com/a/53309454
type: Question
downvote count: 0
answer count: 1
score: 1
has title: Opencv video read and save again is corrupted

http://stackoverflow.com/q/52302752
has title: jupyter notebook not finding python module that is definitely installed
has comment: http://stackoverflow.com/comment/91553433
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91553668
tagged with: jupyter-notebook
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52302958
has comment: http://stackoverflow.com/comment/91553377
has body: I have a Python script in Jupyter Notebook that has some module dependencies. Here is where I'm importing them: import requests import furl import pandas as pd import numpy as np import json When I run that code block in Jupyter, I get this error: ModuleNotFoundError Traceback (most recent call last) &lt;ipython-input-21-9114a07a03b4&gt; in &lt;module&gt;() 1 import requests ----&gt; 2 import furl 3 import pandas as pd 4 import numpy as np 5 import json ModuleNotFoundError: No module named 'furl' I have both Python 2.7 and 3.7 on my machine. I have run both py -3 -m pip install furl and py -2 -m pip install furl to successfully install furl on both versions. Yet, I still get this module not found error. I have no idea what to do next. Would be very grateful for any help.
type: Question

http://stackoverflow.com/comment/91559641
has text: attempt 2 `document.location.reload()` stores the location, hence will reload to same position
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52306100
score: 0

http://stackoverflow.com/comment/91684529
type: Comment
type: QuestionComment
score: 2
has text: This is very confusing. It would probably serve you to take more time to explain what is actually being checked and what constitutes changes. Where you say "I have tried this" doesn't do a good job describing what you mean to do.
comment on: http://stackoverflow.com/q/52369865

http://stackoverflow.com/comment/91627496
comment on: http://stackoverflow.com/a/52337825
type: Comment
score: 0
type: AnswerComment
has text: You can corroborate that with a small test with only a few words and see if it really is that way

http://stackoverflow.com/q/52414555
has title: Google App Engine - App was unable to send logs
type: Question
downvote count: 0
has body: My app started to create some strange errors with logging since the last deployment: File "/env/lib/python3.6/site-packages/google/cloud/logging/handlers/transports/background_thread.py", line 118, in _safely_commit_batch batch.commit() File "/env/lib/python3.6/site-packages/google/cloud/logging/logger.py", line 612, in commit client.logging_api.write_entries(entries, **kwargs) File "/env/lib/python3.6/site-packages/google/cloud/logging/_gapic.py", line 124, in write_entries partial_success=partial_success) File "/env/lib/python3.6/site-packages/google/cloud/logging_v2/gapic/logging_service_v2_client.py", line 341, in write_log_entries request, retry=retry, timeout=timeout, metadata=metadata) File "/env/lib/python3.6/site-packages/google/api_core/gapic_v1/method.py", line 139, in __call__ return wrapped_func(*args, **kwargs) File "/env/lib/python3.6/site-packages/google/api_core/retry.py", line 260, in retry_wrapped_func on_error=on_error, File "/env/lib/python3.6/site-packages/google/api_core/retry.py", line 177, in retry_target return target() File "/env/lib/python3.6/site-packages/google/api_core/timeout.py", line 206, in func_with_timeout return func(*args, **kwargs) File "/env/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 61, in error_remapped_callable six.raise_from(exceptions.from_grpc_error(exc), exc) File "&lt;string&gt;", line 3, in raise_from google.api_core.exceptions.PermissionDenied: 403 The caller does not have permission " timestamp: "2018-09-19T21:35:58Z" However, if I run a local server, everything works normally. I tried to install the newest log library locally, and tested that logs can be sent out in a local environment. Is there a way to debug this?
has answer: http://stackoverflow.com/a/52423290
answer count: 1
favorite count: 0
upvote count: 2
tagged with: google-app-engine
tagged with: python
accepted answer: http://stackoverflow.com/a/52423290
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/91701869
comment on: http://stackoverflow.com/q/52378730
score: 0
type: Comment
type: QuestionComment
has text: Also, it would be best to stick to loops for performance that is.

http://stackoverflow.com/a/52280391
downvote count: 0
type: Answer
has body: You should apply the re.sub function on single objects, not on lists. files_cleaned = [re.sub(r"[-()\"#/@;:&lt;&gt;{}`+=~|.!?,]", "", file) for file in files] If you only want to accept alphanumerical characters you can do this instead: files_cleaned = [re.sub(r"[^a-zA-Z0-9]", "", file) for file in files]
answers question: http://stackoverflow.com/q/52280027
upvote count: 4
score: 4

http://stackoverflow.com/comment/91596848
type: Comment
has text: I understand that - and don't get me wrong, you can choose whatever solution you like best (although of course I naturally find my solution cleaner than that of @Sphinx and I can imagine that it's even more efficient, but this is not proven yet). However, both solutions _can_ work, but for both it's crucial that the regular expression pattern _exactly_ meets your requirements. Otherwise you'll end up getting wrongly deleted id's and false positives.
comment on: http://stackoverflow.com/a/52321093
score: 0
type: AnswerComment

http://stackoverflow.com/a/52374094
downvote count: 0
has comment: http://stackoverflow.com/comment/91711457
type: Answer
score: 1
has body: If it's guaranteed that all the spans will have a data-original-title... and If the title will always in in the format of "Happiness<SPACE><PERCENTAGE><NEW LINE>Sadness<SPACE><PERCENTAGE>" Then below should work out for you. >>> import itertools >>> import re >>> import pandas as pd >>> import bs4 >>> html = """More stats, ... More stats""" >>> soup = bs4.BeautifulSoup(html, 'lxml') >>> all_rows = [] >>> for span in soup.find_all('span'): ... title_eles = re.split(' |\n', span['data-original-title']) ... title_eles = list(filter(None, title_eles)) ... row = dict(itertools.zip_longest(title_eles[::2], title_eles[1::2], fillvalue="")) ... all_rows.append(row) ... >>> pd.DataFrame(all_rows) Happiness Sadness 0 84% 80% 1 70% 59% Also the reason why soup.find_all(class_='data-original-title') returns empty is because data-original-title is an attribute in your HTML. It's not a class.
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52373527
answers question: http://stackoverflow.com/q/52373527
type: AcceptedAnswer

http://stackoverflow.com/comment/91769787
type: Comment
comment on: http://stackoverflow.com/a/52409665
type: AnswerComment
has text: 1. fixed. 2. binding a lambda to a name is totally fine if a function just evaluates an expression. Even Raymond Hettinger [does](https://pybay.com/site_media/slides/raymond2018-keynote/doctest.html) it ;) 3. That's pretty subjective.
score: 0

http://stackoverflow.com/q/52424814
answer count: 0
type: UnansweredQuestion
upvote count: 1
score: 1
type: Question
downvote count: 0
favorite count: 0
has title: pyinstaller multiple files. Import .py
tagged with: pyinstaller
tagged with: python
tagged with: python-3.x
has body: I Have a problem. I want to create a .exe file that will read my project. My project contains the following files: Main.py, Data.py, two images, and two folders. Main.py imports Data.py, reads the images and saves the results in one of the folders. Data.py contains a class and stores data inside the class read from text files that are in the other folder. How can I make a .exe file that will have all of those files and folders? I can build a .exe file out of Main.py and paste all the files in the Main folder of the dist folder, but the .exe won't read data.py. Thank you

http://stackoverflow.com/comment/91756058
score: 0
type: AnswerComment
type: Comment
has text: @JohnE, would you mind writing the line for the updated groupby command?
comment on: http://stackoverflow.com/a/52405491

http://stackoverflow.com/q/52420515
linked to: http://stackoverflow.com/q/36362624
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91789140
has title: Python matplotlib/Seaborn plotting side by side histogram using a loop
answer count: 0
tagged with: histogram
has comment: http://stackoverflow.com/comment/91841291
favorite count: 0
has comment: http://stackoverflow.com/comment/93209742
has comment: http://stackoverflow.com/comment/91810617
linked to: http://stackoverflow.com/q/6871201
type: Question
tagged with: seaborn
has comment: http://stackoverflow.com/comment/91813630
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/91831640
has body: I am trying to plot bar style histograms with multiple classifications as stored in a pandas dataframe. I can get the the histograms to plot using both the methods below, however they cover each other and I'd like to plot them side by side. In the second case, the histtype variable appears to be ignored. Is there a way to do this using one of the two methods below? I have tried like this import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns colour = 0 for var in array: l = [var] df_array=df.loc[df.var.isin(l) , :] df_array[v].dropna(inplace=True) plt3=sns.distplot(df_array[v],label=var,kde=False) colour += 1 and like this import numpy as np import pandas as pd import matplotlib.pyplot as plt colour = 0 for var in array: df_array=df.loc[df.var.isin([var]) , :] df_array[v].dropna(inplace=True) plt4 = plt.hist(list(df_array[df_array['var'] == var][v]), histtype = 'bar', stacked = False) colour += 1 I would like to produce a final plot similar to this
has comment: http://stackoverflow.com/comment/91814135
has comment: http://stackoverflow.com/comment/91814387
has comment: http://stackoverflow.com/comment/93209666
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91814777
has comment: http://stackoverflow.com/comment/93284416
downvote count: 1
upvote count: 5

http://stackoverflow.com/comment/91518059
type: Comment
has text: Ah thanks. I see where I went wrong. Great answer and I appreciate the response.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52284227

http://stackoverflow.com/q/52377496
downvote count: 0
has title: From a list of vectors, extract only one column from each vector
favorite count: 0
has answer: http://stackoverflow.com/a/52377731
type: UnansweredQuestion
tagged with: python
answer count: 4
score: 1
has answer: http://stackoverflow.com/a/52377522
upvote count: 1
has answer: http://stackoverflow.com/a/52377971
type: Question
has answer: http://stackoverflow.com/a/52378160
has body: Given a list of vectors: [((0, 2.6147858445098677), (1, 1.0257184186249431)), ((0, 2.6147858445098677), (2, 0.34113605903013322)), ((0, 2.6147858445098677), (3, 0.074196986667672063)), ((1, 1.0257184186249431), (2, 0.34113605903013322)), ((1, 1.0257184186249431), (3, 0.074196986667672063)), ((2, 0.34113605903013322), (3, 0.074196986667672063))] how to extract only the first entry in each vector? [(0, 1), (0,2), (0, 3), (1, 2), (1,3), (2, 3)]

http://stackoverflow.com/q/52285058
has answer: http://stackoverflow.com/a/52285269
has answer: http://stackoverflow.com/a/52285159
has comment: http://stackoverflow.com/comment/91518630
tagged with: python
has body: I have two sorted lists x = [-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10] y = [3,4,5,6] Between these x and y I would like to return imin = (6,0) and imax = (9,3). If these lists do not share any elements, I would like to return imin = None and imax = None. A solution is def inds(x,y): arr = [(i,j) for i,xx in enumerate(x) for j,yy in enumerate(y) if xx==yy ] if arr!=[]: # to obtain proper None output imin = (min(i for i,_ in arr), min(j for _,j in arr)) imax = (max(i for i,_ in arr), max(j for _,j in arr)) else: imin = None imax = None return (imin,imax) This does a lot of unnecessary computation (O(n**2)) and is a bottleneck of one of my programs. Can anyone suggest something faster? ADDITIONAL (NON-MINIMAL EXAMPLE) INFO If it helps, I actually have a list of objects. objects = [(A1,B1),(A2,B2)] x and y would be attributes of each element of this objects list like so: x = objects[0][0].attrib y = objects[0][1].attrib and I actually want to generate [(imin1,imax1),(imin2,imax2)] Which could come, for example, from def attribs(A,B): return (A.attrib,B.attrib) [inds(*attribs(*v)) for v in objects] note: I added a numpy tag just because I'm open to using numpy for this if it's faster.
type: AnsweredQuestion
tagged with: list
upvote count: 1
has comment: http://stackoverflow.com/comment/91518664
type: Question
has title: fastest method to get indices of first and last common elements between lists
accepted answer: http://stackoverflow.com/a/52285159
score: 1
has comment: http://stackoverflow.com/comment/91518681
has answer: http://stackoverflow.com/a/52285320
tagged with: numpy
answer count: 3
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91518572
possible better answer: http://stackoverflow.com/a/52285269
has comment: http://stackoverflow.com/comment/91518578

http://stackoverflow.com/comment/91495191
comment on: http://stackoverflow.com/q/52273744
score: 0
type: Comment
type: QuestionComment
has text: Why would you want to do that instead of having a nested list? Pandas is not designed for columns containing lists, it works mostly with scalar values. You lose all the benefit by doing that

http://stackoverflow.com/q/52295129
has body: I have the following information in a DataFrame in Python: ## x1 x2 x3 x4 x5 colum ##0 206 214 021 122 554 2 ##1 226 234 123 456 789 4 ##2 245 253 558 855 123 5 ##3 265 272 000 111 222 4 ##4 283 291 214 589 996 1 and I need to generate a new column depending on the value that contains the colum column, in the following way: ## x1 x2 x3 x4 x5 colum newColum ##0 206 214 021 122 554 2 214 ##1 226 234 123 456 789 4 456 ##2 245 253 558 855 123 5 123 ##3 265 272 000 111 222 4 111 ##4 283 291 214 589 996 1 283 I do not know if I am clear in my request, I thank who can help me.
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52295231
tagged with: python
has answer: http://stackoverflow.com/a/52295208
type: AnsweredQuestion
score: 0
has title: Change row value dynamically in python
possible better answer: http://stackoverflow.com/a/52295208
type: Question
tagged with: indexing
has answer: http://stackoverflow.com/a/52295231
answer count: 2
tagged with: pandas

http://stackoverflow.com/q/52346958
answer count: 2
tagged with: virtualenv
has answer: http://stackoverflow.com/a/52347073
favorite count: 0
has comment: http://stackoverflow.com/comment/91639992
linked to: http://stackoverflow.com/q/6943208
has comment: http://stackoverflow.com/comment/91639989
linked to: http://stackoverflow.com/q/18337767
tagged with: python-3.x
upvote count: 2
accepted answer: http://stackoverflow.com/a/52347073
tagged with: python
downvote count: 1
type: AnsweredQuestion
has title: Run virtualenvwrapper commands from python script
score: 1
possible better answer: http://stackoverflow.com/a/63279537
has body: When I'm trying to create a new Python 3 virtual environment by using mkvirtualenv (virtualenvwrapper command) and os.system like this import os os.system('mkvirtualenv foo') nothing happens. os.system("mate-terminal -e 'workon foo'") doesn't work either. The point is to quickly create a new virtual env and work on it later for each project (it's an automation script). virtualenvwrapper is the most convenient option.
has answer: http://stackoverflow.com/a/63279537
tagged with: virtualenvwrapper
type: Question
has comment: http://stackoverflow.com/comment/91639604

http://stackoverflow.com/comment/91801980
type: QuestionComment
has text: @Prune thanks for the edit. Would you be able to help me out?
comment on: http://stackoverflow.com/q/52428823
score: 0
type: Comment

http://stackoverflow.com/q/52347984
tagged with: java
accepted answer: http://stackoverflow.com/a/52354900
type: Question
tagged with: heroku
tagged with: kotlin
has answer: http://stackoverflow.com/a/52354900
upvote count: 1
answer count: 1
favorite count: 0
has title: Running Python script from Java/Kotlin application on Heroku
has body: I have a Java/Kotlin application that runs a Python script every time the user makes a request. It works well on my laptop and any other VPS. But I couldn't make it work on Heroku. It does not work and prints nothing. Here is the relevant code: val command = "python3 $s/assets/script.py $params" println("Command: $command") val process = Runtime.getRuntime().exec(command) process.waitFor() val reader = BufferedReader(InputStreamReader(process.inputStream)) val message = reader.lines().collect(Collectors.joining("\n")) println(message) Why would this fail on Heroku?
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/comment/91602789
score: 0
has text: And you shouldn't. If someone asks for more information in comments on this site, always add them to your question with the correct formatting and then make a comment that you did so.
comment on: http://stackoverflow.com/q/52327864
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52337046
tagged with: pandas
score: 3
has body: I wanto to read a SQL file and use CountVectorizer to get word occurences. I have the following code so far: import re import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer df = pd.read_sql(q, dlconn) print(df) count_vect = CountVectorizer() X_train_counts= count_vect.fit_transform(df) print(X_train_counts.shape) print(count_vect.vocabulary_) This gives an output of 'cat': 1, 'dog': 0 It seems that it is taking just the name of the column animal and counting from there. How do I get it to access the full column and get a chart that shows every word in the column and its frequency?
accepted answer: http://stackoverflow.com/a/52337825
tagged with: python
upvote count: 3
has comment: http://stackoverflow.com/comment/91624529
has comment: http://stackoverflow.com/comment/91622381
has title: Reading in a SQL file and Using Count Vectorizer to get word occurences
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52337825
type: Question
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/q/52390390
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91726208
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91728717
type: Question
has comment: http://stackoverflow.com/comment/91726683
has comment: http://stackoverflow.com/comment/91728642
has title: Django runserver in windows just aborts with no error message
score: 0
has comment: http://stackoverflow.com/comment/91725928
tagged with: windows
has body: I have been developing a Django project with some of the programmers using windows. Suddenly, all of them are unable to go on because runserver just aborts when accessing the port from the web browser. Just like that, with no error message or anything. I guess it is windows issue because programmers with mac have no problem at all, and all windows pcs got the problem at the same time. Has anybody known about any Windows issue lately and have any reference to try to find the solution? It, is a critical situation. I got this information from Windows Event Monitor: System - Provider [ Name] Windows Error Reporting - EventID 1001 [ Qualifiers] 0 Level 4 Task 0 Keywords 0x80000000000000 - TimeCreated [ SystemTime] 2018-09-18T21:23:09.081612800Z EventRecordID 1121 Channel Application Computer DESKTOP-UMHL2MO Security - EventData 2255961328469566825 1 APPCRASH No disponible 0 python.exe 3.7.150.1013 5b330dc6 StackHash_89ce 10.0.17134.1 c8733c73 c0000374 PCH_CF_FROM_ntdll+0x00069ABC \\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER3360.tmp.dmp \\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER340D.tmp.WERInternalMetadata.xml \\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER341E.tmp.xml \\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER341E.tmp.csv \\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER343E.tmp.txt C:\ProgramData\Microsoft\Windows\WER\ReportArchive\AppCrash_python.exe_54cf6c8aeb3ae10789acd854ed6a82b72d1c7c1_d4f4c736_01a13796 0 b7e6ab6d-2a75-4996-9e5e-c5d132578749 268435456 2bfa2eb7e405e3f06f4ec8e02a726569 0 Windows Event Monitor just informs of a crash of python.exe, but no other trace-back information. This is an image of the console for you to see that the server just breakes with no error raised or anything:
has comment: http://stackoverflow.com/comment/91735499
answer count: 0

http://stackoverflow.com/comment/91627867
score: 1
comment on: http://stackoverflow.com/q/52340319
has text: Possible duplicate of [Pytest: Deselecting tests](https://stackoverflow.com/questions/7395444/pytest-deselecting-tests)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91550677
has text: There's a way to call a function with arguments from a button push in tkinter. That would simplify your code somewhat. Go here for the syntax: https://stackoverflow.com/questions/6920302/how-to-pass-arguments-to-a-button-command-in-tkinter#6921225.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52296794

http://stackoverflow.com/comment/91596600
comment on: http://stackoverflow.com/q/52324838
type: Comment
type: QuestionComment
score: 4
has text: Possible duplicate of [How do I copy a file in Python?](https://stackoverflow.com/questions/123198/how-do-i-copy-a-file-in-python)

http://stackoverflow.com/q/52288445
tagged with: tree
type: AnsweredQuestion
tagged with: algorithm
downvote count: 5
has body: how to merge two trees in order (using 'anytree') in python merge the same depth node in order(in order means nodes from left to right in same depth one by one ) to one new node and add edge weight. from anytree import Node, RenderTree,LevelOrderIter,search Root = Node(name="0", cart=0, cnt=0, goodsid='-1', parent=None) node1 = Node(name="1", cart=0, cnt=1, goodsid='-1', parent=Root) node2 = Node(name="2", cart=0, cnt=2, goodsid='-1', parent=Root) node3 = Node(name="3", cart=0, cnt=3, goodsid='-1', parent=Root) node4 = Node(name="4", cart=0, cnt=4, goodsid='-1', parent=Root) node5 = Node(name="5", cart=0, cnt=5, goodsid='-1', parent=node1) node6 = Node(name="6", cart=0, cnt=6, goodsid='-1', parent=node1) node7 = Node(name="7", cart=0, cnt=7, goodsid='-1', parent=node4) print(RenderTree(Root)) Root_1 = Node(name="a", cart=0, cnt=0, goodsid='-1', parent=None) node_b = Node(name="b", cart=0, cnt=1, goodsid='-1', parent=Root_1) node_c = Node(name="c", cart=0, cnt=2, goodsid='-1', parent=Root_1) node_d = Node(name="d", cart=0, cnt=3, goodsid='-1', parent=node_b) node_e = Node(name="e", cart=0, cnt=4, goodsid='-1', parent=node_c) node_f = Node(name="f", cart=0, cnt=5, goodsid='-1', parent=node_c) node_g = Node(name="g", cart=0, cnt=5, goodsid='-1', parent=node_f) node_h = Node(name="h", cart=0, cnt=7, goodsid='-1', parent=node_g) print(RenderTree(Root_1)) here is the two sample tree how to merge them
type: Question
has answer: http://stackoverflow.com/a/52326191
has comment: http://stackoverflow.com/comment/91524825
has comment: http://stackoverflow.com/comment/91524919
answer count: 1
tagged with: graph-algorithm
tagged with: data-structures
tagged with: python
accepted answer: http://stackoverflow.com/a/52326191
favorite count: 0
has comment: http://stackoverflow.com/comment/91525385
upvote count: 2
has comment: http://stackoverflow.com/comment/91524698
score: -3
has comment: http://stackoverflow.com/comment/91524758
has title: How to merge two trees(multi-way tree ) in order (using 'anytree') in python

http://stackoverflow.com/comment/91757632
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52399907
has text: **team** prints the value of the dict on the console.
score: 0

http://stackoverflow.com/comment/133525573
has text: Thank you for submitting an answer! However, it looks like your suggestion is intended for a Linux system using apt, whereas the OP is looking for help on the Windows platform.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/75640101
type: Comment

http://stackoverflow.com/comment/91839312
comment on: http://stackoverflow.com/a/52428327
score: 0
type: Comment
has text: Thank you a lot, it's work with this 'profile_city.cities.all()' and I could get all the values.
type: AnswerComment

http://stackoverflow.com/q/52351526
has comment: http://stackoverflow.com/comment/91683726
answer count: 0
has body: I am trying to facilitate writing series of images acquired from ipcam streaming, so I've used a producer consumer pattern, where producer put image into a queue, while consumer read image out of queue. Is it possible to improve the saving to disk performance by creating multiple thread to handle write to disk ? Because the mechanism how file are write to disk, would this approach be eventually have same performance as a single thread writer ?
type: UnansweredQuestion
tagged with: multithreading
type: Question
has comment: http://stackoverflow.com/comment/91648280
has comment: http://stackoverflow.com/comment/91661892
score: 0
tagged with: io
has title: Is it possible to write image to disk in parallel ? (Python)
tagged with: python

http://stackoverflow.com/comment/91740693
score: 1
has text: For further clarity: I am saying that the comparison of A and B should return False, but the function is not working correctly because it needs to compare like with like `dtypes`, so it is erroneously returning True. A and D have matching dtypes: str, int, str - so their comparison is working correctly and returning False (as the two string columns are switched)
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52398027

http://stackoverflow.com/a/52409668
has comment: http://stackoverflow.com/comment/91763191
type: Answer
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91763069
answers question: http://stackoverflow.com/q/52409584
has body: I think what you want to do is this: def obscure(string, n): characters = list(string) characters[n:-n] = '*' * len(characters[n:-n]) obscured = ''.join(characters) return obscured Turn the string into a list of characters. Replace the ones you want to obscure. Then join the list back into a string.
has comment: http://stackoverflow.com/comment/91763129

http://stackoverflow.com/q/52317881
tagged with: python
type: AnsweredQuestion
has title: Python3 - handle cases where a library is os-dependant
has comment: http://stackoverflow.com/comment/91583152
type: Question
has comment: http://stackoverflow.com/comment/91583689
linked to: http://stackoverflow.com/q/1854
has comment: http://stackoverflow.com/comment/91583134
score: 0
has body: I have a python script that is running on OSX; I use PyObjC library to perform some operations. Now, I would like to run the same script on windows; although there is no PyObjC on Windows, so when I call the module; I get a failure as expected. Is there a way in Python to tell the interpreter that if I am running on OSX, it should load that module, otherwise ignore it? Kinda like the IF statements in a C++ include section; which allow you to fall back to a different library, based on the hardware or software on which that program is running on? EDIT: I know how to find my OS; I did not ask how to find the Os on which my script run upon. The question was about how to import modules selectively, so I won't get a failure when running on a OS that does not require that module.
accepted answer: http://stackoverflow.com/a/52317988
answer count: 1
has answer: http://stackoverflow.com/a/52317988

http://stackoverflow.com/q/52313480
favorite count: 0
has comment: http://stackoverflow.com/comment/91662777
upvote count: 3
tagged with: pandas
has body: I am trying to return a cumulative count based on other columns. For the df below I want to return a count using Outcome and Aa,Bb,Cc,Dd. Specifically, if X or Y is in Outcome, I want to return the most recent increase in integers in Aa,Bb,Cc,Dd. So when X or Y are listed I want to return that against which integer in Aa,Bb,Cc,Dd was the most recent to increase. I have attempted this using the following: import pandas as pd d = ({ 'Outcome' : ['','','X','','','X','','Y','','Y'], 'A' : [0,0,0,1,1,1,2,2,2,2], 'B' : [0,0,0,1,1,1,1,1,2,2], 'C' : [0,0,0,1,2,3,3,3,3,3], 'D' : [0,1,2,2,2,2,2,2,2,2], }) df = pd.DataFrame(data = d) m = pd.get_dummies( df.where(df.Outcome.ne(df.Outcome.shift()) &amp; df.Outcome.str.len().astype(bool) ), prefix='Count').cumsum() df = pd.concat([ m.where(m.ne(m.shift())).fillna('', downcast='infer'), df], axis=1) But it's not quite right. My Intended Output is: Outcome A B C D A_X A_Y B_X B_Y C_X C_Y D_X D_Y 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 2 X 0 0 0 2 0 0 0 0 0 0 1 0 3 1 1 1 2 0 0 0 0 0 0 1 0 4 1 1 2 2 0 0 0 0 0 0 1 0 5 X 1 1 3 2 0 0 0 0 1 0 1 0 6 2 1 3 2 0 0 0 0 1 0 1 0 7 Y 2 1 3 2 0 1 0 0 1 0 1 0 8 2 2 3 2 0 1 0 0 1 0 1 0 9 Y 2 2 3 2 0 1 0 1 1 0 1 0
has comment: http://stackoverflow.com/comment/91669398
has comment: http://stackoverflow.com/comment/91790605
has comment: http://stackoverflow.com/comment/91669376
has title: Cumulative count based of values in another column
possible better answer: http://stackoverflow.com/a/52374631
tagged with: count
tagged with: python
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/91574769
has answer: http://stackoverflow.com/a/52399373
accepted answer: http://stackoverflow.com/a/52399373
type: Question
has answer: http://stackoverflow.com/a/52374631
has comment: http://stackoverflow.com/comment/91777861
has comment: http://stackoverflow.com/comment/91574921
has comment: http://stackoverflow.com/comment/91696685
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91808130

http://stackoverflow.com/q/52375357
has title: How to add Dates and Hours in Python
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52375497
tagged with: date
has comment: http://stackoverflow.com/comment/91695695
has body: Suppose I have two dates. How can I get all the intermediate dates and hours (from 00 to 23) between the two dates? Thank you very much! from datetime import datetime,timedelta, date date_min = (datetime.today()-timedelta(1)).strftime('%Y-%m-%d')+' 00' date_max = datetime.today().strftime('%Y-%m-%d')+' 00' date_min, date_max ('2018-09-16 00', '2018-09-17 00') how to obtain? '2018-09-16 01', '2018-09-16 02', '2018-09-16 03', '2018-09-16 04', .... , '2018-09-16 21', '2018-09-16 22', '2018-09-16 23', '2018-09-17 00'
has answer: http://stackoverflow.com/a/52375547
favorite count: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/52375547
tagged with: python
score: 2
possible better answer: http://stackoverflow.com/a/52375397
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52375397
upvote count: 3

http://stackoverflow.com/a/72261376
upvote count: 2
answers question: http://stackoverflow.com/q/52380572
has body: If you want to fold more that just a loop or a function, you can also try: #%% Code that you want to fold #%%
type: Answer
has comment: http://stackoverflow.com/comment/127729210
score: 2
downvote count: 0

http://stackoverflow.com/q/52390341
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91734978
score: 0
tagged with: youtube-data-api
type: Question
has body: I am using YouTube Data API v3 to search YouTube and parse results. Even if it says 4241 results on the response: resp["pageInfo"] {'totalResults': 4241, 'resultsPerPage': 50} I only get a few videos (49 on this case). Below is my code for getting all videos from the search API: def search_youtube(keyword): base_video_url = 'https://www.youtube.com/watch?v=' base_search_url = 'https://www.googleapis.com/youtube/v3/search?' # See full sample for function first_url = base_search_url+'key={}&amp;q={}&amp;part=snippet,id&amp;order=date&amp;maxResults=50'.format(API_KEY, keyword) video_links = [] url = first_url while True: print(len(video_links)) inp = requests.get(url) resp = json.loads(inp.text) for i in resp['items']: if i['id']['kind'] == "youtube#video": video_links.append(base_video_url + i['id']['videoId']) try: next_page_token = resp['nextPageToken'] url = first_url + '&amp;pageToken={}'.format(next_page_token) except: break return video_links all_videos = search_youtube("ural altay") I am never able to collect all videos from this. What can be the cause?
has comment: http://stackoverflow.com/comment/122521656
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91739980
has title: YouTube Data API v3 returns very few search results
has comment: http://stackoverflow.com/comment/91725829

http://stackoverflow.com/comment/91607835
type: Comment
comment on: http://stackoverflow.com/a/52330494
score: 1
type: AnswerComment
has text: @A.Aminidad The point was use a raw string to save you from from a backslash hell in your regular expression. For example to match a backslash you need two write "\\\\" or just r"\\", because you need to escape both the slash for the regex and the non-raw python string. So that is much easier to read.

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/52378289
tag name: google-oauth

http://stackoverflow.com/comment/91693991
type: QuestionComment
score: 1
has text: creating a process takes some time. How much tme does your processing take? if it's a few seconds, that could be perfectly normal.
type: Comment
comment on: http://stackoverflow.com/q/52374445

http://stackoverflow.com/comment/91641970
comment on: http://stackoverflow.com/q/52348225
score: 0
has text: @juanpa.arrivillaga `.seek` is much cheaper than closing & reopening the file.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52285351
tagged with: python
has body: I am following "Fluent Python" to learn Function and Design Pattern: In chapter 6 example-code/strategy.py def bulk_item_promo(order): """10% discount for each LineItem with 20 or more units""" discount = 0 for item in order.cart: if item.quantity &gt;= 20: discount += item.total() * .1 #augmented += ? return discount I am very confused about: discount += item.total() * .1 I assume it overhead complicated, because it's just discount = item.total() * .1 However, the author prefer to state it like discount = 0*1 + 0*2 + 0*3 + item.total() * .1 to increase it complexity artificially. What's the key points I missed? could you please provide any hints?
type: AnsweredQuestion
has title: An unexpected augmented assignment discount += item.total() * .1
has answer: http://stackoverflow.com/a/52285395
has answer: http://stackoverflow.com/a/52285431
type: Question
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52285414
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52285395
possible better answer: http://stackoverflow.com/a/52285414

http://stackoverflow.com/a/52343052
upvote count: 4
has body: Use EnumServicesStatus API like this : import win32con import win32service def ListServices(): resume = 0 accessSCM = win32con.GENERIC_READ accessSrv = win32service.SC_MANAGER_ALL_ACCESS #Open Service Control Manager hscm = win32service.OpenSCManager(None, None, accessSCM) #Enumerate Service Control Manager DB typeFilter = win32service.SERVICE_WIN32 stateFilter = win32service.SERVICE_STATE_ALL statuses = win32service.EnumServicesStatus(hscm, typeFilter, stateFilter) for (short_name, desc, status) in statuses: print(short_name, desc, status) ListServices(); win32service and win32con is part of pywin32 opensource project which you can download the lastest version here .
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52341845
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52341845
type: Answer
has comment: http://stackoverflow.com/comment/91638081
score: 4

encoder-decoder
type: Tag
tag name: encoder-decoder
tags question: http://stackoverflow.com/q/52412984

printers
tag name: printers
type: Tag
tags question: http://stackoverflow.com/q/52289640

http://stackoverflow.com/a/52377546
accepted answer of: http://stackoverflow.com/q/52377432
has body: You can assign a PeriodIndex to the dataframe with a June annual frequency (A-Jun), e.g.: df = pd.DataFrame({'date': pd.DatetimeIndex(start='2015-01', end='2016-12', freq='D')}) df = df.assign(fiscal_year=pd.PeriodIndex(df.date, freq='A-Jun')) If you need the string representation (e.g. FY2015), df.assign(fiscal_year_str='FY' + df['fiscal_year'].astype(str))
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52377432
upvote count: 1
has comment: http://stackoverflow.com/comment/91737428
score: 1
has comment: http://stackoverflow.com/comment/91737319

http://stackoverflow.com/q/52383595
has comment: http://stackoverflow.com/comment/91711401
has body: I've data iris in UCI. I want to group it by its class. I used this code: def splitData(trainingSet, classedTrainingSet=[], listClass=[]): for x in range(len(trainingSet)): classData = trainingSet[x][-1] #string if classData not in listClass: listClass.append(classData) for y in range(len(listClass)): if listClass[y] == classData: classedTrainingSet.append((y, trainingSet[x])) The error was: IndexError: tuple index out of range How can I group the data by its class?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91711427
tagged with: python
has answer: http://stackoverflow.com/a/52383831
type: Question
linked to: http://stackoverflow.com/q/1132941
has comment: http://stackoverflow.com/comment/91711710
score: 0
answer count: 1
has title: Grouping Data by its class in Python
tagged with: python-3.x

http://stackoverflow.com/q/52416449
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91776873
has comment: http://stackoverflow.com/comment/91776856
has comment: http://stackoverflow.com/comment/91776768
has title: how to use QSortFilterProxyModel for filter a 2d array?
has comment: http://stackoverflow.com/comment/91776784
has comment: http://stackoverflow.com/comment/91776720
has answer: http://stackoverflow.com/a/52418184
has comment: http://stackoverflow.com/comment/91776738
has comment: http://stackoverflow.com/comment/91776743
type: Question
accepted answer: http://stackoverflow.com/a/52418184
has comment: http://stackoverflow.com/comment/91776758
has comment: http://stackoverflow.com/comment/91776712
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/91776890
linked to: http://stackoverflow.com/q/52550903
has comment: http://stackoverflow.com/comment/91776828
has comment: http://stackoverflow.com/comment/91776815
score: 0
tagged with: pyqt
upvote count: 1
has comment: http://stackoverflow.com/comment/91776399
has comment: http://stackoverflow.com/comment/91776697
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91776691
has comment: http://stackoverflow.com/comment/91776755
has comment: http://stackoverflow.com/comment/91776792
favorite count: 0
has comment: http://stackoverflow.com/comment/91776604
tagged with: qsortfilterproxymodel
tagged with: python
has comment: http://stackoverflow.com/comment/91776649
has body: I have been struggling with this for a while, and i am not even sure i am using the right pyqt classes. I have a QTableView that display a 2d array of integers and i wish to filter it to only show the integer under a value. This is the example: from PyQt4 import QtCore, QtGui import random class TableModel(QtCore.QAbstractTableModel): def __init__(self, parent=None): super(TableModel, self).__init__(parent) self._columns = 3 self._parent = parent def rowCount(self, parent=QtCore.QModelIndex()): return int( float( len( self._parent.data ) ) / float( self._columns ) )+1 def columnCount(self, parent=QtCore.QModelIndex()): return self._columns def data(self, index, role=QtCore.Qt.DisplayRole): if not index.isValid(): return None if role == QtCore.Qt.DisplayRole: try: value = self._parent.data[ index.row() * self._columns + index.column() ] except: pass else: return value return None class tableProxyModel(QtGui.QSortFilterProxyModel): def __init__(self, parent=None): super(tableProxyModel, self).__init__(parent) self._parent = parent self.filterColumn = [] self.filterRow = [] self.maxFilter =0 def setFilter(self, value): # # this will find the 2d position of the datas that need to be kept visible # we need a list of the row and column axis # self.maxFilter = value self.filterColumn = [] self.filterRow = [] for i in self._parent.data: if i &lt; self.maxFilter: positionInList = [j for j,x in enumerate( self._parent.data ) if x == i][0] filterRow, filterColumn = self.getPosition( positionInList ) self.filterColumn.append(filterColumn) self.filterRow.append(filterRow) self.invalidateFilter() def getPosition(self, value): # # convert data list to a 2d array # leftOver = value%self._parent._tm._columns filterRow = (value-leftOver) / self._parent._tm._columns filterColumn = leftOver return filterRow, filterColumn def filterAcceptsRow(self, row, parent): model = self.sourceModel() if row in self.filterRow: return True else: return False def filterAcceptsColumn(self, column, pare…

http://stackoverflow.com/comment/91523966
comment on: http://stackoverflow.com/q/52287883
type: Comment
score: 0
has text: Depending on your use case, you may want to look at `defaultdict` or `Counter`, which might make your code a little more succinct. Also you should generally avoid using the names for built in functions as variable names. You use `dict` as a variable name. After this you cant use the built in function `dict`, as it's hidden. A good alternative name might be `d` or `counter`.
type: QuestionComment

http://stackoverflow.com/comment/91645566
has text: Little note for the math interested people, a recursion can be compared to the mathematical induction. The base case is the anchor, the induction step the body.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52349916
score: 0

http://stackoverflow.com/comment/91581316
comment on: http://stackoverflow.com/a/52316703
has text: @BryanOakley Yes, but you are using a str in the process. By example you could implement a Counter without using a Counter, because it is fairly high level. Although a low-level (C-level) type such as str cannot be implemented without somehow using str, implicitly or explicitly.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52354697
has comment: http://stackoverflow.com/comment/91654332
upvote count: 2
type: Answer
score: 2
has body: If you want a one-liner: print(sum([1 for word in input("Enter a string").lower().split() if word[0] == word[-1]]))
has comment: http://stackoverflow.com/comment/91654946
has comment: http://stackoverflow.com/comment/91654240
has comment: http://stackoverflow.com/comment/91654092
answers question: http://stackoverflow.com/q/52354612
downvote count: 0
has comment: http://stackoverflow.com/comment/91654281

http://stackoverflow.com/comment/91795448
has text: Another task (not thread) and a queue isn't any more or less expensive than a lock, so whatever fits your code structure best. Anyway, you might want to use a queue if you have a read backlog otherwise and want to keep more data in the pipeline – a Unix pipe only buffers one page. Or if your data has some structure that needs to be reassembled. Or if the data connection might break and needs to be re-established, which is often easier if you have a task that you can simply restart.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52405992

http://stackoverflow.com/comment/91675548
comment on: http://stackoverflow.com/q/52364673
score: 0
type: Comment
type: QuestionComment
has text: May be that is the reason. But it is not avoidable in my case. The situation of lot of data greater 0.5 may arise. How would I know whether the mode is overfit or not. It seems all Okay to me till now

http://stackoverflow.com/a/52347653
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52345206
answers question: http://stackoverflow.com/q/52345206
has body: My variant would be: df2 = df.reindex(df.index.repeat(df["max"])).reset_index(drop=True) df2["number"] = df2.groupby("name").cumcount(ascending=False) + 1 which gives In [137]: df2 Out[137]: name max number 0 a 1 1 1 b 2 2 2 b 2 1 3 c 2 2 4 c 2 1 5 d 4 4 6 d 4 3 7 d 4 2 8 d 4 1 9 e 1 1 It does assume that the original indices are unique to make the repeat operation concise. If needed, we could replace with df2 = df.iloc[np.repeat(range(len(df)), df["max"])].reset_index(drop=True) or something.
type: Answer
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/91552704
comment on: http://stackoverflow.com/a/52302316
type: Comment
has text: oops apologize my mistake. I thought **;** as colon
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91799482
has text: @Code-Apprentice could you please avoid inept suggestions ? Thank you.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52426691

http://stackoverflow.com/comment/91593928
type: Comment
type: QuestionComment
score: 2
has text: Can't you just write `return (math.sqrt(num)%2 == 0 or (math.sqrt(num)+1) % 2 == 0)`?
comment on: http://stackoverflow.com/q/52323299

http://stackoverflow.com/comment/91782004
comment on: http://stackoverflow.com/q/52419402
score: 3
has text: I don't get how you arrive at the conclusion that numba slowed you down: you show that numba provided you with a 7x speedup (from 8.2 to 1.2 seconds).
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91718888
score: 1
comment on: http://stackoverflow.com/q/52386330
has text: No; if you want named parameters (which is a good idea), then you have to be explicit about what to do with them and write the boilerplate code.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52420801
tagged with: xpath
has answer: http://stackoverflow.com/a/52422176
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52422176
score: 0
has title: Scrapy+Xpath+Python: Datapoint cannot be scraped
tagged with: web-crawler
tagged with: scrapy
has answer: http://stackoverflow.com/a/52421016
type: Question
answer count: 2
has body: I want to scrape the URLs here: I tried these: response.xpath('//header[@class="geodir-entry-header"]/a/@href').extract() response.xpath('//div[class="geodir-content "]/header/a/@href').extract() response.xpath('//div[@class="geodir-content "]/header[@class="geodir-entry-header"]/a/@href').extract() All returned an empty list.
accepted answer: http://stackoverflow.com/a/52421016

http://stackoverflow.com/comment/91560832
type: Comment
has text: This will (undesirably) match `Jan.uary`.
type: AnswerComment
comment on: http://stackoverflow.com/a/52306774
score: 0

http://stackoverflow.com/q/52365008
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52365514
has title: Customizing Model Serializer for many to many fields in Django
has body: I need some guidance to implement the serializers for models containing many to many fields in a generalized way. Suppose I have the following (hugely simplified) models: class Operative(models.Model): name = models.CharField(max_length=256, blank=False) email = models.EmailField(unique=True, null=True) desiganation = models.PositiveSmallIntegerField(default=0, choices=((0, 'Operative'), (1, 'Manager'), (2, 'Owner'))) class Task(models.Model): title = models.CharField(max_length=256, blank=False) manager = models.ForeignKey(Operative, null=True,on_delete=models.SET_NULL) operatives = models.ManyToManyField(Operative, blank=True) deadline = models.DateTimeField(null=True, blank=True) Now if I have a serializer like this: class TaskSerializer(ModelSerializer): class Meta: model = Task fields = ('id', 'title', 'manager', 'operatives', 'deadline') read_only_fields = ('id',) What would be the best approach to handle the update requests containing integer ids for manager and operatives? The update API will receive POST requests containing json data like this: { "id": 1002, "title": "Task1", "deadline": "2018-09-15T15:53:00+05:00", "manager": 55, "operatives": [102, 110, 324] } I would like to implement the customized logic for foreign keys and many to many fields inside the serializer. Currently, I am using some helper methods in the View to get/set the ids for operatives and manager and it seems a bit clumsy.
tagged with: django-serializer
has answer: http://stackoverflow.com/a/52466985
type: Question
answer count: 2
tagged with: django-rest-framework
score: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91774179
comment on: http://stackoverflow.com/a/52415240
has text: Awesome; an unrecoverable position :P
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91553690
score: 0
comment on: http://stackoverflow.com/q/52302837
type: Comment
has text: @Denziloe only timing the svd for both codes lead to really close computation times. I'll check these links, there might be a lot of relevant information in them
type: QuestionComment

http://stackoverflow.com/a/52411391
has body: It looks like when I was defining it, it was a string rather than a list. So I changed: df1.iloc[i, df1.columns.get_loc('polygon')] = '({x},{y}) ({x},{y1}) ({x1},{y1}) ({x1},{y})'.format(x=x,y=y,x1=x+x1,y1=y+y1) to this: df1.iloc[i, df1.columns.get_loc('polygon')] = [(x,y),(x,y+y1),(x+x1,y+y1),(x+x1,y)]
accepted answer of: http://stackoverflow.com/q/52390746
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52390746

http://stackoverflow.com/comment/91670427
score: 0
type: AnswerComment
has text: @newbierp just substitute your `mycol.find` line with this.
type: Comment
comment on: http://stackoverflow.com/a/52363018

http://stackoverflow.com/tag/pdf
tags question: http://stackoverflow.com/q/52285281
tags question: http://stackoverflow.com/q/52346942
tags question: http://stackoverflow.com/q/52315259
tags question: http://stackoverflow.com/q/52303980
type: Tag
tags question: http://stackoverflow.com/q/52370597
tag name: pdf
tags question: http://stackoverflow.com/q/52349625
tags question: http://stackoverflow.com/q/52284547
tags question: http://stackoverflow.com/q/52425783
tags question: http://stackoverflow.com/q/52271908
tags question: http://stackoverflow.com/q/52341788
tags question: http://stackoverflow.com/q/52326782
tags question: http://stackoverflow.com/q/52282223
tags question: http://stackoverflow.com/q/52384798
tags question: http://stackoverflow.com/q/52366753

http://stackoverflow.com/q/52410303
score: 0
has answer: http://stackoverflow.com/a/52413310
tagged with: mqtt
tagged with: python
tagged with: opencv
type: AnsweredQuestion
has body: I'm working on a university project combining MQTT and Face recognition, using a raspberry pi. First of all I want to say that face recognition works normally when it's being run on its own but I have something that bugs me when applying it with MQTT. Inside the Try section, when a person is being recognized or unknown it publishes really fine every 3 secs. The strange thing is that if I put my hand in front of the camera or if I get out of range, it keeps on sending the ID of the last person it had recognized. I want it either do nothing or publish none. Any idea or suggestion to fix this? Thanks in advance EDIT 1: Basically as I figured out, it has to do more with the face recognition part. When using just a face recognition code using opencv it runs smoothly. But the thing complicates when I put my hand in front of the camera or go away, because the capture freezes at the last thing it sees so it keeps on printing/publishing the same thing. Haven't figured out a way to avoid this yet. Any help would be appreciated import cv2 import json import time import datetime as dt import paho.mqtt.client as mqtt detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") recognizer = cv2.face.LBPHFaceRecognizer_create() broker = "*****" port = ***** username = '*****' password = '*****' def on_connect(client, userdata, flags, rc): print("Connected with code: ", rc) client.subscribe('test/#') def on_message(client, userdata, msg): print(str(msg.payload)) client = mqtt.Client("Python1") client.on_connect = on_connect client.on_message = on_message client.username_pw_set(username, password) client.connect(broker, port, 60) client.loop_start() time.sleep(1) def facerecognizer(): recognizer.read("trainerdir/training.yml") font = cv2.FONT_HERSHEY_SIMPLEX # Loading data with open('data.json', 'r') as f: names = json.load(f) # reverse the data # NOTE: for k, v !! # else it raises error ! names = {v: k for k, v in names.items()} # print(names) print("[INFO] Face recognit…
accepted answer: http://stackoverflow.com/a/52520287
type: Question
answer count: 2
tagged with: raspberry-pi
possible better answer: http://stackoverflow.com/a/52413310
has title: Mqtt publishing message when face is detected
tagged with: paho
has answer: http://stackoverflow.com/a/52520287

http://stackoverflow.com/comment/91749361
score: 2
comment on: http://stackoverflow.com/q/52402758
type: Comment
type: QuestionComment
has text: In 2.x, map will build a list of N `None`s which you don't need - so that's not great. Also - you're introducing the overhead of a `lambda` to do the sort... (although technically you could do `map(list.sort, lists)` but that's still ugly and undesirable) And in 3.x, unless you deliberate iterate over it - nothing will happen anyway. Stick to the for-loop... General rule of thumb: If you want to keep the output then use map or a comprehension of some sort, if you don't use a loop.

http://stackoverflow.com/q/52333927
has answer: http://stackoverflow.com/a/52334150
has title: Python - Passing in email address from variable into a Python function
tagged with: email
has answer: http://stackoverflow.com/a/52334308
tagged with: variables
has comment: http://stackoverflow.com/comment/91615263
has body: I am working on building a Python function that emails a simple statement. I am trying to have the username and email address fetched from the respective variables and passed into the function. I am able to have the username passed but unable to pass the email address as part of the function. Could anyone guide as to how to pass in email address from the variable (mail) to "to" field. The below code when triggered sends mail to the email mentioned and also an unknown email address. from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib user = ['Steve','Austin'] mail = ['user1@mail.com','user2@mail.com'] def name(user,mail): # Email recipients sender_email = 'mail@mail.com' sender_password = '123456' server = 'smtp.gmail.com:587' to = "%(mail)s" &lt;-- Holds the email address of the receiver # Email structure and content text = """""" html = """Report Generated for - """ + user +""" message = MIMEMultipart( "alternative", None, [MIMEText(text), MIMEText(html, 'html')]) message.attach(MIMEText(html, 'html')) message['Subject'] = "Test Mail for " + str(user) message['From'] = sender_email message['To'] = to server = smtplib.SMTP(server) server.ehlo() server.starttls() server.login(sender_email, sender_password) server.sendmail(sender_email, to, message.as_string()) server.quit() name('Steve','user1@mail.com') name('Austin','user2@mail.com')
type: UnansweredQuestion
tagged with: python
score: 0
type: Question
has comment: http://stackoverflow.com/comment/91620480
answer count: 2

http://stackoverflow.com/comment/91663766
type: Comment
type: AnswerComment
has text: Thanks for your answer! However, iterator.initializer will reset everything, and the batches will always start from the beginning, thus for the majority class (class 0 in this case) it will always be the first several elements to be sampled. If you run ` sess.run(iterator.initializer, feed_dict={class_relprob_ph: [1, 1, 1, 1, 1]}) print(batch.eval())` in a for loop, the class 0 elements in the output will always be 0-5, which means elements 6-900 in class 0 are never used.
comment on: http://stackoverflow.com/a/52327888
score: 0

http://stackoverflow.com/comment/91673776
comment on: http://stackoverflow.com/a/52359980
has text: @NickD, I've tested the code above and it works as expected.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91761051
type: Comment
has text: "I would have expected that the elements of the array list_1_c to be ctypes elements" Obviously, that is not the case - so what is your question? Why this does not behave differently? How this behaves the way it does? What are the advantages and disadvantages? How to get typed elements?
score: 0
comment on: http://stackoverflow.com/q/52408253
type: QuestionComment

http://stackoverflow.com/a/52367693
has body: As others suggested base64 encoding might be a good solution, however if you can't or don't want to, you could add a custom header to the request, such as headers = {"X-my-custom-header": "uniquevalue"} Then on the flask side: unique_value = request.headers.get('X-my-custom-header') or unique_value = request.headers['X-my-custom-header'] That way you avoid the overhead of processing your image data again (if that matters) and you can generate a unique id for each frame with something like the python uuid module. Hope that helps
answers question: http://stackoverflow.com/q/52350987
score: 0
type: Answer

http://stackoverflow.com/a/52373383
has comment: http://stackoverflow.com/comment/91691496
has comment: http://stackoverflow.com/comment/91691737
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91692029
has comment: http://stackoverflow.com/comment/91691391
answers question: http://stackoverflow.com/q/52373314
type: Answer
has comment: http://stackoverflow.com/comment/91691529
accepted answer of: http://stackoverflow.com/q/52373314
score: 2
has comment: http://stackoverflow.com/comment/91691666
downvote count: 0
upvote count: 2
has body: As @DanielRoseman says, dictionaries have no order (until Python 3.7 where this is part of the language implementation). If you need it to be ordered, use collections.OrderedDict. It functions pretty much like a regular dictionary: import collections d = collections.OrderedDict(zip(a, b))

http://stackoverflow.com/comment/91580606
type: QuestionComment
has text: Wow really? So, if I want to use a CNN that looks into a folder that contains hundreds of images of any kind and returns me only the images that represent a cat, what would be the strategy? The only strategy I can think of is to have a 3rd training folder, apart from "cats" and "dogs", that would be "other". Put other pictures in that folder and train the CNN with these 3 folders. But the the problem is that "other" is very vast. It would take a lot of pictures of other animals, objects, landscapes, abstract pictures... that would be massive. Is there a better strategy for that problem?
score: 0
comment on: http://stackoverflow.com/q/52313836
type: Comment

http://stackoverflow.com/q/52413804
answer count: 1
has title: VTK, Python: How can I connect vtkpoints and visualise them as a surface?
tagged with: vtk
tagged with: python
has body: I currently have a code that visualises vtkpoints that I take from an OBJ file: poly = vtkPolyData() poly.SetPoints(points) //points from obj file sphere = vtkSphereSource() sphere.SetRadius(.7) sphere.SetThetaResolution(4) sphere.SetPhiResolution(4) glyph = vtkGlyph3D() glyph.SetSourceConnection(sphere.GetOutputPort()) glyph.SetInputData(poly) mapper = vtkPolyDataMapper() mapper.SetInputConnection(glyph.GetOutputPort()) self.actor = vtkActor() self.actor.SetMapper(mapper) self.ren.AddActor(self.actor) self.vtkWidget.Render() so then each of my points on my OBJ file is visualised as a sphere. However, I was wondering if there is a way to just connect these points and visualise them as a surface? I've tried vtksurfacereconstruction filter and delaunay, but that produces horrific results, nothing even close to what I need.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52439815
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91771547

http://stackoverflow.com/q/52415577
answer count: 2
accepted answer: http://stackoverflow.com/a/52416676
downvote count: 0
favorite count: 0
has body: Looking to do something along the lines of a UI as here: Bokeh: Using Checkbox widget to hide and show plots wherein I can selectively show/hide the whole figure in a column of figures. A drop down menu (OptionMenu with multiple selections) where I could select which plots showed up (assuming I could name the figures) would be preferable. I am not familiar with JS, any guidance? (Thanks in advance) I'd hope that the image wouldn't be visible anymore and the next figure would jump up like so: eg: I have multiple figures in a column generated as: from bokeh.io import output_file, show from bokeh.layouts import column from bokeh.plotting import figure output_file("layout.html") x = list(range(11)) y0 = x y1 = [10 - i for i in x] y2 = [abs(i - 5) for i in x] # create a new plot s1 = figure(plot_width=250, plot_height=250, title=None) s1.circle(x, y0, size=10, color="navy", alpha=0.5) # create another one s2 = figure(plot_width=250, plot_height=250, title=None) s2.triangle(x, y1, size=10, color="firebrick", alpha=0.5) # create and another s3 = figure(plot_width=250, plot_height=250, title=None) s3.square(x, y2, size=10, color="olive", alpha=0.5) # put the results in a column and show show(column(s1, s2, s3))
has answer: http://stackoverflow.com/a/52416676
tagged with: python
has title: Bokeh: Widget to Show/Hide Figures
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/44374307
score: 3
possible better answer: http://stackoverflow.com/a/60883925
upvote count: 3
tagged with: bokeh
type: Question
has answer: http://stackoverflow.com/a/60883925

http://stackoverflow.com/a/52338704
has comment: http://stackoverflow.com/comment/91624886
has comment: http://stackoverflow.com/comment/91624986
has comment: http://stackoverflow.com/comment/91625498
has comment: http://stackoverflow.com/comment/91624954
has comment: http://stackoverflow.com/comment/91624672
has comment: http://stackoverflow.com/comment/91624797
has comment: http://stackoverflow.com/comment/91625643
answers question: http://stackoverflow.com/q/52338647
has comment: http://stackoverflow.com/comment/91625010
score: 0
has comment: http://stackoverflow.com/comment/91625410
has body: I think you should blit the racetrack before the cars. BACKGROUND = pygame.Surface((1280, 800)) BACKGROUND.fill((127, 69, 2)) BACKGROUND = pygame.image.load("track1.png").convert() screen.blit(BACKGROUND,(0,0)) put this before you blit the cars.
type: Answer

http://stackoverflow.com/q/52398273
answer count: 2
has answer: http://stackoverflow.com/a/52398433
has body: I am writing a function that will retrieve data from sqlite table based on the parameters user provide. This is the function so far def database_retrieve(db_file, id): try: conn = sqlite3.connect(db_file) with conn: sql_command = "SELECT * FROM my_table WHERE id = "+id cur = conn.cursor() cur.execute(sql_command) result = cur.fetchall() return result except Exception as e: print(e) db_file = 'testdb.db' print(database_retrieve(db_file, 'subject1')) This gives me the following error no such column: subject1 None When I add subject1, which is an entry under the id column in my_table, directly to the sql command like this sql_command = "SELECT * FROM my_table WHERE id = 'subject1'" it works fine and prints all the data. I am new to sqlite3. Please help. Thanks in advance These are the links I used to come this far Python sqlite3 string variable in execute https://www.dummies.com/programming/databases/how-to-retrieve-data-from-specific-rows-in-mysql-databases/
score: 0
possible better answer: http://stackoverflow.com/a/52398433
tagged with: sqlite
tagged with: python
has answer: http://stackoverflow.com/a/52398440
type: AnsweredQuestion
has title: retrieving data from table based on a value from a python variable
linked to: http://stackoverflow.com/q/13880786
accepted answer: http://stackoverflow.com/a/52398440
type: Question

http://stackoverflow.com/comment/91748327
comment on: http://stackoverflow.com/q/52402133
score: 2
has text: @Aran-Fey but the 1.0 part isn't addressed there right?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91698728
type: AnswerComment
type: Comment
has text: Do any tutorials exist for this?
comment on: http://stackoverflow.com/a/52363100
score: 0

http://stackoverflow.com/q/52369301
has body: I have a class called Client which uses the requests module to interact with a service. It has methods like: def get_resource(self, url, headers): response = requests.get(url, headers, auth=self.auth) return response Now I want to call some methods before and after each call to the requests module. Something like: def get_resource(self, url, headers): self.add_request_header(headers) response = requests.get(url, headers, auth=self.auth) self.process_response_headers() return response I'm having trouble finding a way to do this without having to rewrite all Client methods. The most straightforward way is to change the calls to the request module to calls to self and add the calls to the methods there. def get_resource(self, url, headers): response = self.__get(url, headers, auth=self.auth) return response def __get(self, headers, auth): self.add_request_header(headers) response = requests.get(url, headers, auth=self.auth) self.process_response_headers() return response But this requires me to change all the call sites and duplicate functionality of the request module. I've tried to use decorators to add these method calls to the request module functions, but got stuck with how to pass in self to the decorator. I'm sure there's an elegant way to do this in Python.
downvote count: 0
has title: Decorating requests module calls with pre and post method calls
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: python-decorators
upvote count: 3
linked to: http://stackoverflow.com/q/39850270
has answer: http://stackoverflow.com/a/52369584
type: Question
score: 3
has answer: http://stackoverflow.com/a/52369976
has comment: http://stackoverflow.com/comment/91696417
answer count: 2

http://stackoverflow.com/q/52365342
linked to: http://stackoverflow.com/q/52219672
has answer: http://stackoverflow.com/a/52368302
accepted answer: http://stackoverflow.com/a/52368302
type: Question
upvote count: 2
has body: I post a new question related the old for a problem with the get from queue. This is the code (thanks to Martijn Pieters) import asyncio import sys import json import os import websockets async def socket_consumer(socket, outgoing): # take messages from the web socket and push them into the queue async for message in socket: await outgoing.put(message) file = open(r"/home/host/Desktop/FromSocket.txt", "a") file.write("From socket: " + ascii(message) + "\n") file.close() async def socket_producer(socket, incoming): # take messages from the queue and send them to the socket while True: message = await incoming.get() file = open(r"/home/host/Desktop/ToSocket.txt", "a") file.write("To socket: " + ascii(message) + "\n") file.close() await socket.send(message) async def connect_socket(incoming, outgoing, loop=None): header = {"Authorization": r"Basic XXX="} uri = 'XXXXXX' async with websockets.connect(uri, extra_headers=header) as web_socket: # create tasks for the consumer and producer. The asyncio loop will # manage these independently consumer_task = asyncio.ensure_future( socket_consumer(web_socket, outgoing), loop=loop) producer_task = asyncio.ensure_future( socket_producer(web_socket, incoming), loop=loop) # start both tasks, but have the loop return to us when one of them # has ended. We can then cancel the remainder done, pending = await asyncio.wait( [consumer_task, producer_task], return_when=asyncio.FIRST_COMPLETED) for task in pending: task.cancel() # pipe support async def stdio(loop=None): if loop is None: loop = asyncio.get_event_loop() reader = asyncio.StreamReader() await loop.connect_read_pipe( lambda: asyncio.StreamReaderProtocol(reader), sys.stdin) writer_transport, writer_protocol = await loop.connect_write_pipe( asyncio.streams.FlowControlMixin, os.fdopen(sys.stdout.fileno(), 'wb')) writer = asyncio.streams.StreamWriter( writer_transport, writer_protocol, None, loop) return reader, writer async def pipe_consumer(pipe_reader, outgoing): # take message…
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: pexpect
tagged with: python-asyncio
tagged with: python
tagged with: asynchronous
score: 2
downvote count: 0
has title: Reading from pipe with pexpect on Linux
type: AnsweredQuestion

http://stackoverflow.com/comment/91520617
has text: nope the names the same. so just take out the columns i want to add too and then add it back to the file appended and with the same other columns with values kept the same
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52285732

http://stackoverflow.com/a/52308339
answers question: http://stackoverflow.com/q/52292861
score: 2
upvote count: 2
has body: The correct loss function is: def customLoss(x): def neg_log_likelihood(y_true, y_pred): def neg_log(y_t,y_p): inter=(y_p[...,0,None]-y_t)/K.clip(y_p[...,1,None],K.epsilon(),None) val=K.log(K.clip(K.square(y_p[...,1,None]),K.epsilon(),None))+K.square(inter) return val val=neg_log(y_true,y_pred) deriv=K.gradients(val,x) xb=x+0.01*K.sign(deriv) out=model(xb) valb=neg_log(y_true,out) return K.mean(val+valb,axis=-1) return neg_log_likelihood The difference is that model(xb) returns a tensor while model.predict(xb) doesn't.
accepted answer of: http://stackoverflow.com/q/52292861
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91691400
comment on: http://stackoverflow.com/q/52372874
has text: you might want to try something like `emailpage.soup.find()`
score: 0
type: Comment
type: QuestionComment

mocking
tags question: http://stackoverflow.com/q/52285345
tags question: http://stackoverflow.com/q/52394540
tags question: http://stackoverflow.com/q/52328011
tags question: http://stackoverflow.com/q/52287624
tags question: http://stackoverflow.com/q/52373694
tags question: http://stackoverflow.com/q/52384833
tags question: http://stackoverflow.com/q/52393056
tags question: http://stackoverflow.com/q/52324568
tag name: mocking
tags question: http://stackoverflow.com/q/52313432
tags question: http://stackoverflow.com/q/52400909
tags question: http://stackoverflow.com/q/52372368
type: Tag
tags question: http://stackoverflow.com/q/52413528

http://stackoverflow.com/comment/91540483
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52293445
has text: Please shrink your code to a minimum working example. Instead of your data an an example numpy array with a few rows. Remove evey strange name, dictionary, etc. everything that is not related to the problem. We want to deal with your problem, not with your code :) https://stackoverflow.com/help/mcve

http://stackoverflow.com/comment/91649658
score: 0
type: AnswerComment
has text: I did the same,but still it gives me output as GET result
type: Comment
comment on: http://stackoverflow.com/a/52352258

http://stackoverflow.com/q/52429421
has comment: http://stackoverflow.com/comment/91804475
answer count: 2
has body: I've been trying to get the output of the following command 'manage-bde -status' which works fine on my windows cmd commande prompt, but by using a python program.The same command doesn't work on python subprocess, so I had to launch the manage-bde.exe file. So my code looks like this now : import os, platform, subprocess ################This part is only helpful for resolving 32 bit/64 bits issues########## system_root = os.environ.get('SystemRoot', 'C:\\Windows'); if (platform.architecture()[0] == '32bit' and platform.machine() == 'AMD64'): system32='Sysnative' else: system32='System32' manage_bde = os.path.join(system_root, system32, 'manage-bde.exe') print(manage_bde) ####################################################################################### stdout=subprocess.check_output(['start',manage_bde,'-status']) print('Output:'+stdout) I'm launching it from cmd commande line, with Python 3.7.0. The problem is that I get the following output : C:\WINDOWS\Sysnative\manage-bde.exe (this is from my print(manage_bde)) Traceback (most recent call last): File "testCLI.py", line 13, in &lt;module&gt; stdout=subprocess.check_output(['start',manage_bde,'-status']) File "d:\Profiles\user\AppData\Local\Programs\Python\Python3\lib\subprocess.py", line 376, in check_output **kwargs).stdout File "d:\Profiles\user\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 453, in run with Popen(*popenargs, **kwargs) as process: File "d:\Profiles\user\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 756, in __init__ restore_signals, start_new_session) File "d:\Profiles\user\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 1155, in _execute_child startupinfo) FileNotFoundError: [WinError 2] Specified file was not found I launch it from the D: Drive. Does anyone know what I missed ?
tagged with: windows
downvote count: 0
tagged with: cmd
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python
has title: Get the output of .exe file in Python3 on Windows
has answer: http://stackoverflow.com/a/52438897
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52429912
type: Question
possible better answer: http://stackoverflow.com/a/52429912
accepted answer: http://stackoverflow.com/a/52438897
tagged with: bitlocker

http://stackoverflow.com/a/52431519
score: 1
has comment: http://stackoverflow.com/comment/114404780
accepted answer of: http://stackoverflow.com/q/52376692
answers question: http://stackoverflow.com/q/52376692
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/114399322
type: Answer
has body: I solved the problem by excluding that single variable using: variables = slim.get_variables_to_restore() variables_to_restore = [v for v in variables if 'global_step_counter' not in v.name.split('/')[0]] saver = tf.train.Saver(variables_to_restore)
downvote count: 0

http://stackoverflow.com/comment/91562283
has text: I don't think you are allowed to use numpy operation in the loss function. How about rewriting it by tensor operations?
score: 0
comment on: http://stackoverflow.com/q/52306842
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91518901
has text: Tbh I think they might be `nlog(n)` because I saw in the source there is a sort algorithm here https://github.com/numpy/numpy/blob/v1.15.0/numpy/lib/arraysetops.py#L376
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52285269
type: AnswerComment

http://stackoverflow.com/q/52335680
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/91618505
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91619518
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52339513
tagged with: python
has title: Better way to replace items in a list / dataframe
has comment: http://stackoverflow.com/comment/91642095
upvote count: 1
has body: I have to manually correct some data that may be misleading for a model otherwise. the logic is : if col("a") not empty &amp; col("b") negative =&gt; create col("ret_a") = 2*min(col("a")) - col("a") else col("ret_a") = col("a") The code i'm using and which does the job (but is not pretty) is : # a df["ret_a"] = np.where( np.logical_and(pd.notnull(df["a"]), df["b"] &lt; 0), 2*df["a"].min()- df["a"], df["a"]) The issue is that i have a bunch of conditions... and I don't think a condition like "&lt;0" can be stored in a dict{} to use pd.map() I then tried to build something using : df['i'] = np.select(conditions, choices,) with 'i' 'conditions' and 'choices': i= [ 'RETURN_COM_EQY_', # a 'INTEREST_COVERAGE_RATIO_', # b 'TOT_DEBT_TO_TOT_CAP_', # c 'TOT_DEBT_TO_TOT_EQY_', # d 'NET_DEBT_TO_EBITDA_', # e 'NET_INTEREST_COVERAGE_'] # f conditions = [ (df['TOTAL_EQUITY_'] &lt; 0), # a (df['IS_INT_EXPENSE_'] &lt; 0), # b (df['NET_DEBT_'] &lt; 0), # c (df['NET_DEBT_'] &lt; 0), # d (df['NET_DEBT_'] &lt; 0), # e1 (df['EBIT_'] &lt; 0), # e2 (df['IS_INT_EXPENSE_'] &lt; 0)] # f choices = [ 2*df["RETURN_COM_EQY_"].min() - df["RETURN_COM_EQY_"], # a 2*df["INTEREST_COVERAGE_RATIO_"].min() - df["INTEREST_COVERAGE_RATIO_"], # b 2*df["TOT_DEBT_TO_TOT_CAP_"].max() - df["TOT_DEBT_TO_TOT_CAP_"], # c 2*df["TOT_DEBT_TO_TOT_EQY_"].max() - df["TOT_DEBT_TO_TOT_EQY_"], # d 2*df["NET_DEBT_TO_EBITDA_"].max() - df["NET_DEBT_TO_EBITDA_"], # e1 2*df["NET_DEBT_TO_EBITDA_"].min() - df["NET_DEBT_TO_EBITDA_"], # e2 2*df["NET_INTEREST_COVERAGE_"].min() - df["NET_INTEREST_COVERAGE_"], # f ] the complete code for that operation would be : # a df["ret_mean_RETURN_COM_EQY_"] = np.where( np.logical_and(pd.notnull(df["mean_RETURN_COM_EQY_"]), df["mean_TOTAL_EQUITY_"] &lt; 0), 2*df["mean_RETURN_COM_EQY_"].min() - df["mean_RETURN_COM_EQY_"], df["mean_RETURN_COM_EQY_"]) # b df["ret_mean_INTEREST_COVERAGE_RATIO_"] = np.where( np.logical_and(pd.notnull(df["mean_INTEREST_COVERAGE_RATIO_"]), df["mean_IS_INT_EXPENSE_"] &l…
has comment: http://stackoverflow.com/comment/91618670
accepted answer: http://stackoverflow.com/a/52339513
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91618623
score: 1

http://stackoverflow.com/q/52371968
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52388581
tagged with: pandas
tagged with: shapely
tagged with: geopandas
answer count: 1
tagged with: python
favorite count: 0
upvote count: 2
has body: How would one go about merging two GeoDataFrames on both Point geometry and arbitrary other columns at the same time? I realize this task is ambiguous for all other geometries than Point because "equality" is not well defined for Lines and Polygons, but still. The following MWE throws an error if I simply try gdf2.merge(gdf), correctly complaining that unhashable type: 'Point'. How does one work around this? import geopandas as gpd import pandas as pd from io import StringIO import shapely df = pd.read_csv(StringIO(''' Name Value x y 'a' 1.5 0. 0. 'b' 22 0. 1. 'c' 0.2 0. 1. '''),sep=r"\s*",engine='python') df2 = pd.read_csv(StringIO(''' Name OtherValue x y 'a' 9.9 0. 0. 'b' 4.5 0. 1. 'c' 2e3 1. 1. '''),sep=r"\s*",engine='python') def dataframe_to_geodataframe(df): geometry = [shapely.geometry.Point(xy) for xy in zip(df.x, df.y)] df = df.drop(['x','y'], axis=1) gdf = gpd.GeoDataFrame(df, geometry=geometry) return gdf gdf = dataframe_to_geodataframe(df) gdf2 = dataframe_to_geodataframe(df2) gdf.merge(gdf2,how='left') Output would ideally be something like Name Value geometry OtherValue 0 'a' 1.5 POINT (0 0) 9.9 1 'b' 22.0 POINT (0 1) 4.5 2 'c' 0.2 POINT (0 1) NaN (of course depending on the how keyword). (I do realize this can be done easily after converting back to ordinary pandas DataFrames, but I feel there should be a way to do this without converting forth and back.)
has title: Merging GeoDataFrames on both Point geometry and other columns at the same time
accepted answer: http://stackoverflow.com/a/52388581
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/91667716
type: QuestionComment
has text: can you show your serializer ?
comment on: http://stackoverflow.com/q/52361744
score: 0
type: Comment

http://stackoverflow.com/q/52314094
favorite count: 0
has answer: http://stackoverflow.com/a/52314919
tagged with: seaborn
tagged with: boxplot
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: matplotlib
linked to: http://stackoverflow.com/q/41997493
has body: I am trying to make a boxplot of an 18 year record of monthly rainfall and flood frequency. i.e. each x tick is the month, and each x tick is associated with two boxplots, one of the rainfall and one of the flood frequency. So far I have managed to plot these using seaborn (see following code and image), however I do not know how to create the boxplot with two y axes, which I need because the scales for each variable differ. The data looks like this (largest value of flood_freq in the dataset is 7, not shown here): Group Rainfall Flood_freq 0 Jan 115.679997 0 1 Jan 72.929999 0 2 Jan 39.719999 0 3 Jan 46.799999 1 4 Jan 54.989998 0 ... 212 Dec 51.599998 0 213 Dec 45.359999 0 214 Dec 10.260000 0 215 Dec 52.709998 0 This is the code I have used: dd=pd.melt(FBPdf,id_vars=['Group'],value_vars=['Rainfall','Flood_freq'],var_name='Data') sns.boxplot(x='Group',y='value',data=dd,hue='Data') Which results in this: I have since looked on the seaborn documentation and it seems it does not permit 2 y axes (Seaborn boxplot with 2 y-axes). Is anyone able to offer potential alternatives for what I am trying to achieve? The solutions on the link above do not relate to this double-y-axis and grouped boxplot problem I have. Thank you very much in advance!
upvote count: 1
accepted answer: http://stackoverflow.com/a/52314919
type: Question
linked to: http://stackoverflow.com/q/47136855
has comment: http://stackoverflow.com/comment/91575839
answer count: 1
downvote count: 0
has title: Grouped boxplot with 2 y axes, 2 plotted variables per x tick

http://stackoverflow.com/q/52426837
has title: Python - Selenium going through array
score: 1
type: Question
tagged with: automation
answer count: 1
has comment: http://stackoverflow.com/comment/91797304
has comment: http://stackoverflow.com/comment/91797607
favorite count: 0
has answer: http://stackoverflow.com/a/52427371
tagged with: python
has comment: http://stackoverflow.com/comment/91797031
has comment: http://stackoverflow.com/comment/91800524
upvote count: 2
has body: I would like to do automated script. I define an array in start of the program. Later program is opening browser and search in google some specific word (for example apple), next program is clicking in first of string from array and close browser. Later is doing the same but it will click in second of word from array. My code: from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome("C:/Users/Daniel/Desktop/chromedriver.exe") driver.implicitly_wait(30) driver.maximize_window() hasla = ["ispot","myapple"] for slogan in hasla: driver.get("http://www.google.com") search_field = driver.find_element_by_id("lst-ib") search_field.clear() search_field.send_keys("apple") search_field.submit() name = driver.find_element_by_link_text(slogan) name.click() driver.quit() driver.implicitly_wait(10) When Im starting this program from console in windows. Program is opening browser, looking for apple click in ispot and clsoe browser but its not opening new browser and it not doing the same for next string in array. Any solution ? In console i have this: screen
type: UnansweredQuestion
tagged with: selenium
downvote count: 1

http://stackoverflow.com/q/52409689
type: Question
accepted answer: http://stackoverflow.com/a/52410069
has title: Join Dataframes in Pandas and Sum Columns
score: -1
answer count: 2
tagged with: pandas
has body: Lets say I have 2 dataframes in pandas. I want to perform a left join on these dataframes in a very specific way as follows, and the easiest way to explain is probably via an example. First dataframe: Date &nbsp; Col1 &nbsp;Col2 1/1 2/1 ... Second Dataframe: Date &nbsp; A &nbsp; B &nbsp; C 1/1 &nbsp; &nbsp; 90 &nbsp;0 &nbsp; 0 1/1 &nbsp; &nbsp; 0 &nbsp; 75&nbsp; 0 1/1 &nbsp; &nbsp; 73 &nbsp;0 &nbsp; 0 2/1 &nbsp; &nbsp; 0 &nbsp; &nbsp;0 &nbsp; 85 2/1 &nbsp; &nbsp; 0 &nbsp; &nbsp;0 &nbsp; 75 The dates in the first dataframe are unique and will be used to join to the second dataframe. Col1 and Col2 are not blank, but they are irrelevant for what I want to do. In second data frame, a date can appear multiple times, and exactly one of the columns A, B, and C contain a number greater than 0, with the other two containing 0. There could also be some extra columns which are irrelevant for what I want to do. I want to keep everything in the first dataframe and add columns A, B and C in such a way that the values in those columns would be the sum of all values on the given data in the second dataframe. So in the example above, I would want the output to look like this: Date &nbsp; Col1 &nbsp;Col2 &nbsp; A &nbsp; B &nbsp; C 1/1 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;163&nbsp;75 &nbsp; 0 2/1 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;0 &nbsp;&nbsp;160 ... I have looked at the pandas join function but it doesn't seem to give the option to sum columns in the way that I want. Is there any other way to achieve such a result? I realise I could probably write a for loop to do this, but I was hoping there might be a more efficient way.
upvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52410069
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52410091
tagged with: data-cleaning
has answer: http://stackoverflow.com/a/52410091
downvote count: 1

http://stackoverflow.com/comment/91494885
type: Comment
comment on: http://stackoverflow.com/q/52273257
type: QuestionComment
score: 0
has text: Possible duplicate of [Adding a y-axis label to secondary y-axis in matplotlib](https://stackoverflow.com/questions/14762181/adding-a-y-axis-label-to-secondary-y-axis-in-matplotlib)

http://stackoverflow.com/q/52372170
has comment: http://stackoverflow.com/comment/91697042
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/91695342
linked to: http://stackoverflow.com/q/51114464
type: Question
tagged with: heroku
has body: Bot Code : import discord import youtube_dl from discord.ext import commands client = commands.Bot(command_prefix = "e!") players = {} @client.event async def on_ready(): print("Bot çevrimiçi!") @client.command(pass_context = True) async def baglan(ctx): channel = ctx.message.author.voice.voice_channel await client.join_voice_channel(channel) @client.command(pass_context = True) async def oynat(ctx, url): server = ctx.message.server voice_client = client.voice_client_in(server) player = await voice_client.create_ytdl_player(url) players[server.id] = player player.start() client.run('') Error : packages/discord/ext/commands/core.py", line 54, in wrapped raise CommandInvokeError(e) from e discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'create_ytdl_player' The bot is normally running on my own PC but I am currently running on a Heroku server. The bot joins the channel but doesn't play the audio. I couldn't figure out a way how to solve this problem Thank you in advance for your help.
has comment: http://stackoverflow.com/comment/91688924
has comment: http://stackoverflow.com/comment/91699154
has comment: http://stackoverflow.com/comment/91870047
has comment: http://stackoverflow.com/comment/91696105
has comment: http://stackoverflow.com/comment/91697690
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91695374
tagged with: discord
has title: Heroku on Discord Bot youtube_dl and discord[voice] error

http://stackoverflow.com/comment/91701828
has text: So, you want a list of arrays? Because a single array as output isn't possible.
comment on: http://stackoverflow.com/q/52378730
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52346758
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91644417
linked to: http://stackoverflow.com/q/6763086
type: Question
has answer: http://stackoverflow.com/a/52346840
has body: I have installed python 3.7, I'm really new to this and read you can run a script with a txt entry in PowerShell (already did environment path configs). I opened PowerShell and type: - cd [Python script directory] - python main_1.py It should run but gives an error in return, here is the error. Any help will be appreciated.
answer count: 1
tagged with: powershell
score: 0
tagged with: python-3.7
tagged with: python
has title: Can't run python script with an txt entry in powershell [Errno 22]

http://stackoverflow.com/comment/91712533
has text: @Stick1000 better not saying you got an error. Instead show the error, please (as an edit in your question). And also you mixed 4 spaces with 8 spaces indendation, see [editing-help](https://stackoverflow.com/editing-help). -- `space` or `side` is a string which needs to be converted to int.
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52384142

http://stackoverflow.com/a/72090539
type: Answer
upvote count: 13
score: 13
has body: I haven't spent the time to fully appreciate this problem, but as I understand this is caused by multiple conflicting versions of some plugin in the environment. I tried installing building opencv-python but there were errors with that approach. Another suggestion is to change your import order, but I've had mixed success with that, and I couldn't get it to work on a project today. But I found a workaround that worked for me. Install opencv-python-headless instead of opencv-python. This will avoid installing the conflicting plugins. It may not work for you depending on what features of opencv you need. $ pip uninstall opencv-python $ pip install opencv-python-headless
answers question: http://stackoverflow.com/q/52337870
downvote count: 0

http://stackoverflow.com/comment/91677978
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52366314
has text: Is that error showing on your deployment server then? Or is it on your local machine?

http://stackoverflow.com/a/52419612
answers question: http://stackoverflow.com/q/52412767
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91804024
has comment: http://stackoverflow.com/comment/91911568
has comment: http://stackoverflow.com/comment/91839305
type: Answer
has comment: http://stackoverflow.com/comment/91922891
has comment: http://stackoverflow.com/comment/91875200
accepted answer of: http://stackoverflow.com/q/52412767
has body: I suspect that the issue lies in your label encoding. You need to use the very same encoder in order for your labels to match: labelencoder_Y = LabelEncoder() x = labelencoder_Y.fit_transform(label_train) label_cat_train = np_utils.to_categorical(x, num_classes=num_classes) y = labelencoder_Y.transform(label_test) # do not fit again, but reuse the encoder label_cat_test = np_utils.to_categorical(y, num_classes=num_classes) Perhaps you also need to check your category labels. Above, you write that mega should go to 3 but goes to 45 which does not even exist but state that num_classes = 54 which is also the size of your output layer.
score: 0
has comment: http://stackoverflow.com/comment/91801940

http://stackoverflow.com/a/52282227
downvote count: 0
answers question: http://stackoverflow.com/q/52282197
type: Answer
upvote count: 2
score: 2
has body: I'm guessing you are only concerned with rows where there was a flood, i.e. Size != 0. You could filter out those rows after applying the code below. Given a DataFrame rain as follows: date Size ppt 2017-09-13 0.0 0.000000 2017-09-14 0.0 34.709998 2017-09-15 0.0 0.000000 2017-09-16 0.0 0.000000 2017-09-17 0.0 0.000000 2017-09-18 0.0 0.600000 2017-09-19 3.0 157.439998 ## 7-day cumulative precipitation rain['ppt_7day'] = rain['ppt'].rolling(7).sum() ## 3-day cumulative precipitation rain['ppt_3day'] = rain['ppt'].rolling(3).sum() Output: date size ppt ppt_7day ppt_3day 0 2017-09-13 0 0 NaN NaN 1 2017-09-14 0 34.71 NaN NaN 2 2017-09-15 0 0 NaN 34.709998 3 2017-09-16 0 0 NaN 34.709998 4 2017-09-17 0 0 NaN 0.000000 5 2017-09-18 0 0.6 NaN 0.600000 6 2017-09-19 3 157.43 192.739998 158.030000

http://stackoverflow.com/comment/91704184
score: 0
has text: @rogan, you are correct sir, my apologies, I have updated my post
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52379836

int
tags question: http://stackoverflow.com/q/52390457
tags question: http://stackoverflow.com/q/52413123
type: Tag
tags question: http://stackoverflow.com/q/52303407
tags question: http://stackoverflow.com/q/52322843
tags question: http://stackoverflow.com/q/52285071
tag name: int
tags question: http://stackoverflow.com/q/52415497
tags question: http://stackoverflow.com/q/52335920
tags question: http://stackoverflow.com/q/52345762

http://stackoverflow.com/q/52374190
has answer: http://stackoverflow.com/a/52374449
answer count: 3
tagged with: pandas
favorite count: 0
accepted answer: http://stackoverflow.com/a/52374254
upvote count: 2
has answer: http://stackoverflow.com/a/52374370
tagged with: python
score: 2
type: AnsweredQuestion
has body: I have the following dataframe in pandas: target A B C 0 cat bridge cat brush 1 brush dog cat shoe 2 bridge cat shoe bridge Desired output: target A B C D 0 cat bridge cat brush B 1 brush dog cat shoe None 2 bridge cat shoe bridge C I need to know which column match my target column (col D). I have seen the previous post 43093394, but it's not enough for me to know if the columns match or not, i need to know which column match which target, and if none match. The same problem is posted here 40320476, but in sql so it didn't help me. Looking forward to your input, thanks!
possible better answer: http://stackoverflow.com/a/52374370
type: Question
has answer: http://stackoverflow.com/a/52374254
has title: Pandas - Check which column match another column - not boolean
downvote count: 0

http://stackoverflow.com/a/52324987
answers question: http://stackoverflow.com/q/52324902
score: 1
has comment: http://stackoverflow.com/comment/91597163
has comment: http://stackoverflow.com/comment/91597200
has comment: http://stackoverflow.com/comment/91597413
has comment: http://stackoverflow.com/comment/91597318
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91597388
has comment: http://stackoverflow.com/comment/91597262
has comment: http://stackoverflow.com/comment/91597229
type: Answer
has body: try this, l=df2['A'].unique().tolist() reg='|'.join(l) print df1[df1['C'].str.contains(reg)==False] Output: A C 1 3 bar 3 6 bat For NaN removal l=df2[df2['A'].notnull()]['A'].unique().tolist()
has comment: http://stackoverflow.com/comment/91597352
upvote count: 1
has comment: http://stackoverflow.com/comment/91597316
has comment: http://stackoverflow.com/comment/91597145
has comment: http://stackoverflow.com/comment/91597408
accepted answer of: http://stackoverflow.com/q/52324902

http://stackoverflow.com/comment/91504299
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52277772
type: QuestionComment
has text: I felt I was pretty clear... I apologize, It is not a "reverse instance". I said "requiring me to reverse an instance of an object (firstObj01(str) -> secondobj02(str)). Implying the second object needs to come first. So, is there a way to accept two pieces of information (color01, color02) pass them both in. alter it so it only accepts and sends out color02.

http://stackoverflow.com/comment/91774664
has text: It turns out that using dict comprehensions for this is just a horrible trap. It seems like it should be a good idea at first, but a dict comprehension will never be as efficient as a normal loop for this.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52415559

http://stackoverflow.com/a/52356579
has comment: http://stackoverflow.com/comment/91685763
has comment: http://stackoverflow.com/comment/91739260
has comment: http://stackoverflow.com/comment/91793154
accepted answer of: http://stackoverflow.com/q/52324820
upvote count: 2
has comment: http://stackoverflow.com/comment/91664865
has comment: http://stackoverflow.com/comment/91664528
has comment: http://stackoverflow.com/comment/91738780
has comment: http://stackoverflow.com/comment/91739110
has comment: http://stackoverflow.com/comment/91685781
has comment: http://stackoverflow.com/comment/91664816
has body: I'm showing you how to solve the general problem with threads only, because that is what you tried first and your example doesn't bring up the need for a child-process. In the example below your dllapi class is named Zoo and it's subclassing threading.Thread, adding some methods to allow execution control. It takes some data upon initialization and its cycle-method simply iterates repeatedly over this data and just counts how many times it has seen the specific item. import time import logging from queue import Queue from threading import Thread from itertools import count, cycle class Zoo(Thread): _ids = count(1) def __init__(self, cmd_queue, data, *args, log_level=logging.DEBUG, **kwargs): super().__init__() self.name = f'{self.__class__.__name__.lower()}-{next(self._ids)}' self.data = data self.log_level = log_level self.args = args self.kwargs = kwargs self.logger = self._init_logging() self.cmd_queue = cmd_queue self.data_size = len(data) self.actual_item = None self.iter_cnt = 0 self.cnt = count(1) self.cyc = cycle(self.data) def cycle(self): item = next(self.cyc) if next(self.cnt) % self.data_size == 0: # new iteration round self.iter_cnt += 1 self.actual_item = f'{item}_{self.iter_cnt}' def run(self): """ Run is the main-function in the new thread. Here we overwrite run inherited from threading.Thread. """ while True: if self.cmd_queue.empty(): self.cycle() time.sleep(1) # optional heartbeat else: self._get_cmd() self.cmd_queue.task_done() # unblocks prompter def stop(self): self.logger.info(f'stopping with actual item: {self.actual_item}') # do clean up raise SystemExit def pause(self): self.logger.info(f'pausing with actual item: {self.actual_item}') self.cmd_queue.task_done() # unblocks producer joining the queue self._get_cmd() # just wait blockingly until next command def resume(self): self.logger.info(f'resuming with actual item: {self.actual_item}') def report(self): self.logger.info(f'reporting with actual item: {self.actual_item}') print(f'completed…
has comment: http://stackoverflow.com/comment/91684300
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91738956
answers question: http://stackoverflow.com/q/52324820
type: Answer

http://stackoverflow.com/a/52347761
answers question: http://stackoverflow.com/q/52347671
has body: If I infer correctly then you want to take each input, square it, average the sum and square root that sum. Remember that when averaging (finding mean), only divide by the sum at the end: def rms(): total = 0.0 count = 0 while True: x = input('enter value (enter nothing to stop):') if x.strip() == '': break count += 1 total += float(x) ** 2 print('mean square root is:', math.sqrt(total/count)) # return math.sqrt(total / count)
type: Answer
downvote count: 1
score: -1
upvote count: 0

http://stackoverflow.com/q/52417801
tagged with: pyspark
has comment: http://stackoverflow.com/comment/91779061
has comment: http://stackoverflow.com/comment/91779069
type: Question
answer count: 2
tagged with: apache-spark
favorite count: 0
has answer: http://stackoverflow.com/a/52419272
tagged with: python
has title: Sum a column in dataframe and return results as int
type: UnansweredQuestion
upvote count: 3
downvote count: 2
has answer: http://stackoverflow.com/a/52420325
has comment: http://stackoverflow.com/comment/91778931
has body: I have a pyspark dataframe with a column of numbers(amount). I need to sum that column(amount) and then have the result return as an int in a python variable. Dataset looks like this: date,p1id,p2id,amount,p3id 1/1/2013,U2_P1,p@c.com,100,P_P With the date grouping and aggregation by sum. groupby_revenue = df.groupby(['date']).sum() print(groupby_revenue) output: DataFrame[visitdate: string] original output: 1/1/2013 13000 1/1/2014 16090 1/1/2015 17330
linked to: http://stackoverflow.com/q/46552161
score: 1

http://stackoverflow.com/comment/91616429
comment on: http://stackoverflow.com/a/52334173
type: AnswerComment
score: 0
has text: One thing to try from that other question is trying to purge Spyder. You could also try checking "conda install -c anaconda spyder". What version of Spyder are you trying to use? Looks like the most recent is 3.3.1.
type: Comment

http://stackoverflow.com/q/52410975
favorite count: 0
has title: Hypothesis strategy generating inf when specifically asked not to
tagged with: python
possible better answer: http://stackoverflow.com/a/52411325
has body: from functools import partial import hypothesis as h import hypothesis.strategies as hs import hypothesis.extra.numpy as hnp import numpy as np floats_notnull = partial(hs.floats, allow_nan=False, allow_infinity=False) complex_notnull = partial(hs.complex_numbers, allow_nan=False, allow_infinity=False) data_strategy_real = hnp.arrays( np.float64, hs.tuples(hs.integers(min_value=2, max_value=50), hs.integers(min_value=2, max_value=5)), floats_notnull() ) data_strategy_complex = hnp.arrays( np.complex64, hs.tuples(hs.integers(min_value=2, max_value=50), hs.just(1)), complex_notnull() ) data_strategy = hs.one_of(data_strategy_real, data_strategy_complex) If you run data_strategy.example() a couple times, you'll notice that some of the values in the result have infinite real or imaginary parts. My intention here was to specifically disallow infinite or NaN parts. What am I doing wrong? Update: if I use data_strategy = hs.lists(complex_notnull, min_size=2, max_size=50) and convert that to an array inside my test, the problem appears to go away. Are the complex numbers overflowing? I'm not getting the usual deprecation warning about overflow from Hypothesis. And if I use data_strategy = data_strategy_real no infs appear.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52435192
accepted answer: http://stackoverflow.com/a/52435192
type: Question
upvote count: 4
tagged with: numpy
answer count: 2
downvote count: 0
score: 4
has answer: http://stackoverflow.com/a/52411325
tagged with: python-hypothesis

http://stackoverflow.com/comment/91786644
score: 1
comment on: http://stackoverflow.com/q/52420470
has text: @Marouen, I pasted the code which helps calculate the slope.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91802405
type: QuestionComment
comment on: http://stackoverflow.com/q/52429283
score: 0
has text: hm it might be in an iframe that you need to "focus" on first
type: Comment

http://stackoverflow.com/q/52303086
score: -1
has answer: http://stackoverflow.com/a/52303167
linked to: http://stackoverflow.com/q/10542240
upvote count: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/10542240
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91553945
has body: I'm trying to figure out if any index of a list of data does not meet the criteria I have. I imagine that I would have to use the np.where function but I don't know how I would match each index to see if it meets or does not meet the criteria. I need to make sure that the data is within certain values. For example, the condition is 1.5 &lt; x &lt; 4.9 so how would I check if anywhere in a list, it does not meet the condition?
downvote count: 1
has title: Check if index in list meets criteria
type: Question
tagged with: numpy

http://stackoverflow.com/q/52378090
answer count: 0
type: UnansweredQuestion
score: 0
has title: Alternatives to linear / bilinear interpolation for extrapolation on 2D array
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91738098
has body: I’m searching for a way to interpolate a portion of a 2d array, likely with a power law approach though perhaps more knowledgeable users have other suggestions more suited to the data. In truth, I'm at a loss for how to even implement a power law approach, but my (poor) intuition is that it might do the trick. I have an array which has a roughly circular region of masked data, similar to the example provided. I would like to interpolate across this area using the surrounding data to get an estimate for the empty region. The complication however is that on one edge (right side here) there is an additional component to the surrounding data which I know has fairly sharp borders, likely fit with a power law. So far I have tried both linear and bicubic interpolation methods however these approaches fail because they over-estimate the contribution from the region of excess on the right. annulus= np.array([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 16.0, 16.0, 17.0, 18.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 15.0, 15.0, 16.0, 16.0, 17.0, 18.0, 19.0, 19.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 15.0, 15.0, 15.0, 16.0, 17.0, 17.0, 18.0, 19.0, 20.0, 21.0, 0.0, 0.0, 0.0], [0.0, 0.0, 15.0, 15.0, 16.0, 16.0, 0.0, 0.0, 0.0, 20.0, 21.0, 22.0, 23.0, 0.0, 0.0], [14.0, 14.0, 15.0, 15.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 22.0, 23.0, 25.0, 26.0, 0.0], [14.0, 14.0, 15.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 24.0, 26.0, 28.0, 30.0], [13.0, 14.0, 14.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 26.0, 28.0, 30.0, 33.0], [13.0, 14.0, 14.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 25.0, 28.0, 30.0, 33.0, 0.0], [13.0, 13.0, 14.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 24.0, 27.0, 30.0, 33.0, 0.0, 0.0], [13.0, 13.0, 14.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 26.0, 28.0, 32.0, 35.0, 0.0, 0.0], [12.0, 13.0, 14.0, 15.0, 0.0, 0.0, 0.0, 0.0, 24.0, 27.0, 30.0, 34.0, 0.0, 0.0, 0.0], [0.0, 13.0, 14.0, 15.0, 16.0, 0.0, 0.0, 22.0, 24.0, 27.0, 31.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 15.0, 16.0, 18.0, 19.0, 22.0, 25.0, 28.0, 32.0, 0.0, 0.0, …
has comment: http://stackoverflow.com/comment/91709858
has comment: http://stackoverflow.com/comment/91705464
tagged with: python
tagged with: extrapolation
tagged with: interpolation

http://stackoverflow.com/a/52363305
answers question: http://stackoverflow.com/q/52363255
type: AcceptedAnswer
type: Answer
upvote count: 4
downvote count: 0
has body: Use list comprehension with f-strings: b = [f'{i+1}-{j+1}' for i, j in zip(a[:-1], a[1:])] print (b) ['0-36', '36-72', '72-108', '108-144', '144-180', '180-216', '216-252', '252-288', '288-324', '324-360'] a += 1 b = [f'{i}-{j}' for i, j in zip(a[:-1], a[1:])]
accepted answer of: http://stackoverflow.com/q/52363255
score: 4

http://stackoverflow.com/a/52280428
has comment: http://stackoverflow.com/comment/91529242
type: AcceptedAnswer
downvote count: 0
has body: You have to tell snakemake to use conda on the command line: snakemake --use-conda The doc states: CONDA: --use-conda If defined in the rule, run job in a conda environment. If this flag is not set, the conda directive is ignored. The error you're having is because the shell command you're running does not exist. Snakemake executes the command source activate /data/projects/testproject/.snakemake/conda/805d8d2a; set -euo pipefail; emirge I think your environment is correctly created and activated but it is the command emirge that is not found.
type: Answer
answers question: http://stackoverflow.com/q/52277725
has comment: http://stackoverflow.com/comment/91512616
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52277725

http://stackoverflow.com/comment/91718222
has text: It didn't work. Now, I don't get status 403 error but my comment doesn't show.
comment on: http://stackoverflow.com/a/52386821
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91742152
type: Comment
type: QuestionComment
has text: yes, i want to remove an element if it is subset of other element. Do you have any idea?
score: 0
comment on: http://stackoverflow.com/q/52399091

http://stackoverflow.com/q/52388552
tagged with: fuzzy-comparison
tagged with: python
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52642484
upvote count: 1
type: AnsweredQuestion
score: 1
has body: I am trying to write some code that will take two lists of names from two csv files, and use the fuzzywuzzy library to find the most similar comparisons and export those to a third csv file. Two problems with my code: Firstly, it is not optimizing, just exporting all the ratios I am calculating. Secondly, it is all exporting to a single column rather than sticking all values in their own relevant columns i.e. CSV1, CSV2, Fuzz Ratio from fuzzywuzzy import fuzz import csv with open('Documents/test_CSV_1.csv', 'r') as t1, open('Documents/test_CSV_2.csv', 'r') as t2: fileone = t1.readlines() filetwo = t2.readlines() with open('update.csv', 'w') as outFile: for i in fileone: for j in filetwo: outFile.write(i + j+ str(fuzz.ratio(i,j)) + ", " + "\n")
type: Question
has title: How to iterate over Max Values for Fuzz Ratio and export to new CSV file
has answer: http://stackoverflow.com/a/52642484
answer count: 1
downvote count: 0
tagged with: fuzzywuzzy

http://stackoverflow.com/q/52274201
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52274234
type: Question
duplicate of: http://stackoverflow.com/q/75666408
has body: I am trying to write a program that will receive inputs, run some calculations and store them in a list before adding the elements of the list. but I keep getting the error: wh_list = wh_list.append(wh) AttributeError: 'NoneType' object has no attribute 'append' code: wh_list = [] u = len(wh_list) if u &lt;= 1: while True: inp = input("Y or N:") B = int(input("B value:")) C = int(input("C value:")) D = int(input("D value:")) wh = B * C * D wh = int(wh) wh_list = wh_list.append(wh) if inp == "Y": break else: Ewh = sum(wh_list) print(Ewh)
has comment: http://stackoverflow.com/comment/91495680
linked to: http://stackoverflow.com/q/3840784
score: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/11205254
has title: python how to populate a list in loop
has answer: http://stackoverflow.com/a/52274234
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/a/75142163
has body: I also had this issue and it's 2023! All I can tell you is what I did to fix it. I tried the other solutions listed in this post (at least the ones I looked at) and they didn't work. What I did was I copied the venv file in my project (for safekeeping) and then moved it elsewhere. I deleted the venv file in my project after making my backup and I deleted the interpreter that I had been trying to use. From there I opened up File -&gt; Settings -&gt; Python Interpreter -&gt; and since there was now no interpreter and no venv folder I created the interpreter again. Make sure to list the proper path to the version of the python exe you want to use! From there you pretty much just apply your changes and you will see it pop up with some prompts. It will create a new venv folder for you, just accept the prompts and it worked for me.
answers question: http://stackoverflow.com/q/52404529
score: 0
type: Answer

http://stackoverflow.com/comment/91835273
type: Comment
type: QuestionComment
has text: @star_trac I had seen it, I'm thinking where the problem is. The port is correct, the program is correct. I think you can test with pyserial to figure out the problem. try to make a small program that import pyserial and write this string to the device: "010307D800024544". After than use `time.sleep(1)` and after that the read command and see if you receive response
comment on: http://stackoverflow.com/q/52392398
score: 0

pytorch
tags question: http://stackoverflow.com/q/52317407
tags question: http://stackoverflow.com/q/52277083
tags question: http://stackoverflow.com/q/52361735
tags question: http://stackoverflow.com/q/52310905
tags question: http://stackoverflow.com/q/52288635
tags question: http://stackoverflow.com/q/52420385
tag name: pytorch
type: Tag
tags question: http://stackoverflow.com/q/52370008
tags question: http://stackoverflow.com/q/52358887
tags question: http://stackoverflow.com/q/52324713
tags question: http://stackoverflow.com/q/52282971
tags question: http://stackoverflow.com/q/52425824
tags question: http://stackoverflow.com/q/52306279
tags question: http://stackoverflow.com/q/52374287
tags question: http://stackoverflow.com/q/52298179
tags question: http://stackoverflow.com/q/52362011
tags question: http://stackoverflow.com/q/52428472
tags question: http://stackoverflow.com/q/52344834
tags question: http://stackoverflow.com/q/52408753
tags question: http://stackoverflow.com/q/52374062
tags question: http://stackoverflow.com/q/52391648
tags question: http://stackoverflow.com/q/52384628
tags question: http://stackoverflow.com/q/52342514
tags question: http://stackoverflow.com/q/52287254
tags question: http://stackoverflow.com/q/52411346

http://stackoverflow.com/comment/91772092
type: AnswerComment
type: Comment
has text: seems working on webpage tester - I will update you later -- thank you
comment on: http://stackoverflow.com/a/52413459
score: 0

http://stackoverflow.com/a/52338514
type: Answer
has comment: http://stackoverflow.com/comment/91628160
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52329817
downvote count: 0
has body: If you want to do your own filtering change describe_images(Filters...) to describe_images(). Note: describe_images() returns a lot of data. Be prepared to wait a few minutes. On my system 89,362 images for us-east-1. import boto3 client = boto3.client('ec2') image_count = [] response = client.describe_images(Filters=[{'Name': 'state', 'Values': ['available']}]) if 'Images' in response: for img in response['Images']: image_count.append(img) print("img count -&gt;" + str(len(image_count)))

http://stackoverflow.com/q/52280855
type: UnansweredQuestion
type: Question
tagged with: threadpool
tagged with: python-multiprocessing
tagged with: pool
has body: One part of my application is producing a lot of tasks(essentially dictionary). Each task(dictionary) is essentially a the POST data to a third-party API. Hence i wanted to multiprocess the execution of these tasks. What I thought was: Create a multiprocess Pool which would read the tasks from a queue and send them to the function(FN) which would then call the API. The issue is that: I want that I should be able to keep pushing tasks in the queue which are continuously read by the Pool. But this is not happening. On updating the queue(that is pushing tasks to queue), the function(FN) is not called. Below is the code: from multiprocessing import Pool, Queue, cpu_count, Manager class PoolThread: running = False def __init__(self, a): self.initialisepool() @staticmethod def poolfunction(arg): print(arg) print(arg.qsize()) return "processed" #return arg * arg def callb(self, a): print(a) def errcall(self, b): print(b) def initialisepool(self): print(cpu_count()) self.p = Pool(cpu_count()) self.m = Manager() self.q = self.m.Queue() self.p.map_async(self.poolfunction, (self.q,), cpu_count(), self.callb, self.errcall) def readcache(self): if not self.running: self.running = True self.threadedhandling() def threadedhandling(self): tasks = self.gettasks() # Push to queue self.q.put(tasks) def gettasks(self): dict_r = {'randomval' : 2} return dict_r pt = PoolThread() pt.readcache() In the above the pool is initialized. However, on calling the readcache(), the poolfunction is not re-called. If the queue is populated with data before self.p.map_async(self.poolfunction, (self.q,), cpu_count(), self.callb, self.errcall) then only the poolfunction is called. My requirement is that : I should keep pushing into the queue and the queue is automatically monitored to call the poolfunction. how can i monitor the result of the poolfunction? The poolfunction should only get one argument at a time from the queue which is passed to the API. once the response is attained, i want to read the …
downvote count: 0
favorite count: 0
tagged with: python
score: 2
has title: Keep adding tasks in multiprocessing pool to be read by pool
answer count: 0
upvote count: 2

http://stackoverflow.com/comment/91676046
score: 0
has text: Ok I will try it out.. May be some mistake on my side, I forgot something....
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52364673

http://stackoverflow.com/comment/91800160
comment on: http://stackoverflow.com/q/52343989
score: 0
type: Comment
type: QuestionComment
has text: Neither can I with TF 1.8 (same environment).

http://stackoverflow.com/comment/91792733
type: AnswerComment
type: Comment
has text: Thank you, that's exactly what I want
comment on: http://stackoverflow.com/a/52411889
score: 0

http://stackoverflow.com/comment/134824196
has text: did you manage to solve your issue? if yes how i'm running on same :( with postgresql
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52410714

http://stackoverflow.com/q/52272005
has title: Generalisation using dictionary
accepted answer: http://stackoverflow.com/a/52272100
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 0
type: Question
has comment: http://stackoverflow.com/comment/91491150
has body: I want to improve and shorten the following function using a dictionary: def loop_solution(filename1=None,filename2=None,filename3=None,filename4=None): if (filename1!=None): im1=import_file_astro(filename1) if (filename2!=None): im2=import_file_astro(filename2) if (filename3!=None): im3=import_file_astro(filename3) if (filename4!=None): im4=import_file_astro(filename4) I thought of using the following snipet: mydic={'im'+str(i):import_file_astro(filename1) for i in range(1,5) if filename1!=None} but of course I need a way to loop through the filenames. I've thought of using exec but I've read that it should be avoided. Any help or suggestion is greatly appreciated.
tagged with: function
answer count: 1
has answer: http://stackoverflow.com/a/52272100

http://stackoverflow.com/a/54833083
has comment: http://stackoverflow.com/comment/103086636
downvote count: 0
has body: All the code worked until I introduced the discord.Embed part. I think I know why...it might be outdated. Here, try using the following command: pip install --upgrade discord.py
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52356064

http://stackoverflow.com/a/52329224
answers question: http://stackoverflow.com/q/52328800
type: Answer
upvote count: 1
has body: I suggest writing all three to the same file You could get common keys by doing something like: common_keys = set(score_dict.keys()+post_dict.keys()+comment_dict.keys()) for key_ in common_keys: val_score = score_dict.get(key_, some_default_value) post_score = post_dict.get(key_, some_default_value) comment_score = comment_dict.get(key_, some_default_value) # print key and vals to csv as before
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91605642

http://stackoverflow.com/q/52346002
tagged with: python
has answer: http://stackoverflow.com/a/52355968
has body: Hoping someone on here can help, I'm struggling to get prediction values back to "unscaled" values. I'm using StandardScaler() in sklearn.preprocessing . My dataset is a numpy array with 4 columns (called dataset). I've tried: # full dataset scaled, then split to X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X,Y, test_size = 0.4) # model looks good but can't inverse_transform(Y_pred) obviously. Y_pred = adam.predict(X_test) scaled X_train, X_test # individually # model comes out bad scaled X_train, X_test, Y_train, Y_test # individually # model comes out bad Am I applying scaling in an incorrect way? Any suggestions on how to inverse scale of Y_pred on scaled model run? Thanks for any help on this!
tagged with: machine-learning
type: Question
has comment: http://stackoverflow.com/comment/91639831
has comment: http://stackoverflow.com/comment/91673777
has answer: http://stackoverflow.com/a/52346253
upvote count: 2
score: 0
downvote count: 2
answer count: 2
tagged with: scikit-learn
favorite count: 0
has comment: http://stackoverflow.com/comment/91639839
type: UnansweredQuestion
has title: Scikit-learn Scaling Question (inverse_transform)

http://stackoverflow.com/comment/91577292
comment on: http://stackoverflow.com/a/52304481
type: Comment
has text: @sphinxI ran the following: mulIndexDataFrame = df['ErrorMessage'].str.extractall(r"---> ([^:]+): ") and it created a new dataframe (as expected) of size (0,1) and it's empty. That is not expected, I imagine. I think there must be something wrong with my original dataframe that I created by reading in the .csv, but I am not sure how to troubleshoot that.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52328683
score: 0
tagged with: string
tagged with: unicode
has title: Can't print string extract from images using both pyocr and pytesseract
has body: I want to extract the Thai text from images using PyOCR but I can't print the string. Here's the code. #!/usr/bin/env python # -*- coding: utf-8 -*- from PIL import Image import sys import pyocr import pyocr.builders tools = pyocr.get_available_tools() if len(tools) == 0: print("No OCR tool found") sys.exit(1) print("Will use tool '%s'" % (tool.get_name())) langs = tool.get_available_languages() print("Available languages: %s" % ", ".join(langs)) lang = langs[3] print("Will use lang '%s'" % (lang)) txt = tool.image_to_string( Image.open('test2.png'), lang=lang, builder=pyocr.builders.TextBuilder() ) print(txt) And it gives me this error. Traceback (most recent call last): File "tess.py", line 29, in print(txt) File "C:\Python34\lib\encodings\cp437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-2: character maps to Here's the code form pytesseract which gives the same error. from PIL import Image import pytesseract text = pytesseract.image_to_string(Image.open('test2.png'), lang='tha') print(text) After I tried encoding it with utf-8. It gives me this output. b'\xe0\xb8\x99\xe0\xb8\xb2\xe0\xb8\xa2 \xe0\xb8\xa0\xe0\xb8\x84\xe0\xb8\x9e\xe0\xb8\x87\xe0\xb8\xa9\xe0\xb9\x8c \xe0\xb8\xaa\xe0\xb8\xad\xe0\xb8\x99\xe0\xb9\x80\xe0\xb8\xad\xe0\xb8\x81' Here's the images that I use.
has comment: http://stackoverflow.com/comment/91608457
tagged with: python
tagged with: ocr
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91607393
tagged with: unicode-string
has comment: http://stackoverflow.com/comment/91604202
has comment: http://stackoverflow.com/comment/91608394
has comment: http://stackoverflow.com/comment/91607243
type: Question

http://stackoverflow.com/a/52418995
has body: As you say none of the azure commands have been successful. So I suggest you reinstall the Azure CLI, you can follow Install Azure CLI 2.0. Additional, install Azure CLI through python: pip install --pre --user azure-nspkg pip install --pre --user azure-multiapi-storage pip install azure-cli For more details, follow this link. About create a container for the storage. You can do that with the CLI command here: az storage container create --name containerName --account-name accountName --account-key accountKey And the container name has the limitation here: A container organizes a set of blobs, similar to a folder in a file system. All blobs reside within a container. A storage account can contain an unlimited number of containers, and a container can store an unlimited number of blobs. Note that the container name must be lowercase. So you should pay attention to it. Hope this will help you.
answers question: http://stackoverflow.com/q/52409379
accepted answer of: http://stackoverflow.com/q/52409379
type: AcceptedAnswer
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/93077874

http://stackoverflow.com/a/52380138
has body: The escape code \u00b2 is a single character; you want something like &gt;&gt;&gt; print(eval(r'"\u00b' + str(2) + '"')) ² Less convolutedly, &gt;&gt;&gt; print(chr(0x00b2)) ² This only works for superscript 2 and 3, though; the other Unicode superscripts are in a different code block. &gt;&gt;&gt; for i in range(10): ... if i == 1: ... print(chr(0x00b9)) ... elif 2 &lt;= i &lt;= 3: ... print(chr(0x00b0 + i)) ... else: ... print(chr(0x2070 + i)) ⁰ ¹ ² ³ ⁴ ⁵ ⁶ ⁷ ⁸ ⁹
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52379803
answers question: http://stackoverflow.com/q/52379803
upvote count: 3

http://stackoverflow.com/a/52492419
upvote count: 4
answers question: http://stackoverflow.com/q/52360313
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52360313
has body: It seems it's a compatibility issue between BlueBorne and Scapy. You (most likely) have installed the latest Scapy version (v2.4.0), which dropped the fields kwarg from scapy.layers.bluetooth.HCI_ACL_Hdr's initializer, while BlueBorne (l2cap_infra.py, and possibly others) was not updated (or branched) accordingly. The latest version that still has it is v2.3.3 ([GitHub]: secdev/scapy - (v2.3.3) scapy/scapy/layers/bluetooth.py). Possible solutions: Uninstall your current Scapy version (pip uninstall scapy) and install v2.3.3 (pip install scapy==2.3.3). Probably, this is the simplest (and most suitable) for you ([PyPI]: scapy 2.3.3) Submit a bug to BlueBorne and wait for them to add support for newer Scapy versions Fix it yourself ("fields" (v2.3.3) to "PB" + "BC" (v2.4.0) kwargs conversion), and maybe submit a patch :)
score: 4

http://stackoverflow.com/comment/91694077
type: Comment
comment on: http://stackoverflow.com/a/52374254
has text: @sand then you should do df[ ['A','F'] ]
score: 0
type: AnswerComment

http://stackoverflow.com/q/52411660
score: 4
has body: looking for help applying a regex function that finds a string that starts with 5 and is 7 digits long. this is what i have so far based on my searches but doesn't work: import re string = "234324, 5604020, 45309, 45, 55, 5102903" re.findall(r'^5[0-9]\d{5}', string) not sure what i'm missing. thanks
answer count: 3
has answer: http://stackoverflow.com/a/52411730
has answer: http://stackoverflow.com/a/52411707
favorite count: 0
has answer: http://stackoverflow.com/a/52411700
has comment: http://stackoverflow.com/comment/91767069
has comment: http://stackoverflow.com/comment/91767379
tagged with: python
tagged with: regex
possible better answer: http://stackoverflow.com/a/52411700
upvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91767024
accepted answer: http://stackoverflow.com/a/52411707
downvote count: 2
linked to: http://stackoverflow.com/q/22937618
type: Question
has title: regex starting with number 5

http://stackoverflow.com/comment/91639723
score: 0
type: Comment
type: QuestionComment
has text: I think the question is clear. I can think of one solution, however it is not optimal.
comment on: http://stackoverflow.com/q/52347052

http://stackoverflow.com/comment/91718513
score: 0
type: Comment
type: QuestionComment
has text: when it goes into datafreame it shows dtype:object
comment on: http://stackoverflow.com/q/52386793

http://stackoverflow.com/q/52341646
linked to: http://stackoverflow.com/q/2268104
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52447329
tagged with: makefile
tagged with: python
upvote count: 6
type: AnsweredQuestion
has body: I am learning Test Driven development for the first time. I have no experience of software development, but have some experience with scripting. I have been following LinuxAcademy Python 3 for Sys Admin tutorial. I created the following structure, ├── Makefile ├── Pipfile ├── Pipfile.lock ├── README.rst ├── setup.py ├── src │ └── pgbackup │ ├── cli.py │ └── __init__.py └── tests └── test_cli.py setup.py file, from setuptools import setup, find_packages with open('README.rst', 'r') as f: readme = f.read() setup( name='pgbackup', version='0.1.0', description='Database backups locally or to AWS S3.', long_description=readme, author='Keith Thompson', author_email='keith@linuxacademy.com', packages=find_packages('src'), package_dir={'': 'src'}, ) Makefile file, .PHONY: install test default: test install: pipenv install --dev --skip-lock test: PYTHONPATH=./src pytest tests/test_cli.py file, import pytest from pgbackup import cli def test_helloworld(): """ JUST A HELLO WORLD TEST """ assert cli.hello() == "helloworld" and src/pgbackup/cli.py file, def hello(): return "helloworld" I wrote helloworld as my first sample test it is not the part of the tutorial. Now when I run make command from project root directory, my test is passed, ========================================== test session starts ===========================================platform linux -- Python 3.6.6, pytest-3.8.0, py-1.6.0, pluggy-0.7.1 rootdir: /root/code/pgbackup, inifile: collected 1 item tests/test_cli.py . [100%] ======================================== 1 passed in 0.04 seconds ======================================== I know the make command is setting PYTHONPATH to ./src pytest but not get my head around how its running actual test? I know its only setting a search path to import python modules. If I try to run pytest command from tests dir, my test if failed, ================================================= ERRORS =================================================___________________________________ …
type: Question
has answer: http://stackoverflow.com/a/52447329
has title: pytest using Makefile and make command
score: 6

http://stackoverflow.com/comment/91611685
has text: What is your question? Please don't just dump an error message here. Esspecially when the error message has a clear message: `CMake must be installed`. Make sure to indicate where your specific problem is
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/52332268
type: Comment

http://stackoverflow.com/a/52400313
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52385079
has body: Finally, I found the solution. Here is the example: line_bot_api.reply_message(event.reply_token, [TextSendMessage(text= reply_text), TextSendMessage(text= reply_text1)])
type: Answer
has comment: http://stackoverflow.com/comment/110159862

http://stackoverflow.com/q/52395174
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52395525
linked to: http://stackoverflow.com/q/26167097
type: Question
has body: .. seealso:: Class :class:`apps.business.models.Department` Explanation goes here `GNU tar manual, Basic Tar Format &lt;http://link&gt;`_ Documentation for tar archive files, including GNU tar extensions. That creates a proper link to the class Department. How do I change the HTML output to have a just a single class name, without 'apps.business.models' prefix? so it reads Class Department in HTML?
has answer: http://stackoverflow.com/a/52395525
upvote count: 6
has title: Shorter name for the class link in Sphinx
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-sphinx
score: 6

http://stackoverflow.com/a/52324065
type: Answer
score: 19
upvote count: 19
has comment: http://stackoverflow.com/comment/91595675
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52323957
has body: If by shared letters you mean the Counter intersection, you can use the &amp; operator and the amount of letters needed to convert R1 into R2 can be seen as the difference: from collections import Counter D1 = Counter({'A': 2, 'B': 1, 'C': 4, 'D': 5}) D2 = Counter({'A': 3, 'B': 4, 'C': 4, 'D': 7}) R1 = D1 &amp; D2 print(R1) # intersection: min(c[x], d[x]) print(D2 - D1) # subtract (keeping only positive counts) Output Counter({'D': 5, 'C': 4, 'A': 2, 'B': 1}) Counter({'B': 3, 'D': 2, 'A': 1}) If you want to keep negative counts, you can do it like this: from collections import Counter D1 = Counter({'A': 2, 'B': 1, 'C': 4, 'D': 5, 'E': 5}) D2 = Counter({'A': 3, 'B': 4, 'C': 4, 'D': 7, 'E': 3}) R2 = Counter({key: D2.get(key, 0) - value for key, value in D1.items()}) print(R2) Output Counter({'B': 3, 'D': 2, 'A': 1, 'C': 0, 'E': -2}) In the above example 'E' : -2 because the count of E is 5 in D1 and 3 in D2. Note: All the examples are in Python 3.5.
answers question: http://stackoverflow.com/q/52323957

http://stackoverflow.com/comment/92000145
has text: I would assume the correct column for Area is X X Y X Z Z. Is that right?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52416796

http://stackoverflow.com/q/52334127
accepted answer: http://stackoverflow.com/a/52334376
tagged with: python
type: AnsweredQuestion
has title: Data too big in pandas & seaborn. How to create an "other" column?
has comment: http://stackoverflow.com/comment/91615591
type: Question
has answer: http://stackoverflow.com/a/52334376
answer count: 1
has body: I have a series of names each related to an ID. In pandas I then combined these names so each ID would just have a combination as opposed to many individual names. Then I created a count to see how many times these combinations would appear. For example I wanted people who ate apples and oranges. **Combination Count** Apples, Oranges 2 Apples 1 Oranges 1 However, my specific data set was far too large and I have many elements with the count of 1. I am trying to combine these into an "other" group to display using seaborn for a bar chart. However, all the names overlap due the such volume of data. I want to merge probably the last 500 rows of my data set to "other" (as the combination name) and the count is the sum of all those counts. In this example it would be like this: **Combination Count** Apples, Oranges 2 Other 2 I have tried using groupby, but lacking experience in pandas I am unsure of how to write this syntactically. Any help would be appreciated.
has comment: http://stackoverflow.com/comment/91615468
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/91615600
tagged with: grouping

http://stackoverflow.com/comment/125915591
type: Comment
has text: This helped me solve the problem.
type: AnswerComment
comment on: http://stackoverflow.com/a/60495307
score: 0

http://stackoverflow.com/comment/91516796
type: Comment
comment on: http://stackoverflow.com/a/52284165
has text: What do you want: 4 subplots, each with one line?
type: AnswerComment
score: 0

http://stackoverflow.com/q/52354011
has comment: http://stackoverflow.com/comment/91652785
accepted answer: http://stackoverflow.com/a/52354510
has comment: http://stackoverflow.com/comment/91653272
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91652808
tagged with: python-3.x
has title: Index out of range while accessing index of the next iteration in loop in python
has body: There are several image files in a directory on which I need to iterate through, where need to access the next iteration value in the current iteration. img_files_list = os.listdir(/path/to/directory) new_list = [] for index, img in enumerate(img_files_list): if img in new_list: continue new_list.extend([img, img_files_list[index + 1], img_files_list[index + 2]]) print(img) print(img_files_list[index + 1]) print(img_files_list[index + 2]) I need to iterate over all the items of the img_files_list but when reached at the end of the loop need to properly come out of loop without index out of range exception. Anyone, please point out where do I missed the logic.
possible better answer: http://stackoverflow.com/a/52354560
has answer: http://stackoverflow.com/a/52354560
tagged with: python
has answer: http://stackoverflow.com/a/52354510
type: AnsweredQuestion
tagged with: list
type: Question

http://stackoverflow.com/comment/91535212
comment on: http://stackoverflow.com/a/52293463
type: AnswerComment
score: 0
has text: It doesn't let open any file. Error is "No such file or directory"
type: Comment

http://stackoverflow.com/comment/91524535
has text: a callback cannot be a method. Have to carry context/class information when calling the callback. For instance, why not passing an unique ID in the parameters, and this ID is linked to the class instance through a dictionary?
score: 0
comment on: http://stackoverflow.com/q/52288408
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52344823
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/52344228
downvote count: 0
answers question: http://stackoverflow.com/q/52344228
score: 1
type: AcceptedAnswer
has body: You can't directly pass variables into SQL query like this. It can only be done if the values you're passing in are literals. To pass in variables placeholders need to be used. So, the db.execute line should be changed to --> db.execute("INSERT INTO users (name,pw,email) VALUES (:name,:pw,:email)", {"name":Name1, "pw":pw1, "email":Email1}) What we're doing here is, we replace the variables by placeholders in the query by using a colon( : ) in front of them and then passing in their values as python dictionary.

http://stackoverflow.com/comment/91630015
has text: Possible duplicate of [Sort array of objects by string property value in JavaScript](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript)
score: 0
comment on: http://stackoverflow.com/q/52339931
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52297352
has comment: http://stackoverflow.com/comment/91542571
downvote count: 0
type: Answer
score: 4
has body: Use: df = df[df['x'].cumsum().mul(df['x'].iloc[::-1].cumsum()).ne(0)] print (df) x 2 1 3 0 4 3 5 1 Explanation: Get cumsum of column: print (df['x'].cumsum()) 0 0 1 0 2 1 3 1 4 4 5 5 6 5 7 5 Name: x, dtype: int64 Invert column and again cumsum: print (df['x'].iloc[::-1].cumsum()) 7 0 6 0 5 1 4 4 3 4 2 5 1 5 0 5 Name: x, dtype: int64 Multiple by Series.mul: print (df['x'].cumsum().mul(df['x'].iloc[::-1].cumsum())) 0 0 1 0 2 5 3 4 4 16 5 5 6 0 7 0 Name: x, dtype: int64 And check for not equal by ne (!=) of 0: print (df['x'].cumsum().mul(df['x'].iloc[::-1].cumsum()).ne(0)) 0 False 1 False 2 True 3 True 4 True 5 True 6 False 7 False Name: x, dtype: bool Last filter by boolean indexing. Thank you, @Wen for another solution: df[(df.x.eq(0).cumprod().eq(0))&amp;(df.x[::-1].eq(0).cumprod().eq(0))]
answers question: http://stackoverflow.com/q/52297315
upvote count: 4
has comment: http://stackoverflow.com/comment/91542549
has comment: http://stackoverflow.com/comment/91542760
has comment: http://stackoverflow.com/comment/91543035

http://stackoverflow.com/comment/91518727
has text: And take note of my earlier comment about `widget.html()` being incorrect.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52284965

http://stackoverflow.com/comment/91752656
comment on: http://stackoverflow.com/q/52404410
type: Comment
type: QuestionComment
has text: @timgeb or just `{v: k for k, v in d.items()}` is a bit more readable?
score: 3

http://stackoverflow.com/comment/91781637
comment on: http://stackoverflow.com/a/52418552
score: 0
type: AnswerComment
has text: finally block wan't reached when I killed job from UI and no error message was shown. sub process was running in worker machine still. stopping subprocess message shown after process completion
type: Comment

http://stackoverflow.com/q/52353566
has comment: http://stackoverflow.com/comment/91652252
type: Question
has title: Why "next(dropwhile(lambda x: x" error when trying to compare csv files with python script?
has comment: http://stackoverflow.com/comment/91651992
has answer: http://stackoverflow.com/a/52353768
score: -1
has comment: http://stackoverflow.com/comment/91651993
downvote count: 2
tagged with: http://stackoverflow.com/tag/csv
upvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: Thank you for reading, I´m trying to compare two or more csv files to look if a address exists in more than one file. The csv files that I´m tryting to comapre look like this test1.csv address 5A:BA:2A:83:AA:81 FB:AB:8E:74:3A:EB test2.csv address 5A:BA:2A:83:AA:81 FB:AB:8E:74:3A:EB The python script I use is the following (which is borrowed from a similar project here on stackoverflow) from itertools import dropwhile from collections import defaultdict import glob import csv fieldnames = ['address'] address = defaultdict(list) for csv_filename in glob.glob('*.csv'): with open(csv_filename, 'rb') as f_input: csv_reader = csv.DictReader(f_input, fieldnames=fieldnames, skipinitialspace=False) next(dropwhile(lambda x: x['address'] != 'address', csv_reader)) for row in csv_reader: address[row['address']].append(row) with open('output.csv', 'wb') as f_output: csv_writer = csv.DictWriter(f_output, fieldnames=fieldnames, extrasaction='ignore') csv_writer.writeheader() for address, rows in sorted(address.items()): if len(rows) &gt; 1: csv_writer.writerows(rows) Expected outcome is a new .csv file with the the addresses that exists in more than one file. However, I recieve the following error code: Traceback (most recent call last): File "match.py", line 12, in &lt;module&gt; next(dropwhile(lambda x: x['address'] != 'address', csv_reader)) StopIteration Any help regarding this matter is much appreciated, and thank you again for taking your time to read this!

http://stackoverflow.com/comment/91807479
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52410033
type: Comment
has text: Awesome RobJan, thanks! Never heard of "melt" so i had to research and play around with it using my real data. Good stuff!

http://stackoverflow.com/comment/91560565
has text: I guess OP asks how to access instance attribute from outside of the method, no?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52306592

http://stackoverflow.com/comment/91524862
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52288325
has text: I expanded my answer to accomodate your Edit of your Question.

http://stackoverflow.com/comment/91625374
type: QuestionComment
comment on: http://stackoverflow.com/q/52336811
score: 0
type: Comment
has text: There are two summaries. One for the u-resnet34 model and another for the model1, which has u-resnet34 inside.

http://stackoverflow.com/a/52365198
has body: I prefer using list or dict def func_a(a): print(a) def func_b(b): print(b, b) def func_c(c): print(c, c, c) def func_d(d): print(d, d, d, d) # use list func_list = [func_a, func_b, func_c, func_d] for i in range(4): func_list[i](i) # use dict func_dict = {"vect_1": func_a, "vect_2": func_b, "vect_3": func_c, "vect_4": func_d} for i in range(1, 5): func_dict["vect_" + str(i)](i) which will print 0 1 1 2 2 2 3 3 3 3 1 2 2 3 3 3 4 4 4 4
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52364934
has comment: http://stackoverflow.com/comment/91678906

http://stackoverflow.com/comment/91572656
has text: The per-view cache is great when you don't need to invalidate caches. Sometimes when you need to invalidate them, a django extension helps it. https://ring-cache.readthedocs.io/en/latest/ring/django.html#ring.django.cache_page
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52300577

http://stackoverflow.com/comment/91561365
type: Comment
type: QuestionComment
has text: Yes @Kingsley I created the document by using the bullet style manually.
comment on: http://stackoverflow.com/q/52306827
score: 0

http://stackoverflow.com/q/52413357
has body: I have a list of string line = ["set_param(find_system('Fccroot_to_ICD','RegExp','on','FindAll','on','Name','B10_Stat_TRXA_FCC'),'port', '1218');", "set_param(find_system('Fccroot_to_ICD','RegExp','on','FindAll','on','Name','Az_INS3_RawValidity'),'port', '1438');"] I am trying to sort is based on last digit 1438 and 1218 sorting numerically ..'1438' should be treated as number below lines doesn't give me expected result line = sorted(line) ["set_param(find_system('Fccroot_to_ICD','RegExp','on','FindAll','on','Name','Az_INS3_RawValidity'),'port', '1438');", "set_param(find_system('Fccroot_to_ICD','RegExp','on','FindAll','on','Name','B10_Stat_TRXA_FCC'),'port', '1218');"]
possible better answer: http://stackoverflow.com/a/52413397
has answer: http://stackoverflow.com/a/52413397
type: Question
score: -2
has comment: http://stackoverflow.com/comment/91770565
has comment: http://stackoverflow.com/comment/91770617
upvote count: 0
has answer: http://stackoverflow.com/a/52413423
has title: Sorting a list of string based on digit
has answer: http://stackoverflow.com/a/52413399
favorite count: 0
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/52413555
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91770678
has comment: http://stackoverflow.com/comment/91770546
accepted answer: http://stackoverflow.com/a/52413423
has answer: http://stackoverflow.com/a/52413457
downvote count: 2
linked to: http://stackoverflow.com/q/8966538

http://stackoverflow.com/comment/91579871
comment on: http://stackoverflow.com/q/52316063
score: 4
type: Comment
type: QuestionComment
has text: The list comprehension is the most pythonic approach.

http://stackoverflow.com/a/52418184
type: AcceptedAnswer
has body: QSortFilterProxyModel only filters columns or rows, it does not filter elements, so the strategy for this case is to convert the table into a list, then filter the list since filtering a row is equivalent to filtering an element and finally converting the list into a table. import random import math from PyQt4 import QtCore, QtGui class TableModel(QtCore.QAbstractTableModel): def __init__(self, data, columns, parent=None): super(TableModel, self).__init__(parent) self._columns = columns self._data = data[:] def rowCount(self, parent=QtCore.QModelIndex()): if parent.isValid() or self._columns == 0: return 0 return math.ceil(len(self._data )*1.0/self._columns) def columnCount(self, parent=QtCore.QModelIndex()): if parent.isValid(): return 0 return self._columns def data(self, index, role=QtCore.Qt.DisplayRole): if not index.isValid(): return if role == QtCore.Qt.DisplayRole: try: value = self._data[ index.row() * self._columns + index.column() ] return value except: pass class Table2ListProxyModel(QtGui.QIdentityProxyModel): def columnCount(self, parent=QtCore.QModelIndex()): return 1 def rowCount(self, parent=QtCore.QModelIndex()): if parent.isValid(): return 0 return self.sourceModel().rowCount() * self.sourceModel().columnCount() def mapFromSource(self, sourceIndex): if sourceIndex.isValid() and sourceIndex.column() == 0 \ and sourceIndex.row() &lt; self.rowCount(): r = sourceIndex.row() c = sourceIndex.column() row = c * sourceIndex.model().columnCount() + r return self.index(row, 0) return QtCore.QModelIndex() def mapToSource(self, proxyIndex): r = proxyIndex.row() / self.sourceModel().columnCount() c = proxyIndex.row() % self.sourceModel().columnCount() return self.sourceModel().index(r, c) def index(self, row, column, parent=QtCore.QModelIndex()): return self.createIndex(row, column) class ListFilterProxyModel(QtGui.QSortFilterProxyModel): def setThreshold(self, value): setattr(self, "threshold", value) self.invalidateFilter() def filterAcceptsRow(self, row, pa…
has comment: http://stackoverflow.com/comment/92039921
accepted answer of: http://stackoverflow.com/q/52416449
type: Answer
answers question: http://stackoverflow.com/q/52416449
has comment: http://stackoverflow.com/comment/92040023
has comment: http://stackoverflow.com/comment/91786835
has comment: http://stackoverflow.com/comment/92040314
has comment: http://stackoverflow.com/comment/92040624
score: 0

http://stackoverflow.com/comment/91610418
has text: @Marko Well, that happens. I edited the answer accordingly.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52331423
type: Comment

http://stackoverflow.com/comment/91521017
has text: The call requires an `Authorization` header to be set. Most likely it has to contain an OAuth token. Many GET calks to youtube can be done without authorization.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52286294

http://stackoverflow.com/q/52372665
has answer: http://stackoverflow.com/a/52372994
accepted answer: http://stackoverflow.com/a/52372994
tagged with: bokeh
upvote count: 2
tagged with: google-maps
answer count: 1
has title: Replot on Bokeh Google Map Offline
favorite count: 0
has body: I would like to create a bokeh gmap figure with some plotted circles, save that figure's map background, and then create offline figures with new circles on that same map background. For example: import bokeh.plotting as bk from bokeh.models import GMapOptions from bokeh.io import output_file, show, save output_file('test.html', , mode='inline') api_key = #insert your key here mid_lat = 39.8283 mid_lon = 98.5795 map_options = GMapOptions(lat = mid_lat, lng = mid_lon, map_type="satellite", zoom=15) lons = [mid_lon + 0.001, mid_lon - 0.001, mid_lon] lats = [mid_lat + 0.001, mid_lat - 0.001, mid_lat] p = bk.gmap(google_api_key = api_key, map_options = map_options) p.circle(x = lons, y = lats, color = 'white') save(p, 'test.html') show(p) Gives the following, plotting three white points on the map: Now, I want to use that same map image off line--with the zoom level, the x and y domains constant. But I want to plot new circles. For example: lons = [mid_lon + 0.003, mid_lon - 0.003, mid_lon] lats = [mid_lat + 0.003, mid_lat - 0.003, mid_lat] Is there a way to save the figure's background image and load it into a new plot? Looking it doesn't look like GMap supports this, but is there a clever workaround to do this in python? It seems that I might need to save my own tile provider (as shown here), but I think I'm misunderstanding the correct way to do this and then have bokeh re-access the images/tiles offline. But the tiles approach might not even be the way to go for my simple, static map. Python 3.6, Bokeh 12.7
tagged with: python
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/33421734
downvote count: 0
type: Question

http://stackoverflow.com/a/52340103
answers question: http://stackoverflow.com/q/52340045
has comment: http://stackoverflow.com/comment/91627431
has comment: http://stackoverflow.com/comment/91627637
has comment: http://stackoverflow.com/comment/91627814
has comment: http://stackoverflow.com/comment/91627417
has body: You can make use of a defaultdict (I assumed the 1, 2, 3... etc was your index): Setup from collections import defaultdict dct = defaultdict(list) for k, v in list1: dct[k].append(v) pd.DataFrame.from_dict(dct, orient='index').rename(columns=lambda x: f'col{x+1}') col1 col2 col3 1 [dog, slow] [5, 4] [mice, cat] 2 [cat, fast] [6, 6] [cat, mice] 3 [tree, hurry] [7, 5] [mice, cat]
upvote count: 1
has comment: http://stackoverflow.com/comment/91627566
has comment: http://stackoverflow.com/comment/91627525
has comment: http://stackoverflow.com/comment/91627512
type: Answer
has comment: http://stackoverflow.com/comment/91627969
downvote count: 0
score: 1

http://stackoverflow.com/a/52381538
type: Answer
score: 0
type: AcceptedAnswer
has body: The solution I figured out is rather disappointing. Turns out that with a USB to RS232 converter cable, instead of the USB connection I used before, the commands to set and get values work as expected. The command '*DIN?', which I tried initially, which I got from the manual:), still gives no reaction - probably just not supported.
accepted answer of: http://stackoverflow.com/q/52333651
answers question: http://stackoverflow.com/q/52333651

http://stackoverflow.com/comment/91630951
comment on: http://stackoverflow.com/a/52342169
has text: Thanks buddy , you were of great help, yes i wont make that assumption in the future .
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52350820
score: 7
type: AcceptedAnswer
downvote count: 0
has body: It turns out it is possible to mock a function called in a function inside a module with the same name. A small wrapper around unittest.mock.patch() can make that happen like so: Code: from unittest import mock import importlib def module_patch(*args): target = args[0] components = target.split('.') for i in range(len(components), 0, -1): try: # attempt to import the module imported = importlib.import_module('.'.join(components[:i])) # module was imported, let's use it in the patch patch = mock.patch(*args) patch.getter = lambda: imported patch.attribute = '.'.join(components[i:]) return patch except Exception as exc: pass # did not find a module, just return the default mock return mock.patch(*args) To use: Instead of: mock.patch("module.a.b") you need: module_patch("module.a.b") How does this work? Basic idea is to attempt module imports started with the longest possible module path towards the shortest path, and if an import is successful use that module as the patched object. Test Code: import module print('module.a(): ', module.a()) print('module.b(): ', module.b()) print('--') with module_patch("module.a.b") as module_a_b: module_a_b.return_value = 'new_b' print('module.a(): ', module.a()) print('module.b(): ', module.b()) try: mock.patch("module.a.b").__enter__() assert False, "Attribute error was not raised, test case is broken" except AttributeError: pass Test files in module # __init__.py from .a import a from .a import b # a.py def a(): return b() def b(): return 'b' Results: module.a(): b module.b(): b -- module.a(): new_b module.b(): b
accepted answer of: http://stackoverflow.com/q/52324568
type: Answer
answers question: http://stackoverflow.com/q/52324568
has comment: http://stackoverflow.com/comment/91646912
upvote count: 7

http://stackoverflow.com/q/52417686
downvote count: 1
has comment: http://stackoverflow.com/comment/91779834
favorite count: 0
has comment: http://stackoverflow.com/comment/91779808
tagged with: python-requests-html
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: django-views
has title: Python video is not playing Downloaded by using requests module
answer count: 0
has comment: http://stackoverflow.com/comment/91780040
tagged with: python-requests
type: Question
has body: I'm working on a Python(3.6) &amp; Django(2) project in which I need to download a video from a URL. Here's what I have tried: from views.py: if validation is True: url = request.POST.get('video_url') r = requests.get(url, allow_redirects=True) file = open('my_video.mp4', 'wb').write(r.content) rea_response = HttpResponse(file, content_type='video/mp4') rea_response['Content-Disposition'] = 'attachment; filename=my_video.mp4' return rea_response The URL from where it's downloading the vide is: https://expirebox.com/files/386713962c5f8b7556bc77c4a6c2a576.mp4 It downloads a file with the name as my_video.mp4 but when I try to open this video it's not playing. What can be wrong here with my code? OR is there any better way to download the video from URL.
has comment: http://stackoverflow.com/comment/91779653
score: 0
upvote count: 1

http://stackoverflow.com/comment/91669997
score: 1
comment on: http://stackoverflow.com/a/52357919
type: AnswerComment
has text: In MVC (Model-View-Controller) paradigm, your `Instagram` class is a Model (just not a Django model, because it isn't saved to database). Your `InstabotFormView` is a Controller (django views take the role of controllers, a bit confusingly). A Model should never ever have to deal with a controller, so you should never have to initialise your `InstabotFormView` inside your `Instagram` model. Do it the other way round: your controller instantiates the model and sends messages to the model by calling its methods.
type: Comment

iterator
tags question: http://stackoverflow.com/q/52359813
tags question: http://stackoverflow.com/q/52354054
tag name: iterator
tags question: http://stackoverflow.com/q/52387920
tags question: http://stackoverflow.com/q/52374584
tags question: http://stackoverflow.com/q/52296541
tags question: http://stackoverflow.com/q/52306852
tags question: http://stackoverflow.com/q/52310755
type: Tag
tags question: http://stackoverflow.com/q/52344137

http://stackoverflow.com/a/52387040
type: Answer
has body: I have used namedtuple of python. Sample Code: from collections import namedtuple Type_1 = namedtuple('Type_1', 'Name Kilometers_Driven') list_1 = [Type_1('John Doe', 500), Type_1('Jane Doe', 500)] Type_2 = namedtuple('Type_2', 'Id Name Kilometers_Walked Total_Events') list_2 = [Type_2(2, 'Joe Doe', 20, 2), Type_2(3, 'Frank Kelly', 32, 4), Type_2(3, 'John Doe', 10, 3)] for obj_1 in list_1: for idx, obj_2 in enumerate(list_2): if obj_1.Name == obj_2.Name: total = obj_2.Kilometers_Walked + obj_1.Kilometers_Driven list_2[idx] = obj_2._replace(Kilometers_Walked = total) print(list_1) print(list_2) [Type_1(Name='John Doe', Kilometers_Driven=500), Type_1(Name='Jane Doe', Kilometers_Driven=500)] [Type_2(Id=2, Name='Joe Doe', Kilometers_Walked=20, Total_Events=2), Type_2(Id=3, Name='Frank Kelly', Kilometers_Walked=32, Total_Events=4), Type_2(Id=3, Name='John Doe', Kilometers_Walked=510, Total_Events=3)] As you can see kilometer is getting updated correctly
answers question: http://stackoverflow.com/q/52385810
score: 0

http://stackoverflow.com/a/52395577
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52394413
score: 8
upvote count: 8
type: Answer
has body: I found a way to do it, but I want to know if there is a better way. Using the google-auth library, I can do something like this: import json from google.cloud import bigquery from google.oauth2 import service_account """ Securely get content of JSON file from protected memory because having the credential file plainly on the filesystem is unsafe """ service_account_info = json.loads(json_file_content_string) credentials = service_account.Credentials.from_service_account_info(service_account_info) client = bigquery.Client(project='secret-proj', credentials=credentials) More about the library here: https://google-auth.readthedocs.io/en/latest/reference/google.oauth2.service_account.html
accepted answer of: http://stackoverflow.com/q/52394413

http://stackoverflow.com/q/52365428
type: AnsweredQuestion
tagged with: conv-neural-network
accepted answer: http://stackoverflow.com/a/52381786
score: 1
type: Question
downvote count: 0
answer count: 1
tagged with: keras
has body: So I have prepared a sentiment analysis model and I am trying to predict it with new input but I am faced with an error: data = getFile('Cleaned Data.xlsx') data['Description'] = data['Description'].apply(lambda x: x.lower()) data['Description'] = data['Description'].apply((lambda x: re.sub('[^a-zA-z0-9\s]','',x))) print(data[ data['Classification'] == 1].size) print(data[ data['Classification'] == 0].size) for idx,row in data.iterrows(): row[1] = row[1].replace('rt',' ') tokenizer = Tokenizer(split=' ') tokenizer.fit_on_texts(data['Description'].values) #vectorizer = CountVectorizer() #X = vectorizer.fit_transform(jobSpec['Description']).toarray() X = tokenizer.texts_to_sequences(data['Description'].values) X = pad_sequences(X, maxlen=100, value=0.) display(X.shape) vocab_size = len(tokenizer.word_index) + 1 max_length = max([len(s.split()) for s in data['Description']]) Y = pd.get_dummies(data['Classification']).values X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size = 0.33, random_state = 42) tokens_docs = [doc.split(" ") for doc in data['Description'].values] all_tokens = itertools.chain.from_iterable(tokens_docs) my_dict = {token: token if token.isdigit() else idx for idx, token in enumerate(set(all_tokens))} print(X_train.shape,Y_train.shape) print(X_test.shape,Y_test.shape) raw_embedding = load_embedding('glove.6B.100d.txt') embedding_vectors= get_weight_matrix(raw_embedding, tokenizer.word_index) embedding_layer = Embedding(vocab_size, 100, weights=[embedding_vectors], input_length = X.shape[1], trainable=False, name="Embeddings") display(embedding_vectors.shape) # define model sequence_input = Input(shape=(100,), dtype='int32') embedded_sequences = embedding_layer(sequence_input) x = Conv1D(128, 5, activation='relu')(embedded_sequences) x = MaxPooling1D(2)(x) x = Conv1D(128, 5, activation='relu')(x) x = MaxPooling1D(2)(x) x = Conv1D(128, 5, activation='relu')(x) x = MaxPooling1D(18)(x) x = Flatten()(x) x = Dense(128, activation='relu')(x) …
has title: Predicting a conv1d model in keras that takes index of words in a sentence as input
has answer: http://stackoverflow.com/a/52381786
favorite count: 0
tagged with: machine-learning
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/91511131
has text: `len(coords)` will change if `popList` is called but `range(len(coords))` is not recalculated. Leaving with a range that is longer than `coords`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52281365

http://stackoverflow.com/comment/91627380
comment on: http://stackoverflow.com/q/52340088
type: Comment
type: QuestionComment
score: 1
has text: You also get only a single color if this is run as a .py file...

http://stackoverflow.com/comment/91713267
has text: @A.Lorefice thanks for the comment. There is no change on those specific pages. I have manually scrapped it and it works. So I learned this in 1 day and I did not come across Scrappy on tutorials I found online. Also, why dictionary is only holding 36 items while it's printing 60 items?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52377732

http://stackoverflow.com/q/52422876
possible better answer: http://stackoverflow.com/a/52422908
tagged with: python
has answer: http://stackoverflow.com/a/52422908
has body: I have made the loop work so it can repeat itself for the given number of times. Although, I am not able to sum up the ticket costs and it is giving me an error 'ticketType' not defined I have tried ticketType = 0, but the totalCost ends up being 0. Heres the link for the python code: https://repl.it/repls/IrritatingBlankOs print ('Welcome to RareCinema Ticketing System') num = int(input('How many tickets would you like to buy?')) def buyOneTicket() : ticketType = input('Enter the type of ticket (Child/Adult/Senior)?') movieType = input('Enter the movie type (2D/3D)?') return ticketCost return ticketType return movieType ticketCost=0 if ticketType == ("child"): if movieType == ("2D"): ticketCost = 16 elif movieType == ('3D'): ticketCost = 19 elif ticketType == ('adult'): if movieType == ('2D'): ticketCost = 22 elif movieType == ('3D'): ticketCost = 27 elif ticketType == ('senior'): if movieType == ('2D'): ticketCost = 14 elif movieType == ('3D'): ticketCost = 18 count = 1 while (count &lt;= num): ticketCost = ticketCost + buyOneTicket() count = count + 1 print('Your total cost for ' + str(num) + ' is ', ticketCost) Any idea why it is not working as expected?
type: AnsweredQuestion
has title: name 'ticketType' is not defined
downvote count: 2
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52423097
has answer: http://stackoverflow.com/a/52423105
score: -1
favorite count: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/52423097

http://stackoverflow.com/a/52358950
has body: You should just use __init__. You are creating a regular class instance first, and then await on the instance. These are two separate actions. For example, you could first create the instance, and then later, separately, await on it: my_class = MyClass(my_parameter) result_from_coroutine = await my_class or you could create a task from it and have the event loop execute it with my_class = MyClass(my_parameter) task = asyncio.create_task(my_class) # the loop will await the task # ... if task.done(): result_from_coroutine = task.result() The __await__ method is what await or the event loop use to drive coroutines. The same separation applies to coroutine functions (defined with async def); they too create a new coroutine object when you call them, and you don't have to await on them immediately. You can use await on the result at another time. If you are looking for asynchronous instance creation, then you could hack that up by making the __new__ method into a coroutine: &gt;&gt;&gt; class Async: ... async def __new__(cls): ... instance = super().__new__(cls) ... return instance ... &gt;&gt;&gt; Async() &lt;coroutine object Async.__new__ at 0x103654148&gt; Awaiting on the coroutine would create the actual instance and return it. Take into account that this does mean that the __init__ method will be skipped; the latter is only called when the __new__ method directly returns an instance of the class (or a subclass), and a coroutine is not such an instance. You'd have to explicitly do so yourself: class Async: async def __new__(cls, *args, **kwargs): instance = super().__new__(cls) instance.__init__(*args, **kwargs) return instance at which point you could decide to make the __init__ method a coroutine too. Note that this is really going against the grain. I'd postpone calling dependent coroutines to a later point instead. For example, you can just store the parameters to the class on the instance and use those when the instance is awaited on (by having __await__ called)…
has comment: http://stackoverflow.com/comment/91662374
type: AcceptedAnswer
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52358908
downvote count: 0
has comment: http://stackoverflow.com/comment/91662479
answers question: http://stackoverflow.com/q/52358908
has comment: http://stackoverflow.com/comment/91662383
has comment: http://stackoverflow.com/comment/91662351
upvote count: 2

http://stackoverflow.com/comment/91765348
type: QuestionComment
comment on: http://stackoverflow.com/q/52410714
has text: I would suggest SQLAlchemy https://www.sqlalchemy.org/
score: 0
type: Comment

http://stackoverflow.com/a/52364373
type: Answer
has body: Try with: find_elements_by_xpath instead of find_element_by_xpath which will return you the list. PS: I didn't tried your code locally but the error you mentioned is the solution which I mentioned.
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52364188

http://stackoverflow.com/comment/91614206
type: QuestionComment
comment on: http://stackoverflow.com/q/52333570
score: 0
has text: The error has nothing to do with postman. It is because you are getting an error and passing the exception object itself to Response; you should pass `e.message` instead. But once you've fixed that, you should investigate why you are getting an error at all; and that is probably because you are doing things like manually trying to parse the request body rather than just accessing `request.data` directly.
type: Comment

http://stackoverflow.com/q/52387730
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91720491
has comment: http://stackoverflow.com/comment/91720341
tagged with: oop
score: 1
has answer: http://stackoverflow.com/a/52388168
upvote count: 1
possible better answer: http://stackoverflow.com/a/52388087
has title: Calculating Euclidean distance using Magic Methods in Python 3
type: Question
has answer: http://stackoverflow.com/a/52388087
has body: I have a code that calculates Euclidean distance for me: class Point: """A point in two-dimensional space.""" def __init__(self, x, y): self._x = x self._y = y def __eq__(self, other): return self._x == other._x and self._y == other._y def distance(self, other): new_x = self._x - other._x new_y = self._y - other._y print(new_x,' ',new_y) return (new_x ** 2 + new_y ** 2) ** 0.5 p1 = Point(10, 4) p2 = Point(3, 1) print('Euclidean distance : 'p1.distance(p2)) However, now I want to calculate this distance using magic methods in python like __sub__ and __pow__. I've managed to implement __sub__ but I don't know how to implement for __pow__ and square root. This is my code so far: class Point_1(object): def __init__(self, x, y): self._x = x self._y = y def setX(self, x,y): self._x = x self._y = y def getX(self): return self._x,self._y def __sub__ (self, other ): return Point_1(self._x - other._x, self._y - other._y) def __pow__(self,p): return Point_1(self._x ** p, self._y **p) p1 = Point_1(10,4) print(p1.getX()) p2 = Point_1(3,1) print(p2.getX()) p3 = p1 - p2 How can I implement the rest of the formula using magic methods. I'm really confused. Help would me appreciated.
has comment: http://stackoverflow.com/comment/91720653
has answer: http://stackoverflow.com/a/52388373
accepted answer: http://stackoverflow.com/a/52388373
downvote count: 0
has comment: http://stackoverflow.com/comment/91721383
has comment: http://stackoverflow.com/comment/91720447
has answer: http://stackoverflow.com/a/52388036
favorite count: 0
has comment: http://stackoverflow.com/comment/91720930
has comment: http://stackoverflow.com/comment/91720215
tagged with: python

http://stackoverflow.com/a/54095854
has comment: http://stackoverflow.com/comment/95259794
accepted answer of: http://stackoverflow.com/q/52409673
upvote count: 1
answers question: http://stackoverflow.com/q/52409673
type: AcceptedAnswer
type: Answer
downvote count: 0
has body: Answer is: import time import xlwt import csv date_string = time.strftime("%Y%m%d %H.%M") if saving to CSV document data_output = [] with open('C:\\Users\\Desktop\\File Name' + date_string + '.csv', 'a+') as f: w = csv.writer(f, delimiter=',') for data in data_output: w.writerow(data) f.close() if saving to Excel document df.to_excel('C:\\Users\\Desktop\\File Name' + date_string + '.xlsx') if saving to Txt document df.to_csv('C:\\Users\\Desktop\\File Name' + date_string + '.txt')
score: 1

http://stackoverflow.com/q/52279168
has comment: http://stackoverflow.com/comment/91581402
score: 2
has comment: http://stackoverflow.com/comment/91579746
tagged with: python-ldap
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/91507212
tagged with: flask
tagged with: ldap
tagged with: python
favorite count: 0
tagged with: flask-login
answer count: 0
has comment: http://stackoverflow.com/comment/91581455
upvote count: 2
has body: Imagine a web application written using Python Flask for server-side processing that uses Flask-Login to handle user logins and python-LDAP to authenticate against an LDAP server. A simple example of such an implementation is given here: https://code.tutsplus.com/tutorials/flask-authentication-with-ldap--cms-23101 My question is: how exactly is the password passed from the web form (client-side) back to the server and then passed on to the LDAP server for authentication? More importantly, do I (as a developer of the application) have the ability to view a user's plain-text (or otherwise) password in this client-server transaction? And if this authentication framework does allow a developer to view plaintext passwords from all the users of an application, then is there a way to allow my server-side processing to handle LDAP authentication that doesn't allow this or do I need to offload this functionality to the client? Please let me know if I need to cross-post this on another SE forum.
type: UnansweredQuestion
has title: Python Flask LDAP - can I see passwords as a developer?

http://stackoverflow.com/comment/91683726
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52351526
has text: A RAID might not t help, because it's a single device as far as your program can tell. A single thread might be able to saturate it. If not, then additional threads can help. But usually you'd want each thread to write to a separate drive hooked up to a separate controller.
type: Comment

http://stackoverflow.com/comment/91871500
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52397563
has text: I am really not able to replicate. I think I have tried all combinations of `nohup`, `&`, `shell=True` and so forth... Yes (I actually changed for an actual PHP script to test), I do have a `while (true)` condition in the script... But the flask server always replies in a small amount of time... How does your php script looks like? How do you launch your uWSGI server? What is your platform?
score: 0

http://stackoverflow.com/q/52404692
type: Question
has title: Problem in removing a table with large object in postgresql
tagged with: database
has body: My database has one table named pg_largeobjects. I want to truncate the whole table and tried many things so far, like: VACUUM FULL ANALYZE pg_largeobject lo_unlink backup database by excluding that particular table. restore database by excluding that particular table (Failed). Any help will be appreciated
tagged with: postgresql
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: odoo-11
tagged with: odoo
has answer: http://stackoverflow.com/a/52405504

http://stackoverflow.com/a/68916589
has body: Few things to try Run the Navigator in admin mode (Right click the shortcut -&gt; More -&gt; Run as Administrator) Downgrade Jupyterlab to another version and upgrade it again (basically reinstalling) The first one solved my issue.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52300930

http://stackoverflow.com/a/52322937
type: Answer
score: 0
has body: Turns out the data I was getting was not JSON appropriate. I went back and changed the request to send data as a json and it worked perfectly.
answers question: http://stackoverflow.com/q/52318845

http://stackoverflow.com/a/52369900
has comment: http://stackoverflow.com/comment/91686914
has comment: http://stackoverflow.com/comment/91686946
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/91686395
has body: When using virtualenv or conda what I do is activate the env in a terminal and then launch emacs from that terminal. On a Mac: $ conda activate hcpy (hcpy)$ /Applications/Emacs.app/Contents/MacOS/Emacs if you want to just have a terminal version of emacs add the argument -nw then in emacs the command M+x pdb works fine for me. The issue here is that there are often multiple python installs. So it is not enough for emacs to find a python exe, emacs needs to find the python that has the libraries installed. so for instance if I go: $which python I get: /Users/jamesanderson/anaconda3/bin/python but, if I go: $source ./.py3dev/bin/activate $which python /Users/jamesanderson/code/python/camera/.py3dev/bin/python so setup your virtual env with conda with the libraries you need. When you are inside emacs and start a shell, and do the which python step. The answer has to be the instance of python with the libraries installed.
answers question: http://stackoverflow.com/q/52358677

http://stackoverflow.com/q/52419790
tagged with: syntax-error
has comment: http://stackoverflow.com/comment/91782819
has body: I was following this repo for installing files2rouge, then i got an error as below: Traceback (most recent call last): File "setup_rouge.py", line 7, in &lt;module&gt; from files2rouge import settings File "/home/cerdas/files2rouge/files2rouge/__init__.py", line 2, in &lt;module&gt; from files2rouge.files2rouge import main File "/home/cerdas/files2rouge/files2rouge/files2rouge.py", line 17, in &lt;module&gt; from files2rouge import utils File "/home/cerdas/files2rouge/files2rouge/utils.py", line 16 print(file=saveto, *args, **kwargs) ^ SyntaxError: invalid syntax Here the line of code that encountered the error: def tee(saveto, *args, **kwargs): """Mimic the tee command, write on both stdout and file """ print(args, kwargs) if saveto is not None: print(file=saveto, *args, **kwargs) I have no idea whats wrong, and not sure what is saveto for. Please give me some insight, thanks.
upvote count: 1
answer count: 1
tagged with: python-2.x
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: rouge
downvote count: 2
type: Question
linked to: http://stackoverflow.com/q/52418360
score: -1
has title: SyntaxError: invalid syntax for print(file=saveto, *args, **kwargs)
has answer: http://stackoverflow.com/a/52419846

http://stackoverflow.com/comment/91602324
comment on: http://stackoverflow.com/a/52316923
has text: Thanks for this. The format is now correct but it isn't correctly identifying where the status has changed. In some cases (eg where there is a new test in the second file) there is no status next to the test name. In others it is adding an incorrect status?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91676404
comment on: http://stackoverflow.com/q/52357812
score: 0
type: Comment
type: QuestionComment
has text: @today: Yes, I train on a CPU of a Lenovo Thinkpad T530 with an i5 that came out 2012...

http://stackoverflow.com/q/52363416
tagged with: recurrent-neural-network
has comment: http://stackoverflow.com/comment/91676003
tagged with: lstm
type: Question
linked to: http://stackoverflow.com/q/56804431
answer count: 2
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/91753608
has title: LSTM giving same prediction for numerical data
tagged with: keras
score: 0
has answer: http://stackoverflow.com/a/52792073
has comment: http://stackoverflow.com/comment/91712162
has comment: http://stackoverflow.com/comment/91671192
tagged with: python
has body: I created an LSTM model for intraday stock predictions. I took the training data with the shape of (290, 4). I did all the preprocessing like Normalize the data, taking the difference, taking window size of 4. This is a sample of my input data. X = array([[0, 0, 0, 0], [array([ 0.19]), 0, 0, 0], [array([-0.35]), array([ 0.19]), 0, 0], ..., [array([ 0.11]), array([-0.02]), array([-0.13]), array([-0.09])], [array([-0.02]), array([ 0.11]), array([-0.02]), array([-0.13])], [array([ 0.07]), array([-0.02]), array([ 0.11]), array([-0.02])]], dtype=object) y = array([[array([ 0.19])], [array([-0.35])], [array([-0.025])], ....., [array([-0.02])], [array([ 0.07])], [array([-0.04])]], dtype=object) Note: I am giving as well as predicting the difference value. So input value is between range (-0.5,0.5) Here is my Keras LSTM model : dim_in = 4 dim_out = 1 model.add(LSTM(input_shape=(1, dim_in), return_sequences=True, units=6)) model.add(Dropout(0.2)) model.add(LSTM(batch_input_shape=(1, features.shape[1],features.shape[2]),return_sequences=False,units=6)) model.add(Dropout(0.3)) model.add(Dense(activation='linear', units=dim_out)) model.compile(loss = 'mse', optimizer = 'rmsprop') for i in range(300): #print("Completed :",i+1,"/",300, "Steps") model.fit(X, y, epochs=1, batch_size=1, verbose=2, shuffle=False) model.reset_states() I am feeding the last sequence value of shape=(1,4) and predict the output. This is my prediction : base_value = df.iloc[290]['Close'] prediction = [] orig_pred = [] input_data = np.copy(test[0,:]) input_data = input_data.reshape(len(input_data),1) for i in range(100): inp = input_data[i:,:] inp = inp.reshape(1,1,inp.shape[0]) y = model.predict(inp) orig_pred.append(y[0][0]) input_data = np.insert(input_data,[i+4],y[0][0], axis=0) base_value = base_value + y prediction_apple.append(base_value[0][0]) sqrt(mean_squared_error(test_output, orig_pred)) RMSE = 0.10592485833344527 Here is the difference in prediction visualization along with stock price predict…
has answer: http://stackoverflow.com/a/52367906
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/100164095
has comment: http://stackoverflow.com/comment/126095455

http://stackoverflow.com/comment/91638712
comment on: http://stackoverflow.com/a/52343682
score: 1
type: AnswerComment
type: Comment
has text: Unless you are using object dtype arrays, `y = y.copy()` is enough.

http://stackoverflow.com/comment/91965765
type: AnswerComment
type: Comment
has text: for both the code the datasent prints 8, I think I went wrong somewhere. please correct me . Added the code in the question. thanks
comment on: http://stackoverflow.com/a/52411059
score: 0

http://stackoverflow.com/a/69097391
type: Answer
answers question: http://stackoverflow.com/q/52297740
score: 4
has body: In this type, we will see that we have some column values that are nan or empty so we were not able to do this. Hence, when you applied the code as here given below it, will work. df_pcc_mod = df_pcc_mod[~df_pcc_mod['Invoice'].str.contains('Reversed',na=False)]
upvote count: 4
has comment: http://stackoverflow.com/comment/122122882
downvote count: 0

http://stackoverflow.com/comment/91781508
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52418749
has text: Do you want to freeze random 50 percent or specific ones of specific layers?

http://stackoverflow.com/comment/91583720
score: 1
has text: Try `-no-pie` linker option.
type: QuestionComment
comment on: http://stackoverflow.com/q/52315461
type: Comment

http://stackoverflow.com/q/52280087
has comment: http://stackoverflow.com/comment/91510817
has comment: http://stackoverflow.com/comment/91508246
has comment: http://stackoverflow.com/comment/91508475
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/91508869
has answer: http://stackoverflow.com/a/52280128
has body: I know, that the purpose of str() method is to return the string representation of an object, so I wanted to test what happens if I force it to make something else. I've created a class and an object: class MyClass(object): def __str__(self, a=2, b=3): return a + b mc = MyClass() When I call: print(str(mc)) The interpreter complains: TypeError: __str__ returned non-string (type int) And this is fully understandable because the str() method is trying to return int. But if I try: print(mc.__str__()) I get the output: 5. So why the interpreter allows me to return int when I call __str__ directly, but not when I'm using str(mc) which - as I understand - is also evaluated to mc.__str__().
has answer: http://stackoverflow.com/a/52280355
has comment: http://stackoverflow.com/comment/91508294
linked to: http://stackoverflow.com/q/8144026
tagged with: string
answer count: 4
favorite count: 0
linked to: http://stackoverflow.com/q/34859471
tagged with: python-internals
has title: Returning int from a __str__ method in Python
type: UnansweredQuestion
tagged with: cpython
has answer: http://stackoverflow.com/a/52280314
score: 13
tagged with: python
has comment: http://stackoverflow.com/comment/91508267
linked to: http://stackoverflow.com/q/12448175
upvote count: 13
has answer: http://stackoverflow.com/a/52280364

http://stackoverflow.com/a/52284545
accepted answer of: http://stackoverflow.com/q/52283346
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
has body: Thanks to @abarnert for the suggestion to look at overhead through longer task length. It seems like the length of each task was too short, and the overhead made Dask slower. I changed the exponent from 2 to 10000 to make each task longer. This example produces what I was expecting: Python code: %%timeit b = list(range(50000)) b = list(filter(is_even, b)) b = list(map(lambda x: x ** 10000, b)) &gt;&gt;&gt; 34.8 s ± 2.19 s per loop (mean ± std. dev. of 7 runs, 1 loop each) Dask code: %%timeit b = db.from_sequence(range(50000)) c = b.filter(is_even).map(lambda x: x ** 10000) c.compute() &gt;&gt;&gt; 26.4 s ± 409 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
upvote count: 1
answers question: http://stackoverflow.com/q/52283346

http://stackoverflow.com/q/52430003
type: UnansweredQuestion
tagged with: python
tagged with: plot
answer count: 0
score: 1
tagged with: matplotlib
upvote count: 1
type: Question
downvote count: 0
has body: I'm new to python and I am trying to make a real time plot of data from a serial sensor connected to a raspberry pi 3. I have been trying to change the x axis to a time axis but I keep getting a string to float error. how can I modify my code to get a a real time plot that reads data every second and it updates constantly and that the x axis shows the time at which is reading the point. Here is what I have so far, import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.animation as animation import serial import platform import time import datetime import csv import re print("Python version: " + platform.python_version()) print("matplotlib version: " + mpl.__version__) fig, ax = plt.subplots() line, = ax.plot(np.random.rand(10)) ax.set_ylim(-.1, .08) xdata, ydata = [0]*100, [0]*100 SerialIn = serial.Serial("/dev/ttyUSB0",115200) FILE = open('Pressure ' + time.strftime("%Y-%m-%d %H:%M") + '.csv','a') pattern = re.compile( r'([0-9 .+-]*)' ) #Added def update(data): line.set_ydata(data) return line, def run(data): global xdata, ydata x,y = data if (x == 0): xdata = [0]*100 ydata = [0]*100 del xdata[0] del ydata[0] xdata.append(x) ydata.append(y) line.set_data(xdata, ydata) return line, def data_gen(): x = 10 while True: if (x &gt;= 9): x = 0 else: x += 0.1 SerialIn.write(b"P\r") try: inRaw = re.search( pattern, SerialIn.read(SerialIn.in_waiting).decode('utf-8') ).group(0) inInt = float(inRaw) TIME = time.strftime('%H:%M:%S') FILE.write("{0},{1}\r".format(TIME, inInt)) FILE.flush() print('['+time.strftime('%H:%M:%S')+']',inInt) time.sleep(1-time.time()%1) except: inInt = 0 yield x, inInt ani = animation.FuncAnimation(fig, run, data_gen, interval=0, blit=True) plt.show() SerialIn.close() FILE.close()
favorite count: 0
has title: python plotting realtime from serial sensor

http://stackoverflow.com/a/52364128
type: Answer
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/91675076
has comment: http://stackoverflow.com/comment/91674630
score: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52363748
has comment: http://stackoverflow.com/comment/91673725
has body: You can make direct request to Society6 API as below: counter = 1 while True: source = requests.get('https://society6.com/api/users/franciscomffonseca/followers?page=%s' % counter).json() if source['data']['attributes']['followers']: for i in source['data']['attributes']['followers']: print(i['card']['link']['href']) counter += 1 else: break This will print relative hrefs as /wickedhonna /wiildrose /williamconnolly /whiteca1x If you want absolute hrefs just replace print(i['card']['link']['href']) with print("https://society6.com" + i['card']['link']['href'])
accepted answer of: http://stackoverflow.com/q/52363748
has comment: http://stackoverflow.com/comment/91673815

http://stackoverflow.com/q/52345424
score: 3
has comment: http://stackoverflow.com/comment/91637129
tagged with: in-place
tagged with: python
has body: I found this question that asks for in-place modification of an array, so that all zeros are moved the end of the array and the remaining order of non-zero elements is maintained. In-place, according to the problem statement, means without making a copy of the original array. (This is taken from Leetcode and can be found as #283, Move Zeroes) An example input and output would be, [0,1,0,13,12] becomes [1,13,12,0,0]. One simple solution I saw is: for num in nums: if num == 0: nums.remove(num) nums.append(0) The solution is clear and easy to follow, so I get that it is doing what it is supposed to. However, I am not fully clear/sold on the in-place part, because I am not sure how remove works in the background. Does remove internally make a copy of the array to remove the specified element - how does it work? Using this notion of "in-place", is my initial solution below considered in-place (since it does not make any copies of nums, but rather modifies the original version of nums)? indices = [] for en, num in enumerate(nums): # get the index of all elements that are 0 if num == 0: indices.append(en) for en, i in enumerate(indices): new_i = i-en # use the index, accounting for the change in length of the array from removing zeros nums = nums[:new_i] + nums[new_i+1:] # remove the zero element nums = nums + [0] * len(indices) # add back the appropriate number of zeros at the end
has comment: http://stackoverflow.com/comment/91637174
has title: In-place modification of array in python
upvote count: 3
has comment: http://stackoverflow.com/comment/91637056
has comment: http://stackoverflow.com/comment/91637066
answer count: 1
tagged with: indexing
has answer: http://stackoverflow.com/a/52345734
has comment: http://stackoverflow.com/comment/91636974
type: UnansweredQuestion
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/91637192
favorite count: 0
type: Question

http://stackoverflow.com/q/52345148
tagged with: python
has answer: http://stackoverflow.com/a/52345514
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91636175
has answer: http://stackoverflow.com/a/52345598
type: Question
has title: Combining lists which has corresponding values
score: 0
has answer: http://stackoverflow.com/a/52345257
has body: I am new to python, so in need of help. I am having a three lists in which the values correspond to each other. As in an excel like below ID Name Height 1 u 5 2 s 7 3 d 9 4 u 7 5 k 7 6 z 5 and so on. Now from this table I want to combine the ID which are having same height. names as in not so important.. How do I do that using python.
answer count: 3

http://stackoverflow.com/q/52333121
possible better answer: http://stackoverflow.com/a/52334787
has body: How can I retrieve usage and cost data for my IBM Cloud account using a REST API? I found that there are billing related commands and I can export some data as JSON. Is there an API or SDK I can use, ideally Python? Here are some of the IBM Cloud billing commands I use: ibmcloud billing resource-instances-usage --json ibmcloud billing account-usage --json Are there equivalent APIs for that?
has answer: http://stackoverflow.com/a/52334787
answer count: 2
downvote count: 2
has title: IBM Cloud: How to access the API for billing and usage?
favorite count: 0
tagged with: billing
accepted answer: http://stackoverflow.com/a/52333233
tagged with: python
upvote count: 4
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52333233
type: Question
tagged with: ibm-cloud

http://stackoverflow.com/a/52395207
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52357463
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52357463
has body: Use subtitles with the subtitles filter. This will be easier and more efficient than making images beforehand and trying to time everything. You can also control the font, size, color, style, position, etc. Example using the color filter as the background: ffmpeg -i music.mp3 -filter_complex "color=c=blue,subtitles=lyrics.srt[v]" -map "[v]" -map 0:a -c:a aac -shortest output.mp4 SRT This is a simple format that supports basic styling. 1 00:00:00,600 --> 00:00:02,340 Revelation, chapter 4 2 00:00:02,340 --> 00:00:04,100 After these things I looked, 3 00:00:04,100 --> 00:00:06,410 and behold a door was opened in heaven, ASS With ASS subtitles you can get even more control, such as individual word and letter styling, but this format is much more complicated: [Script Info] ScriptType: v4.00+ PlayResX: 384 PlayResY: 288 [V4+ Styles] Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding Style: Default,Arial,16,&Hffffff,&Hffffff,&H0,&H0,0,0,0,0,100,100,0,0,1,1,0,2,10,10,10,0 [Events] Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text Dialogue: 0,0:00:00.60,0:00:02.34,Default,,0,0,0,,Revelation, chapter 4 Dialogue: 0,0:00:02.34,0:00:04.10,Default,,0,0,0,,After these things I looked, Dialogue: 0,0:00:04.10,0:00:06.41,Default,,0,0,0,,and behold a door was opened in heaven, This example only shows the format structure: I didn't add any styling. Aegisub can be used to create ASS subtitles if you want to experiment with this format. ffmpeg can convert subtitle formats. force_style option The force_style option in the subtitles filter can extend the formatting possibilities of the simplistic SRT format. It uses the ASS format options such as Fontsize, Fontname, OutlineColour, etc. Look at the Format line in the ASS example above for a list of options. subtitles=lyrics.sr…

http://stackoverflow.com/comment/92068007
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52553043
type: Comment
has text: @el_pup_le If you're interested where PyCharm keeps its settings or what those files are, that's completly unrelated to the current question. (FWIW see https://www.jetbrains.com/help/pycharm/project-and-ide-settings.html on the former, the 1st in google on "where pycharm keeps global and project-specific settings").

http://stackoverflow.com/a/52387204
answers question: http://stackoverflow.com/q/52386976
has body: your cron expression should be 0 0/10 * 1/1 * ? * You can take help from this also try using &gt; instead of &gt;&gt;
score: 1
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91719350
has comment: http://stackoverflow.com/comment/91719347
upvote count: 1

http://stackoverflow.com/q/52283928
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: django-views
type: Question
score: 0
has answer: http://stackoverflow.com/a/52291933
has body: What I want to do is to create a list within another. Example home/4/5/ etc Also if I want to change the name from path it gives an error saying no reverse. path('findstudent/', views.FindStudent.as_view(), name='findstudent'), path('findstudent/&lt;int:pk&gt;/', views.FindStudentdetail.as_view(), name='findstudent'), path('findstudent/&lt;int:pk&gt;/&lt;int:pk_alt&gt;/', views.FindStudentresult.as_view(), name='findstudent'), @method_decorator(login_required, name='dispatch') class FindStudent(ListView): template_name = 'Dashboard/findStudent.html' model = Student fields = ['sbtc'] def get_queryset(self): batch = Student.objects.values_list('sbtc').distinct() return batch @method_decorator(login_required, name='dispatch') class FindStudentdetail(ListView): template_name = 'Dashboard/findStudentdetail.html' model = Student fields = ['all'] def get_queryset(self): student = Student.objects.filter(sbtc=self.kwargs['pk']) return student @method_decorator(login_required, name='dispatch') class FindStudentresult(ListView): template_name = 'Dashboard/findStudentresult.html' model = Result fields = ['all'] def get_queryset(self): result1 = Result.objects.select_related('Student') result = Result.objects.filter(id=self.kwargs['pk_alt']) return result The problem is here: How can I define the path/url in the template! &lt;div class="form-group"&gt; {% for student in object_list %} &lt;li&gt;&lt;a href="{% url **'Dashboard:findstudent'** %}"&gt;{{student.sroll}} {{student.snam}}&lt;/a&gt;&lt;/li&gt; {% endfor %} &lt;/div&gt;
answer count: 1
has title: How to declare a dynamic link in django template?
tagged with: django-templates

http://stackoverflow.com/comment/91607744
score: 0
comment on: http://stackoverflow.com/q/52330386
type: QuestionComment
type: Comment
has text: You can't call a 32-bit DLL from a 64-bit executable. If you try you will only get an error message. This error message is one of the most explicit that I've seen. Mostly they are along the lines of *file not found* or *could not be loaded*.

http://stackoverflow.com/q/52318351
type: Question
has comment: http://stackoverflow.com/comment/91584747
accepted answer: http://stackoverflow.com/a/52318458
answer count: 1
has body: I know that some variants of this question have been discussed, but they don't seem to work universally, as it were. Hence this question. Say I have a text and within it appears, several times, this pattern: Let's start! ... blah, blah, blah... This is the end, my friend. I want to replace every appearance of this pattern with Whatever. The thing is - this pattern can be of any arbitrary length (other than its beginning and end), it may be stretched over one or more lines, and may contain with any number of special characters, including single and double quotes, slashes of all types, HTML tags, and other whatnots. The expression will have to look for the starting phrase, collect it and everything the follows that phrase, regardless of how long it takes and what type of "stuff" is on the way, until it encounters the closing phrase, collects that too and replaces the whole thing with the replacement string; then do it again until it encounters the end of the text. Is there any one (python) universal expression that will can do this kind of job?
tagged with: wildcard
has comment: http://stackoverflow.com/comment/91584346
score: 0
has title: Universal match and replace a pattern of arbitray length where only the beginning and end are known
has comment: http://stackoverflow.com/comment/91584125
has comment: http://stackoverflow.com/comment/91584179
has comment: http://stackoverflow.com/comment/91584064
has comment: http://stackoverflow.com/comment/91584418
has answer: http://stackoverflow.com/a/52318458
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/91584466
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91584526

http://stackoverflow.com/q/52407736
possible better answer: http://stackoverflow.com/a/68824216
tagged with: logging
type: Question
upvote count: 9
has comment: http://stackoverflow.com/comment/133652849
has answer: http://stackoverflow.com/a/52455408
has title: How to filter logs from gunicorn?
score: 9
has body: I have a Flask API with gunicorn. Gunicorn logs all the requests to my API, i.e. 172.17.0.1 - - [19/Sep/2018:13:50:58 +0000] "GET /api/v1/myview HTTP/1.1" 200 16 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36" However, I want to filter the logs to exclude a certain endpoint which is called from some other service all few seconds. I wrote a filter to exclude this endpoint from being logged: class NoReadyFilter(logging.Filter): def filter(self, record): return record.getMessage().find('/api/v1/ready') == -1 and if I add this filter to the werkzeuglogger and use the Flask development server, the filter works. Requests to /api/v1/ready won't appear in the log files. However, I can't seem to add the filter to the gunicornlogger. With the following code, requests to /api/v1/ready still appear: if __name__ != '__main__': gunicorn_logger = logging.getLogger('gunicorn.glogging.Logger') gunicorn_logger.setLevel(logging.INFO) gunicorn_logger.addFilter(NoReadyFilter()) How can you add a filter to the gunicorn logger? I tried adding it to the gunicorn.error-logger as suggested here, but it didn't help.
accepted answer: http://stackoverflow.com/a/52455408
downvote count: 0
has answer: http://stackoverflow.com/a/61462859
favorite count: 0
tagged with: python-logging
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/68824216
type: AnsweredQuestion
tagged with: gunicorn

http://stackoverflow.com/q/52391072
upvote count: 8
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52391339
has comment: http://stackoverflow.com/comment/91727251
linked to: http://stackoverflow.com/q/44948865
tagged with: sqlalchemy
type: Question
has title: creating and appending to a list in SQLAlchemy database table
has body: I am learning SQLAlchemy and I am stuck. I have a SQL table (table1) has two fields: 'name' and 'other_names' I have an excel file with two columns: first_name alias paul patrick john joe simon simone john joey john jo I want to read the excel file into my table1, so that it looks like this (i.e. all of the aliases for the same line are on one row): paul patrick john joe,joey,jo simon simone This is the idea that I was trying to do. The code (with comments) that I tried: for line in open('file.txt', 'r'): #for each line in the excel file line = line.strip().split('\t') #split each line with a name and alias first_name = line[0] #first name is the name before the tab alias = line[1] #alias is the name after the tab instance = Session.query(session,tbs['table1'].name).filter_by(name=first_name) #look through the database table, by name field, and see if the first name is there list_instance = [x[0] for x in instance] #make a list of first names already in database table if first_name not in list_instance: #if the excel first name is not in the database table alias_list = [] #make an empty list alias_list.append(alias) #append the alias name_obj = lib.get_or_create( #small function to make db object session, tbs["table1"], name = first_name, #add first name to the name field other_names = alias_list # add alias list to the other_names field ) elif first_name in list_instance: #elif first name already in db alias_list.append(alias) #append the alias to the alias list made above name_obj = lib.get_or_create( session, tbs["table1"], name = first_name, other_names = alias_list #create object as before, but use updated alias list ) The problem is that I can get the above code to run with no errors, but also the output is not an appended list, it is simply a database table that looks like the excel file; i.e. name alias paul patrick john joe simon simone john joey john jo Could someone point out where I am going wrong, specifically, how do i amend this code? Please let me kn…
has comment: http://stackoverflow.com/comment/131355394
linked to: http://stackoverflow.com/q/9667138
linked to: http://stackoverflow.com/q/48799232
has answer: http://stackoverflow.com/a/52553400
answer count: 2
tagged with: sql
downvote count: 0
favorite count: 0
score: 8
has comment: http://stackoverflow.com/comment/92024767
has comment: http://stackoverflow.com/comment/92044515
has comment: http://stackoverflow.com/comment/92043866

http://stackoverflow.com/q/52279863
tagged with: python
type: Question
has title: Bazel, python3 and python interpreter options
has body: I have a large and diverse codebase, much of which is python(3), which I am trying to organise with bazel. I would ideally like (in approximate order of importance): To default to python3 (ideally a specific version, but I can live with just using whatever's in /usr/bin/python3) To send options to the python interpreter, ideally in a per-target manner The option to override the python interpreter and other options for specific targets Right now I have a partial solution and I would like some advice on whether it is idiomatic and where it might be improved. In /BUILD I have genrule( name = "python3_interpreter", outs = ["python"], cmd = "echo '#!/bin/bash\n/usr/bin/python3 -OO \"$$@\"\n' &gt; $@", executable = True, ) py_runtime( name = "python3", visibility = ["//visibility:public"], interpreter = ":python3_interpreter", files = [] ) to create a man-in-the-middle python interpreter, where I can add options to the python interpreter (-OO in this case). In /.bazelrc I have build --python_top=//:python3 run --python_top=//:python3 To default to that interpreter. I could probably use a macro around the genrule to make adding interpreter options more ergonomic (and perhaps search for python3 in a more structured way), but it still feels a lot like a hack. I could also use an external repository to download and build a specific python version from source, more effort but also more hermitic. None of these options seem particularly satisfying and none allow me to override things per-target. Any advice or constructive criticism would be welcome. I'm already using rules_python to manage pip dependencies. I'm also thinking of using rules_pyz, which looks like it might be easier to edit to support other features I need from python (e.g. py_library that depends on cc_library).
downvote count: 0
tagged with: bazel
upvote count: 6
favorite count: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
score: 6

http://stackoverflow.com/q/52387450
tagged with: encoding
has comment: http://stackoverflow.com/comment/91720521
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52389384
has comment: http://stackoverflow.com/comment/91720097
tagged with: utf-8
has answer: http://stackoverflow.com/a/52388645
has comment: http://stackoverflow.com/comment/91721628
has title: Using Swift, how do you re-encode then decode a String like this short script in Python?
has body: XKCD has some issues with their API and weird encoding issues. Minor encoding issue with xkcd alt texts in chat The solution (in Python) is to encode it as latin1 then decode as utf8, but how do I do this in Swift? Test string: "Be careful\u00e2\u0080\u0094it's breeding season" Expected output: Be careful—it's breeding season Python (from above link): import json a = '''"Be careful\u00e2\u0080\u0094it's breeding season"''' print(json.loads(a).encode('latin1').decode('utf8')) How is this done in Swift? let strdata = "Be careful\\u00e2\\u0080\\u0094it's breeding season".data(using: .isoLatin1)! let str = String(data: strdata, encoding: .utf8) That doesn't work!
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: swift
score: 1
has comment: http://stackoverflow.com/comment/91720812
has comment: http://stackoverflow.com/comment/91720803
tagged with: character-encoding
type: Question
answer count: 2

http://stackoverflow.com/q/52400904
has answer: http://stackoverflow.com/a/52401047
has body: I am pretty new to python and used to use R. For this matter, I would use as.factor and categorize based on the number. Earlier I was trying to use replace and .loc function in order to give a new category value in a new column according to the condition but it would run only to fail at what I wanted to do. Eventually I created the following, very simple function: g['Category'] = "" for i in g['NumFloorsGroup']: if i == '0-9' or i == '10-19': g['Category'] = 'LowFl' elif i == '50~': g['Category'] = 'HighFl' else: g['Category'] = 'NormalFl' When I run the function though, it only returns the 'LowFl' and doesn't correct the other parts. I feel like I am missing something. the data info is as follows: &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 596 entries, 128 to 595 Data columns (total 4 columns): YearBuilt 596 non-null int64 NumFloorsGroup 596 non-null category Count 596 non-null int64 Category 596 non-null object dtypes: category(1), int64(2), object(1) Any comment will be helpful! bins = [0, 10, 20, 30, 40, 50, np.inf] labels = ['0-9', '10-19', '20-29', '30-39', '40-49', '50~'] copy = original_data.copy() copy['NumFloorsGroup'] = pd.cut(copy['NumFloors'], bins=bins, labels=labels, include_lowest=True) g = (copy.groupby(['YearBuilt', 'NumFloorsGroup'])['YearBuilt'] .count() .reset_index(name="Count") .sort_values(by='Count', ascending=False)) And the parts that only returns LowFl g['Category'] = "" for i in g['NumFloorsGroup']: if i == '0-9' or i == '10-19': g['Category'] = 'LowFl' elif i == '50~': g['Category'] = 'HighFl' else: g['Category'] = 'NormalFl' This returns All the Category as LowFl YearBuilt NumFloorsGroup Count Category 128 1920 0-9 90956 LowFl 171 1930 0-9 76659 LowFl 144 1925 0-9 70387 LowFl 237 1950 0-9 47237 LowFl 91 1910 0-9 46384 LowFl
tagged with: if-statement
possible better answer: http://stackoverflow.com/a/52401007
has comment: http://stackoverflow.com/comment/91745699
accepted answer: http://stackoverflow.com/a/52401047
has title: for if loop to categorize under condition
tagged with: for-loop
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91745831
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52401057
type: Question
has comment: http://stackoverflow.com/comment/91745909
has comment: http://stackoverflow.com/comment/91745863
tagged with: python
upvote count: 2
answer count: 3
downvote count: 1
has answer: http://stackoverflow.com/a/52401007

http://stackoverflow.com/comment/91513945
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52282538
has text: That looks like a datetime variable, not a date. Should the value be January 5, 2011 22:59:07?
score: 0

http://stackoverflow.com/q/52328581
has comment: http://stackoverflow.com/comment/91604191
has answer: http://stackoverflow.com/a/52328992
has comment: http://stackoverflow.com/comment/91604153
accepted answer: http://stackoverflow.com/a/52328992
has comment: http://stackoverflow.com/comment/91604148
has comment: http://stackoverflow.com/comment/91604098
has comment: http://stackoverflow.com/comment/91604205
has body: I an trying to scrape an application off of the fareham.gov.uk web page and every time I try it returns an error instead of the reference number. Can somebody help me to fix this problem? I am new to web scraping and whenever I try to google a fix nothing worked. Error: Traceback (most recent call last): File "C:\Users\DBaldwin\Desktop\sel.py", line 39, in <module> div = soup.select(' Reference ') File "C:\Users\DBaldwin\Anaconda3\lib\site-packages\bs4\element.py", line 1477, in select 'Unsupported or invalid CSS selector: "%s"' % token) ValueError: Unsupported or invalid CSS selector: "<div" Code: import time import urllib.request from bs4 import BeautifulSoup from selenium import webdriver url = "http://www.fareham.gov.uk/casetrackerplanning/applicationsearch.aspx" driver = webdriver.Chrome(executable_path=r"C:\Users\DBaldwin\Desktop\chromedriver.exe") driver.get(url) driver.find_element_by_id("lnkAllowCookies").click() def rerun(): driver.find_element_by_id("BodyPlaceHolder_uxLinkButtonShowAdvancedSearch").click() time.sleep(3) driver.find_element_by_id("uxStartDateDecisionTextBox").click() driver.find_element_by_id("uxStartDateDecisionTextBox").clear() driver.find_element_by_id("uxStartDateDecisionTextBox").send_keys("1/8/2018") driver.find_element_by_id("uxStopDateDecisionTextBox").click() driver.find_element_by_id("uxStopDateDecisionTextBox").clear() driver.find_element_by_id("uxStopDateDecisionTextBox").send_keys("308/2018") driver.find_element_by_id("BodyPlaceHolder_uxButtonSearch").click() time.sleep(3) rerun() elements = driver.find_elements_by_class_name("searchResultsCell") for e in elements: e.click() newUrl = driver.current_url go = urllib.request.urlopen(newUrl) soup = BeautifulSoup(go.read(), "html.parser") div = soup.select(' Reference ') test = div[0].get_text() print(test) driver.back() rerun() print("Worked???")
answer count: 1
has comment: http://stackoverflow.com/comment/91604291
tagged with: beautifulsoup
score: 0
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91604268
has comment: http://stackoverflow.com/comment/91604261
tagged with: selenium
tagged with: web-scraping
has title: Python - Beautifulsoup | ValueError: Unsupported or invalid CSS selector: "<div"
type: Question

http://stackoverflow.com/a/52293704
has body: You are writing double-encoded JSON to the child process: message = '{"header":{"protocolVersion":1,"messageID":2,"stationID":400}, the rest of json...}}'; jsonValue = json.dumps(message) message is already a JSON string, so jsonValue is a double-encoded JSON string. The pipe consumer pushes this double-encoded string into the queue for the socket. Next, the websocket producer in socket_producer() encodes the message again: while True: message = await incoming.get() # ... json_message = json.dumps(message) await socket.send(json_message) So now json_message is a triple-encoded JSON value, a JSON document containing a JSON document containing a JSON document: &gt;&gt;&gt; import json &gt;&gt;&gt; message = '{"header":{"protocolVersion":1,"messageID":2,"stationID":400}}}' # valid JSON &gt;&gt;&gt; json_message = json.dumps(message) &gt;&gt;&gt; print(json_message) # double-encoded "{\"header\":{\"protocolVersion\":1,\"messageID\":2,\"stationID\":400}}}" &gt;&gt;&gt; json_message = json.dumps(json_message) # encode *again* &gt;&gt;&gt; print(json_message) # triple-encoded "\"{\\\"header\\\":{\\\"protocolVersion\\\":1,\\\"messageID\\\":2,\\\"stationID\\\":400}}}\"" I don't know exactly what your web socket does with this, but lets assume that it uses json.loads() once, then echoes the decoded message back. This means that socket_consumer() receives the a JSON document that's encoded just twice. Your FromSocket.txt log certainly implies that this is what happens, because it contains a double encoded JSON message: You can see this in your FromSocket.txt log: From socket: "{\"header\":{\"protocolVersion\":1,\"messageID\":2,\"stationID\":400},\"cam\":{\"generationDeltaTime\":1,...other fields}}" Note those \" entries, and the whole document is wrapped in quotes, but there are no \\\ triple-backslashes in the value. Still, this extra layering of JSON encoding breaks the pipe_producer() coroutine, which expects the message to decode to a dictionary, not another string (even i…
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91571370
has comment: http://stackoverflow.com/comment/91564417
has comment: http://stackoverflow.com/comment/91566911
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/91567214
answers question: http://stackoverflow.com/q/52291218
has comment: http://stackoverflow.com/comment/91570738
has comment: http://stackoverflow.com/comment/91566368
has comment: http://stackoverflow.com/comment/91564516
score: 2
accepted answer of: http://stackoverflow.com/q/52291218
has comment: http://stackoverflow.com/comment/91564319
has comment: http://stackoverflow.com/comment/91573842

http://stackoverflow.com/q/52366673
accepted answer: http://stackoverflow.com/a/52367241
has comment: http://stackoverflow.com/comment/91678034
has comment: http://stackoverflow.com/comment/91677663
type: Question
has answer: http://stackoverflow.com/a/52367241
has title: Calculate time shift between two signals and shifting
tagged with: matplotlib
score: 0
has comment: http://stackoverflow.com/comment/91677878
answer count: 1
has comment: http://stackoverflow.com/comment/91677980
has comment: http://stackoverflow.com/comment/91677930
has body: I have a temperature sensor and a strain sensor, I would like to calculate the time delay between the two sensors. def process_data_time_delay(temperature, strain, normal_data): from scipy import signal T1 = temperature['T1'].tolist() S1 = strain[0] time = normal_data['TIMESTAMP'].tolist() fig = plt.figure() plt.plot(time, T1, 'r') plt.plot(time, S1, 'b') shift = (np.argmax(signal.correlate(T1, S1))) fig = plt.figure() plt.plot(time, T1 - shift) plt.show() I have a strange and strange output graph. Here is a sample data https://pastebin.com/eEd6MTL0 According to the excellent answer I have modified the code to calculate the time delay between the two signals. def process_data_time_delay(temperature, strain, df): from scipy import signal # normalization before ACF def normalize(data): return (data - np.mean(data, axis=0).reshape((1, -11))) / (np.std(data, axis=0).reshape((1, -1))) # select subset of columns, seems relevant as a group SCOLS = ['T1', 'W_A1'] # just to see the data f = plt.figure() ax = f.add_subplot(111) df[SCOLS[:2]].iloc[::10].plot(ax=ax) ax.set_title('Raw data') # normalization normalized = normalize(df[SCOLS].values) f = plt.figure() ax = f.add_subplot(111) ax.plot(np.arange(normalized.shape[0]), normalized[:, 0], label='TW_A1') ax.plot(np.arange(normalized.shape[0]), normalized[:, 1], label='W_A1') ax.set_title('Normalized') # ACF between two components x1x2 = np.correlate(normalized[:, 0], normalized[:, 1], 'full') # see the results f = plt.figure() ax = f.add_subplot(111) ax.plot(x1x2) ax.set_title('ACF') df['TIMESTAMP'] = pd.to_datetime(df['TIMESTAMP']) peaks_indices = signal.find_peaks_cwt(np.array(x1x2), np.arange(1, len(x1x2))) print(peaks_indices) delta_index = np.argmax(peaks_indices); delta_time = df['TIMESTAMP'][delta_index] - df['TIMESTAMP'][0] # assuming timestamps is a datetime64 numpy array that can be easily obtained from pandas; shifted_signal = x1x2[delta_time:] f = plt.figure() ax = f.add_subplot(111) ax.plot(shifted_signal) # ma…
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91678138
has comment: http://stackoverflow.com/comment/91677598

http://stackoverflow.com/q/52407467
upvote count: 0
score: -1
has answer: http://stackoverflow.com/a/52452374
accepted answer: http://stackoverflow.com/a/52452374
answer count: 1
favorite count: 0
has body: I am trying to crawl a specific item from a particular website. The Code snippet is as follows: # Constant Div Path variables for Parameters. pathForMovieCardContainer = '//div[@class="card-container wow fadeIn movie-card-container"]' pathForMovieName = 'div[@class="card-container wow fadeIn movie-card-container"]//div[@class="cards"]//div[@class="card-details"]//div[@class="card-right"]//div[@class="card-title"]/text()' str_slash = "/" movies_dict = [] movies = response.xpath(pathForMovieCardContainer).extract() for movie in movies: print("***********************") print(movie) mov = TestDataCrawlersItem() mov['name'] = Selector(text=movie).xpath(pathForMovieName).extract() I am unable to get the text from the path 'div[@class="card-container wow fadeIn movie-card-container"]//div[@class="cards"]//div[@class="card-details"]//div[@class="card-right"]//div[@class="card-title"]/text()' I am not sure if my pathForMovieName is constructed properly. Can some one help me with this? Thanks!
has title: How do i parse this specific html body using selector in scrapy?
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/95931243
has comment: http://stackoverflow.com/comment/91779010
has comment: http://stackoverflow.com/comment/91758726
tagged with: web-crawler
tagged with: scrapy
downvote count: 1
type: Question

http://stackoverflow.com/comment/102878341
type: AnswerComment
type: Comment
score: 0
has text: Ugh.. Can't add answer :( Is it because it's marked as duplicate? Personally I don't agree with the duplicate mark, it's much different wording and shorter question
comment on: http://stackoverflow.com/a/52273900

http://stackoverflow.com/q/52292482
has comment: http://stackoverflow.com/comment/91532929
has comment: http://stackoverflow.com/comment/91532957
has comment: http://stackoverflow.com/comment/91533245
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/52292639
has comment: http://stackoverflow.com/comment/91533195
favorite count: 0
accepted answer: http://stackoverflow.com/a/52293102
has title: Weird behaviour in random.choice
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91533306
tagged with: python
upvote count: 1
has comment: http://stackoverflow.com/comment/91533110
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91533183
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52293102
has body: I'm trying to randomly reorder an Array using my scramble function: def scramble(arr): arr_len = len(arr) container = [None]*arr_len indexes = [i for i in range(arr_len)] print(random.choice(indexes)) # works as expected for i in range(arr_len): my_choice = None while not my_choice: my_choice = random.choice(indexes) print(my_choice) # always None if my_choice is not None: indexes[my_choice] = None container[my_choice] = arr[my_choice] print(container) scramble([2,3,4,5,6]) The issue that I'm facing is that my_choice variable is always containing None. Can anyone please point out what I'm missing?
has answer: http://stackoverflow.com/a/52292639

lambda
tags question: http://stackoverflow.com/q/52393566
tags question: http://stackoverflow.com/q/52399690
tags question: http://stackoverflow.com/q/52310283
tags question: http://stackoverflow.com/q/52398738
tags question: http://stackoverflow.com/q/52369437
tags question: http://stackoverflow.com/q/52344055
tags question: http://stackoverflow.com/q/52401988
tag name: lambda
tags question: http://stackoverflow.com/q/52276666
type: Tag
tags question: http://stackoverflow.com/q/52276620
tags question: http://stackoverflow.com/q/52387563
tags question: http://stackoverflow.com/q/52427357

http://stackoverflow.com/q/52339399
has answer: http://stackoverflow.com/a/52339466
accepted answer: http://stackoverflow.com/a/52339466
answer count: 2
has body: When the keys in a dictionary comprehension is the same, I want their values to be added up. For example, &gt;&gt;&gt; dct = {-1: 1, 0: 2, 1: 3} &gt;&gt;&gt; {k**2: v for k, v in dct.items()} {1: 3, 0: 2} However, what I want to get in this case is {1: 4, 0: 2}, because both the square of 1 and -1 is 1, and 1 + 3 = 4. Clearly, I can do it with a for loop, but is there a shorthand?
has comment: http://stackoverflow.com/comment/91627877
tagged with: dictionary-comprehension
score: 0
has comment: http://stackoverflow.com/comment/91627851
tagged with: python
has comment: http://stackoverflow.com/comment/91626095
tagged with: merge
has answer: http://stackoverflow.com/a/52339634
tagged with: dictionary
has title: Summing instead of overriding values in dictionary comprehension
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91628006
has comment: http://stackoverflow.com/comment/91627143
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91628042
possible better answer: http://stackoverflow.com/a/52339634

http://stackoverflow.com/comment/91635026
comment on: http://stackoverflow.com/a/52341596
type: Comment
has text: But the class is not created yet
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91623973
has text: Ops. The work =) But i cannot read return data? I try .extract() return all html
comment on: http://stackoverflow.com/q/52338156
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91648991
type: Comment
type: QuestionComment
has text: Yeah you need to remove brackets now that you have a dictionary. It should be `pd.concat(data, axis=0, ignore_index=True)`
score: 1
comment on: http://stackoverflow.com/q/52351616

http://stackoverflow.com/comment/91635910
type: Comment
has text: I think so. I tried to explain the reason in the answer.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52344406

http://stackoverflow.com/comment/91698592
comment on: http://stackoverflow.com/q/52376942
has text: I'm not sure if related, but you have never closed `file_in`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91619556
type: Comment
comment on: http://stackoverflow.com/q/52320969
score: 0
type: QuestionComment
has text: I've added the 'Computer Modern' ttf to the data directory for matplotlib and those files are showing up in the `fontsList.json` file as well.

http://stackoverflow.com/a/52288631
has body: There's been some great comments from people more knowledgable of the specifics of kernels and processes and memory than I! Check them out. I don't really have a definitive answer for you but I can hopefully shed some light here: The cause of the memory usage, and hence the out of memory exception, is explained at this SO anwer: Python memory allocation error using subprocess.Popen. this is a very common problem in Unix, and actually has nothing to do with python or bioinformatics. A call to os.fork() temporarily doubles the memory of the parent process (the memory of the parent process must be available to the child process), before throwing it all away to do an exec(). While this memory isn't always actually copied, the system must have enough memory to allow for it to be copied, and thus if you're parent process is using more than half of the system memory and you subprocess out even "wc -l", you're going to run into a memory error. You should look at implementing this perl script in Python and using that module/package in your view, avoid using another thread/process in your request-response cycle to handle this. Another thing that may or may not be relevant, if this is a long running job or CPU intensive task, you should consider processing this in a background job using something like Celery or Python RQ. This keeps your server responding to requests fast and avoids a backlog of requests, so to avoid a situation where 20 requests are still being worked on because this long running task is doing its job and hence no-one else can access the server. The choice of using workers would depend on your needs, deadlines, etc.
has comment: http://stackoverflow.com/comment/91525680
downvote count: 1
has comment: http://stackoverflow.com/comment/91526413
upvote count: 0
has comment: http://stackoverflow.com/comment/91525254
has comment: http://stackoverflow.com/comment/91525972
has comment: http://stackoverflow.com/comment/91525660
score: -1
type: Answer
has comment: http://stackoverflow.com/comment/91525805
has comment: http://stackoverflow.com/comment/91528312
answers question: http://stackoverflow.com/q/52288485
has comment: http://stackoverflow.com/comment/91525791
has comment: http://stackoverflow.com/comment/91525926

http://stackoverflow.com/comment/91639697
has text: Please [edit](https://stackoverflow.com/posts/52347018/edit) your question to add code there.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52347018

http://stackoverflow.com/q/52306592
has comment: http://stackoverflow.com/comment/91560401
tagged with: python
answer count: 1
has title: How to retrieve variable in def __init__ in Python
has comment: http://stackoverflow.com/comment/91560579
has comment: http://stackoverflow.com/comment/91560436
has comment: http://stackoverflow.com/comment/91560568
has comment: http://stackoverflow.com/comment/91560634
has answer: http://stackoverflow.com/a/52306640
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/91560565
tagged with: variables
has comment: http://stackoverflow.com/comment/91560505
has comment: http://stackoverflow.com/comment/91560545
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/91560701
accepted answer: http://stackoverflow.com/a/52306640
has comment: http://stackoverflow.com/comment/91560616
score: -2
has comment: http://stackoverflow.com/comment/91560404
has comment: http://stackoverflow.com/comment/91560750
has comment: http://stackoverflow.com/comment/91560662
has comment: http://stackoverflow.com/comment/91560685
downvote count: 2
has body: I need to retrieve a variable inside the def __init__. The code as below: class HuffmanCode(object): def __init__(self, probabilities, digits): self.probabilities = probabilities #print (self.probabilities) self.huffman = huffman_nary_dict(probabilities, digits) #print (self.huffman) self.inv_huffman = inverse_dict(self.huffman) I need to call self.inv_huffman outside the class HuffmanCode. self.inv_huffman is a set of dictionary for the specific character that I need to retrieve. self.inv_huffman = {'m': '110', 'a': '0', 's': '10', 'y': '111'}

http://stackoverflow.com/a/52426234
answers question: http://stackoverflow.com/q/52425332
score: 4
has comment: http://stackoverflow.com/comment/91799818
has comment: http://stackoverflow.com/comment/91798610
has comment: http://stackoverflow.com/comment/91799477
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91799634
has comment: http://stackoverflow.com/comment/91798798
has comment: http://stackoverflow.com/comment/91798695
type: Answer
has body: You can use pd.concat to join groupby results and then apply sum: &gt;&gt;&gt; pd.concat([xd0,xd1],axis=1) export export origin dest year aus ind 2000 6 6 2001 8 8 chn aus 2001 40 40 ind aus 2000 19 19 2001 42 42 2002 30 30 chn 2000 9 9 2001 13 13 2002 14 14 &gt;&gt;&gt; pd.concat([xd0,xd1],axis=1).sum(axis=1) origin dest year aus ind 2000 12 2001 16 chn aus 2001 80 ind aus 2000 38 2001 84 2002 60 chn 2000 18 2001 26 2002 28
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52425332
has comment: http://stackoverflow.com/comment/91799284

http://stackoverflow.com/a/52420983
has comment: http://stackoverflow.com/comment/91785289
has comment: http://stackoverflow.com/comment/91785155
answers question: http://stackoverflow.com/q/52420714
score: 0
type: Answer
has body: I think you should try running docker-compose in detach mode : docker-compose up -d -d, --detach Detached mode: Run containers in the background, print new container names. Incompatible with --abort-on-container-exit. See https://docs.docker.com/compose/reference/up/

http://stackoverflow.com/comment/91717837
score: 0
comment on: http://stackoverflow.com/a/52385950
type: Comment
has text: you want to put then names ON the map at all time?
type: AnswerComment

http://stackoverflow.com/q/52410291
has body: def function(x+4): return (x*5)+3 SyntaxError: invalid syntax Why is that? i don't get the logic behind it? (i know that it is a simple question but i couldn't find an answer to it. i got many unclear feedbacks about my question,i am sorry about that as english is not my first language i couldn't clarify my question in short: While i was learning about what return does,i compromised the logic with the logic behind f(x)= codomain as def function(x) = return codomain but as you know there are functions in maths like f(x+2) = 5x+3. I thought maybe i could do the same on def function,the problem was it was giving a syntax error ,and i was curious about the design idea behind it and if there was an alternative solution to implement this in code.Thanks for answers!
has answer: http://stackoverflow.com/a/52410663
has comment: http://stackoverflow.com/comment/91764410
has comment: http://stackoverflow.com/comment/91765405
type: Question
tagged with: user-defined-functions
answer count: 2
tagged with: function
has comment: http://stackoverflow.com/comment/91764322
linked to: http://stackoverflow.com/q/3748592
downvote count: 4
has comment: http://stackoverflow.com/comment/91765882
accepted answer: http://stackoverflow.com/a/52410663
possible better answer: http://stackoverflow.com/a/52410608
has comment: http://stackoverflow.com/comment/91765098
has comment: http://stackoverflow.com/comment/91764541
has answer: http://stackoverflow.com/a/52410608
favorite count: 0
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/91764324
has comment: http://stackoverflow.com/comment/91764601
has comment: http://stackoverflow.com/comment/91764309
has title: Python:Why i can't put in e.g. (x+1) inside def function(here)?
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/91764739
type: AnsweredQuestion

http://stackoverflow.com/q/52297308
downvote count: 1
has comment: http://stackoverflow.com/comment/91542538
type: Question
has title: How to convert a pandas column to datetime
has answer: http://stackoverflow.com/a/52297394
tagged with: series
score: 0
answer count: 2
tagged with: pandas
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52297486
type: UnansweredQuestion
has body: I have a dataframe df df date 0 05/01/2017 1 04/01/2017 2 08/01/2017 3 03/01/2017 4 10/01/2017 I want to convert the column date from str to datetime I am doing like the following df['date'] = pd.to_datetime(df['date']) but it takes infinite time and if I try pd.to_datetime(df['date'][0]) I get the following error year is out of range
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/91542572
tagged with: performance

http://stackoverflow.com/comment/91644130
comment on: http://stackoverflow.com/q/52349325
has text: @GregM check my answer below where someone posted an answer .
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52413407
type: UnansweredQuestion
tagged with: python
tagged with: regex
downvote count: 1
has title: Python regex to find div tag content
upvote count: 1
type: Question
answer count: 2
has body: What pattern do you write to find the content between the tags? inputData = ' content and content ' pattern = ' (.*?) ' pattern_matcher = re.compile(pattern)
score: 0
has comment: http://stackoverflow.com/comment/91779680
has answer: http://stackoverflow.com/a/52413459
has comment: http://stackoverflow.com/comment/91771442
has comment: http://stackoverflow.com/comment/91792658
favorite count: 0
has answer: http://stackoverflow.com/a/52413530

http://stackoverflow.com/q/52426972
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52427136
has title: Pandas: Bin dates into 30 minute intervals and calculate averages
type: Question
tagged with: average
answer count: 2
possible better answer: http://stackoverflow.com/a/52427232
has answer: http://stackoverflow.com/a/52427232
downvote count: 0
has comment: http://stackoverflow.com/comment/91797873
tagged with: pandas
has comment: http://stackoverflow.com/comment/91797196
linked to: http://stackoverflow.com/q/41929772
has answer: http://stackoverflow.com/a/52427136
tagged with: python
has body: I have a Pandas dataframe with two columns which are speed and time. speed date 54.72 1:33:56 49.37 1:33:59 37.03 1:34:03 24.02 7:39:58 28.02 7:40:01 24.04 7:40:04 24.02 7:40:07 25.35 7:40:10 26.69 7:40:13 32.04 7:40:16 28.02 11:05:43 30.71 11:05:46 29.36 11:05:49 18.68 11:05:52 54.72 11:05:55 34.69 10:31:34 25.03 10:31:38 56.04 10:31:40 44.03 10:31:43 I want to calculate the average of speeds per bins of 30 minutes. For example, the average speed during the 4th bin (1:31 - 2:00) is (54.72 + 49.37 + 37.03)/3. I have thought of converting hours, minutes and seconds to seconds from 00:00 and then have bins of 1800 seconds. I have tried to do use binned_statistic from scipy.stats but my main issue is that I cannot find a way to separate bins based on date and get the average of speeds. Any ideas?
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91797459
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/91797297
tagged with: bins
has comment: http://stackoverflow.com/comment/91797300

http://stackoverflow.com/q/52308649
favorite count: 0
has body: I'm applying a number of regex patterns to text entries, and I wish for them to be automatically entered into a list. e.g. import re raw='NIH05484225_1_binders_list ID_054345 Proteincomplex /D1/ERBH1_ERV_ACWX' regex= '.*Proteincomplex /[\S]+\/([\S]+)_([\S]+)_([\S]+)' regex=re.compile(regex) result = re.match(regex, raw) answer=[] answer.append (result.group(1)) answer.append (result.group(2)) answer.append (result.group(3)) print (answer) Is there a way to have answer collect all the captured results? As in answer.extend (result.allgroups()) # does not work, of course
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/91564425
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/52308757
upvote count: 2
score: 0
has comment: http://stackoverflow.com/comment/91564524
downvote count: 2
has title: How to simultaneously collect all captured substrings using re.match() ?
has answer: http://stackoverflow.com/a/52308757
answer count: 1
has comment: http://stackoverflow.com/comment/91564405

django-forms
tags question: http://stackoverflow.com/q/52361744
tags question: http://stackoverflow.com/q/52402791
tags question: http://stackoverflow.com/q/52333867
tags question: http://stackoverflow.com/q/52335510
tags question: http://stackoverflow.com/q/52376115
tags question: http://stackoverflow.com/q/52275690
tags question: http://stackoverflow.com/q/52304057
tag name: django-forms
type: Tag
tags question: http://stackoverflow.com/q/52327186
tags question: http://stackoverflow.com/q/52368870
tags question: http://stackoverflow.com/q/52376675
tags question: http://stackoverflow.com/q/52273087
tags question: http://stackoverflow.com/q/52366158
tags question: http://stackoverflow.com/q/52384271
tags question: http://stackoverflow.com/q/52371384

http://stackoverflow.com/comment/91706050
has text: Please provide [all the means to reproduce the problem, including your configuration, exact command and full output](/help/mcve).
comment on: http://stackoverflow.com/q/52380558
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91632345
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52342430
type: Comment
has text: Are you importing anything from this file to any other file? If so, what?

http://stackoverflow.com/comment/96766494
comment on: http://stackoverflow.com/q/52297550
score: 0
type: Comment
type: QuestionComment
has text: @Melike unfortunately, no. My problem wasn't resolved in the end

http://stackoverflow.com/comment/91557920
type: QuestionComment
has text: Forgot to mention : installed everything with brew.
comment on: http://stackoverflow.com/q/52305171
score: 0
type: Comment

http://stackoverflow.com/comment/91619157
comment on: http://stackoverflow.com/q/52335418
has text: something like [that](https://gist.github.com/gagareg/0af52b849944eabb71865ba8d2155f27)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52274852
type: Question
accepted answer: http://stackoverflow.com/a/52274967
answer count: 1
score: 0
has body: I'm learning sqlite3 with python, but I've been facing this error: "sqlite3.OperationalError: no such table: store". How do I get around this? import sqlite3 def create_table(): #function to create the table conn = sqlite3.connect('lite.db') cur = conn.cursor() # creating th cursor object cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)") conn.commit() conn.close() def insert(item, quantity, price ): #function to insert into the table conn = sqlite3.connect('lite.db') cur = conn.cursor() # creating th cursor object cur.execute("INSERT INTO store VALUES(?,?,?)", (item, quantity, price)) conn.commit() conn.close() insert("biscuits",500,20000) def view(): conn = sqlite3.connect('lite.db') cur = conn.cursor() cur.execute("SELECT * FROM store") rows = cur.fetchall() return rows conn.close() print(view())
has answer: http://stackoverflow.com/a/52274967
tagged with: sqlite
tagged with: python
type: AnsweredQuestion
has title: sqlite3.OperationalError: no such table: store

http://stackoverflow.com/q/52314599
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has body: I have a seaborn heatmap that I am building from a matrix of values. Each element of the matrix corresponds to an entitiy that I would like to make the tick label for each row/col in the matrix. I tried using the ax.set_xticklabel() function to accomplish this but it seems to do nothing. Here is my code: type(jr_matrix) &gt;&gt;&gt; numpy.ndarray jr_matrix.shape &gt;&gt;&gt; (15, 15) short_cols = ['label1','label2',...,'label15'] # list of strings with len 15 fig, ax = plt.subplots(figsize=(13,10)) ax.set_xticklabels(tuple(short_cols)) # i also tried passing a list ax.set_yticklabels(tuple(short_cols)) sns.heatmap(jr_matrix, center=0, cmap="vlag", linewidths=.75, ax=ax, norm=LogNorm(vmin=jr_matrix.min(), vmax=jr_matrix.max())) The still has the matrix indices as labels: Any ideas on how to correctly change these labels would be much appreciated. Edit: I am doing this using jupyter notebooks if that matters.
upvote count: 1
answer count: 1
has title: Relabel axis ticks in seaborn heatmap
favorite count: 0
has comment: http://stackoverflow.com/comment/91576727
tagged with: seaborn
tagged with: python
tagged with: jupyter
has answer: http://stackoverflow.com/a/52314835
accepted answer: http://stackoverflow.com/a/52314835

http://stackoverflow.com/comment/91795829
comment on: http://stackoverflow.com/q/52423443
type: Comment
type: QuestionComment
score: 0
has text: @VaisakhPS a lambda function in a public subnet will not have Internet access, since lambda functions don't get public IP addresses assigned to them regardless of subnet they are in. If the Lambda is in a VPC, then it must be in a private subnet with a NAT gatetway in order to have Internet access.

http://stackoverflow.com/comment/91686138
comment on: http://stackoverflow.com/q/52370708
score: 1
type: Comment
type: QuestionComment
has text: Why not `for i, f in enumerate(os.listdir()):`. That way you have both and it's pythonic. Do you want this numbers to be in a random order?

http://stackoverflow.com/comment/91712358
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52383948
has text: FYI: https://www.geeksforgeeks.org/find-length-period-decimal-value-1n/ lacks a Python Implementation for that.
type: Comment

http://stackoverflow.com/a/56436037
type: Answer
score: 1
upvote count: 1
has body: If you used a Procfile in deployment, make sure it does not have an extension such as .txt. If it does, you might try: Deleting that Procfile.txt. Creating a new Procfile without the extension. Pushing the new files to Heroku.
answers question: http://stackoverflow.com/q/52423143
downvote count: 0

http://stackoverflow.com/q/52337636
has comment: http://stackoverflow.com/comment/91835234
tagged with: tensor
has comment: http://stackoverflow.com/comment/91629341
accepted answer: http://stackoverflow.com/a/52489422
has comment: http://stackoverflow.com/comment/91665047
tagged with: python
has title: adding data to decoder in autoencoder during learning
type: AnsweredQuestion
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/91833774
has comment: http://stackoverflow.com/comment/91682381
score: 4
has answer: http://stackoverflow.com/a/52489422
has body: I want to implement an autoencoder using Keras and this structure is a large network that some operations is done on the output of autoencoder and then we should consider two loss I attached an image that shows my proposed structure. the link is below. autoencoder structure w has the same size as the input image and in this autoencoder, I do not use max pooling so the output of each phase has the same size as the input image. I want to send w and latent space representation to decoder part and then after adding a noise to the decoder output try to extract w using third part of the network. so I need that my loss function considers the difference between the input image and latent space representation and also between w and w'. but I have several problems with implementation. I do not know how can I add w to the decoder output, due to using this line "merge_encoded_w=cv2.merge(encoded,w) " produce an error and does not work. I do not sure my loss function is true based on what I need or not?please help me with this code. I am a beginner and finding the solution is difficult for me. I asked this question before but no one help me with this. please guide me. my code is as below: from keras.models import Sequential from keras.layers import Input, Dense, Dropout, Activation,UpSampling2D,Conv2D, MaxPooling2D, GaussianNoise from keras.models import Model from keras.optimizers import SGD from keras.datasets import mnist from keras import regularizers from keras import backend as K import keras as k import numpy as np import matplotlib.pyplot as plt import cv2 from time import time from keras.callbacks import TensorBoard # Embedding phase ##encoder w=np.random.random((1, 28,28)) input_img = Input(shape=(28, 28, 1)) # adapt this if using `channels_first` image data format x = Conv2D(8, (5, 5), activation='relu', padding='same')(input_img) #x = MaxPooling2D((2, 2), padding='same')(x) x = Conv2D(4, (3, 3), activation='relu', padding='same')(x) #x = MaxPooling2D((2, 2), padding=…
upvote count: 4
tagged with: keras-layer
has comment: http://stackoverflow.com/comment/91910729
answer count: 1
has comment: http://stackoverflow.com/comment/91842284
downvote count: 0
tagged with: keras
favorite count: 0

http://stackoverflow.com/a/52338063
has body: yes it will return the array of shape (57,). If you want to be as (57,1) , you can do it so by reshape(). col1=(result[:, 1]).reshape(-1,1)
type: Answer
answers question: http://stackoverflow.com/q/52337931
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/91692616
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52372410
type: Comment
has text: well if you have a python installed that didn't come from anaconda, you can certainly try make a virtual environment, activate it & install those modules with pip so you can run your app there.

python-3.6
tags question: http://stackoverflow.com/q/52383948
tags question: http://stackoverflow.com/q/52371167
tags question: http://stackoverflow.com/q/52367335
tags question: http://stackoverflow.com/q/52417440
tags question: http://stackoverflow.com/q/52382999
tags question: http://stackoverflow.com/q/52424001
tags question: http://stackoverflow.com/q/52366226
tags question: http://stackoverflow.com/q/52325263
tags question: http://stackoverflow.com/q/52346711
tags question: http://stackoverflow.com/q/52352226
type: Tag
tags question: http://stackoverflow.com/q/52350978
tags question: http://stackoverflow.com/q/52303658
tags question: http://stackoverflow.com/q/52389350
tags question: http://stackoverflow.com/q/52412777
tags question: http://stackoverflow.com/q/52417794
tags question: http://stackoverflow.com/q/52286719
tags question: http://stackoverflow.com/q/52411294
tags question: http://stackoverflow.com/q/52309772
tags question: http://stackoverflow.com/q/52297574
tags question: http://stackoverflow.com/q/52306739
tags question: http://stackoverflow.com/q/52274071
tags question: http://stackoverflow.com/q/52408841
tags question: http://stackoverflow.com/q/52416268
tags question: http://stackoverflow.com/q/52336862
tags question: http://stackoverflow.com/q/52336742
tags question: http://stackoverflow.com/q/52332969
tags question: http://stackoverflow.com/q/52423254
tags question: http://stackoverflow.com/q/52428109
tag name: python-3.6
tags question: http://stackoverflow.com/q/52296586
tags question: http://stackoverflow.com/q/52350850
tags question: http://stackoverflow.com/q/52374356
tags question: http://stackoverflow.com/q/52404656
tags question: http://stackoverflow.com/q/52355348
tags question: http://stackoverflow.com/q/52344889
tags question: http://stackoverflow.com/q/52372152
tags question: http://stackoverflow.com/q/52282780
tags question: http://stackoverflow.com/q/52375251

http://stackoverflow.com/q/52334053
has body: I am trying to write code in python to rename a file by using NAME_COMPUTERNAME_ and then the current date. I have the following code: PCname=socket.gethostname() date_now = datetime.now().strftime'%d%m%Y') file_one = "C:\\Reports\\Report.pdf" file_two = 'C:\\Reports\\VSR_(PCname)_{}.pdf'.format(date_now) os.rename(file_one, file_two) I can rename the file with just VSR_14092018.pdf but I would like to include the computername also after VSR in the file's name. Thanks
possible better answer: http://stackoverflow.com/a/52334188
has answer: http://stackoverflow.com/a/52334188
tagged with: python
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/52334192
score: 0
has answer: http://stackoverflow.com/a/52334192
answer count: 3
has title: Rename File using computer name and current date using Python
has answer: http://stackoverflow.com/a/52334229

http://stackoverflow.com/a/52328232
downvote count: 0
has body: We can first define a function that adds a integer to a string and returns a string, padded with zeros to keep the same length: def add_to_string(s, n): total = int(s)+n return '{:0{}}'.format(total, len(s)) add_to_string('003', 2) #'005' add_to_string('00030', 12 ) #'00042 We can then use re.sub with a replacement function. We use the regex r"(?&lt;=/)\d{3}(?=/)" that matches a group of 3 digits, preceded and followed by /, without including them in the match. The replacement function takes a match as parameter, and returns a string.You could hardcode it, like this: import re def add_5_and_replace(match): return add_to_string(match.group(0), 5) url = 'https://nasa.gov/archive/allData/6/MYD021KM/2018/002/MYD021KM.hdf' new = re.sub(r"(?&lt;=/)\d{3}(?=/)", add_5_and_replace, url) print(new) # https://nasa.gov/archive/allData/6/MYD021KM/2018/007/MYD021KM.hdf But it could be better to pass the value to add. Either use a lambda: def add_and_replace(match, n=1): return add_to_string(match.group(0), n) url = 'https://nasa.gov/archive/allData/6/MYD021KM/2018/002/MYD021KM.hdf' new = re.sub(r"(?&lt;=/)\d{3}(?=/)", lambda m: add_and_replace(m, n=5), url) Or a partial function. A complete solution could then be: import re from functools import partial def add_to_string(s, n): total = int(s)+n return '{:0{}}'.format(total, len(s)) def add_and_replace(match, n=1): return add_to_string(match.group(0), n) url = 'https://nasa.gov/archive/allData/6/MYD021KM/2018/002/MYD021KM.hdf' new = re.sub(r"(?&lt;=/)\d{3}(?=/)", partial(add_and_replace, n=3), url) print(new) # https://nasa.gov/archive/allData/6/MYD021KM/2018/005/MYD021KM.hdf If you only want to add the default value 1 to your number, you can simply write new = re.sub(r"(?&lt;=/)\d{3}(?=/)", add_and_replace, url) print(new) # https://nasa.gov/archive/allData/6/MYD021KM/2018/003/MYD021KM.hdf
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52326825
has comment: http://stackoverflow.com/comment/91614389
accepted answer of: http://stackoverflow.com/q/52326825
type: Answer
has comment: http://stackoverflow.com/comment/91614045

http://stackoverflow.com/q/52354705
answer count: 1
tagged with: sublimetext3
type: UnansweredQuestion
tagged with: python
has body: I am using windows 10 operating system. I had downloaded and installed Ananconda python 3.6 version for windows 64 bit. I had added Anaconda to windows path manually. The current path is as below. I have also added the PYTHONPATH variable. The command py launches the python interpreter as below. But the command python fails with below error. How do I fix the issue. I am trying to run a simple hello World on sublime text but the same is failing with below error. 'python' is not recognized as an internal or external command, operable program or batch file. [Finished in 0.0s with exit code 1] [shell_cmd: python -u "D:\Python_Test\testprinting.py"] [dir: D:\Python_Test]
has comment: http://stackoverflow.com/comment/91654429
has comment: http://stackoverflow.com/comment/91691749
type: Question
has title: why python command does not invoke python interpreter in powershell though py is working
tagged with: powershell
has comment: http://stackoverflow.com/comment/91691329
has answer: http://stackoverflow.com/a/52430752
has comment: http://stackoverflow.com/comment/91667318
score: 0
has comment: http://stackoverflow.com/comment/91654582

http://stackoverflow.com/a/52341598
answers question: http://stackoverflow.com/q/52341182
downvote count: 0
type: Answer
has body: Everyone is writing short codes and meta classes while I barely write a decorator. (damn, lol) But I'm gonna share it anyways. from functools import wraps class CLOSED: _built_ins = [ '__add__', '__sub__', '__mul__', '__floordiv__', '__div__', '__truediv__', '__mod__', '__divmod__', '__pow__', '__lshift__', '__rshift__','__and__', '__or__', '__xor__', ] @staticmethod def register_closed(method): # Or you can use type annotations method.registered = True # Or you can add the method names as string to closed decorator return method # In this version you decorate the methods with this @staticmethod def closed_method(method, cls): @wraps(method) def wrapper(*a, **kw): return cls(method(*a, **kw)) return wrapper @classmethod def closed_class(klass, cls): for magic in klass._built_ins: _method = getattr(cls, magic, False) if _method: setattr(cls, magic, klass.closed_method(_method, cls)) for method in dir(cls): c1 = method not in klass._built_ins c2 = method not in dir(object) c3 = getattr(getattr(cls, method), 'registered', False) if all((c1, c2, c3)): _method = getattr(cls, method) setattr(cls, method, klass.closed_method(_method, cls)) return cls Now after you have this long setup, you just decorate the class as you would normally do; I am too sleepy to make it work with inherited classes so for now you have to decorate the class that inherits from a closed class. @CLOSED.closed_class class foo(int): @CLOSED.register_closed # or if you can simply add this to CLOSED.closed_class def bar(self, other): # if you are certain that every method can be casted to its own class """Basically just the __add__ method""" return self + other print(type(foo(1) + foo(1))); print(foo(1) + foo(1)) # &lt;class '__main__.foo'&gt; 2 print(type(foo(1).bar(2))); print(foo(1).bar(2)) # &lt;class '__main__.foo'&gt; 3 @CLOSED.closed_class class baz(foo): pass print(type(baz(1) + baz(3))); print(baz(1) + baz(3)) # &lt;class '__main__.baz'&gt; 4 print(type(baz(1).bar(4))); print(baz(1).bar(4)) # &…
score: 1
upvote count: 1

http://stackoverflow.com/q/52397920
tagged with: parsing
type: AnsweredQuestion
has body: I have json in a text file that is formatted like so: { "_id":"123adfvssw", "content_type":"video", "content_id":"12345", "commenter":{ "display_name":"student2", "name":"student2", "type":"user", }, "source":"chat", "state":"published", "message":{ "body":"the world", "fragments":[ { "text":"the world" } ], "is_action":false }, "more_replies":false } { "_id":"123adfvssw", "content_type":"video", "content_id":"12345", "commenter":{ "display_name":"student", "name":"student", "type":"user", }, "source":"chat", "state":"published", "message":{ "body":"the space", "fragments":[ { "text":"the space" } ], "is_action":false }, "more_replies":false } I would like to loop through the text file and count how many times the commenter field appears and save the results in another text file in the following format: For Example: FileName Commenters 2 I have some code but am getting stuck when it comes to counting the occurrence of the field names and not their values. import json import requests &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; filepath="/chatinfo.txt" &gt;&gt;&gt; with open(filepath) as f: ... for line in f: ... jsondata = json.loads(line) ... dictjson = json.dumps(jsondata) ... len(jsondata["commenter"]) However, len is counting the number of fields nested inside of the commenter field. Can anyone give me an idea of what I can use to count the occurrence of the commenter field name and possibly set up an exception if the commenter field isn't present?
upvote count: 1
accepted answer: http://stackoverflow.com/a/52397953
type: Question
has title: Can I "count" the number of times a field/name in a json file occurs using python? I do not need the value in the field but the name occurrence
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/52397953
downvote count: 4
answer count: 1
favorite count: 0
score: -3
tagged with: count
tagged with: python

http://stackoverflow.com/comment/91763482
type: Comment
has text: OK but what if the string is `"let’s test this`"?
type: AnswerComment
comment on: http://stackoverflow.com/a/52409900
score: 0

http://stackoverflow.com/a/52424017
has body: You can use the threading module to start a thread running your function with other code simultaneously. For example like this: import threading import time def PrintTime(): D = 1 M = 1 Y = 2019 print(D, "/", M, "/", Y) Time = 0 while Time &lt; 24: print("Background thread: Time=", Time) Time += 1 time.sleep(1) if Time == 24: Time = 0 D += 1 M += 1 if M in list[2, 4, 6, 9, 11] and D &gt; 30: D = 1 if M in list[1, 3, 5, 7, 8, 10, 12] and D &gt; 31: D = 1 if M &gt; 12: M = 1 thread = threading.Thread(target=PrintTime) thread.start() for i in range(10): print("do sth else", i) time.sleep(.7)
score: 1
has comment: http://stackoverflow.com/comment/92166239
answers question: http://stackoverflow.com/q/52423516
has comment: http://stackoverflow.com/comment/91795950
downvote count: 0
has comment: http://stackoverflow.com/comment/92215950
type: Answer
has comment: http://stackoverflow.com/comment/91822365
upvote count: 1

http://stackoverflow.com/comment/91609336
type: AnswerComment
type: Comment
has text: thanks for the answer! I forgot to mention that the number of lines in each object is varying too. Sorry about that. I edited my question to reflect that. Is there a way to do this without fixing the number of lines in a variabe?
comment on: http://stackoverflow.com/a/52331258
score: 0

http://stackoverflow.com/comment/91646868
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52350622
type: Comment
has text: @WaaberiIbrahim updated with some extra info. hope it helps.

http://stackoverflow.com/q/52304695
has answer: http://stackoverflow.com/a/76785406
has comment: http://stackoverflow.com/comment/91557417
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52304988
has title: Black bar covering my x labels for matplotlib plot?
has comment: http://stackoverflow.com/comment/91556880
accepted answer: http://stackoverflow.com/a/52304988
linked to: http://stackoverflow.com/q/332289
has comment: http://stackoverflow.com/comment/91557426
has answer: http://stackoverflow.com/a/52304778
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/91557371
favorite count: 0
possible better answer: http://stackoverflow.com/a/52304778
tagged with: python
has comment: http://stackoverflow.com/comment/91557389
type: AnsweredQuestion
score: 1
has body: I am trying to play a figure and I am having a black box pop up on the bottom of the plot where the x labels should be. I tried this command from a similar question on here in the past: from matplotlib import rcParams rcParams.update({'figure.autolayout': True}) But the problem was still the same. Here is my current code: import pylab from matplotlib import rcParams rcParams.update({'figure.autolayout': True}) df['date'] = df['date'].astype('str') pos = np.arange(len(df['date'])) plt.bar(pos,df['value']) ticks = plt.xticks(pos, df['value']) And my plot is attached here. Any help would be great!
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91557311

http://stackoverflow.com/comment/91794815
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52424527
has text: Is it not this the start in Machine learning? I am confused now

http://stackoverflow.com/comment/91696203
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52375516
has text: Thanks for the suggestion. I'm at my work computer and am stuck with 2.7.10, I would have to argue with IT to get 3.6. I'll keep that in mind as a last resort.
type: Comment

http://stackoverflow.com/q/52396650
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91738264
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52397462
has body: I am trying to build a horizontal bar chart for employees showing their scheduled hours worked vs. their actual hours worked for a given day. I have tried the following code but as you can see in the 'Plot' image below, it is concatenating the actual hours worked (blue) to the ends of the scheduled hours (green). Also the time's on the x axis are not very telling. What I am after is to have two bars for each employee, a green bar showing the scheduled hours at the top and a blue bar for the actual hours worked underneath, something like a gantt chart almost. Can anybody help me understand where I am going wrong in my code? #import stack import pandas as pd import datetime as dt import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates #dummy df df = pd.DataFrame([['Bob', '2018-09-14 9:00:00', '2018-09-14 18:00:00', 'actual'] , ['Bob', '2018-09-14 9:15:00', '2018-09-14 18:30:00', 'scheduled'] , ['Kim', '2018-09-14 9:00:00', '2018-09-14 18:00:00', 'actual'] , ['Kim', '2018-09-14 8:45:00', '2018-09-14 17:30:00', 'scheduled']] , columns=['name','start','finish', 'type']) #convert timestamp columns to datetime df'start', 'finish' = df'start', 'finish'.apply(pd.to_datetime) #scheduled time period scheduledStart = mdates.date2num(df['start'][(df['type'] == 'scheduled')].dt.to_pydatetime()) scheduledEnd = mdates.date2num(df['finish'][(df['type'] == 'scheduled')].dt.to_pydatetime()) scheduledWidth = scheduledEnd - scheduledStart #actual time period actualStart = mdates.date2num(df['start'][(df['type'] == 'actual')].dt.to_pydatetime()) actualEnd = mdates.date2num(df['finish'][(df['type'] == 'actual')].dt.to_pydatetime()) actualWidth = actualEnd - actualStart #y axis values yval = df['name'].unique() #generate plot fig, ax = plt.subplots() ax.barh(yval, width = actualWidth, left = actualStart, color = 'blue', height = 0.3, label = 'actual') ax.barh(yval, width = scheduledWidth, left = scheduledStart, color = 'green', height = 0.3, label = 'sc…
answer count: 1
downvote count: 0
favorite count: 0
tagged with: gantt-chart
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/52397462
has title: matplotlib barh for scheduled hours vs actual hours worked
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/91669228
type: QuestionComment
score: 1
has text: One issue is that you are calling `n_queens_helper(n, board)` but you are throwing away the result, which means it does nothing (the generator is actually run only when you try to iterate over it). Try to add `yield from n_queens_helper(n, board)`. Or use `for result in n_queens_helper(n, board): yield result` if you are using python<3.3. I'm not sure whether this is the only issue in your code, as such I'm not posting this as an answer.
type: Comment
comment on: http://stackoverflow.com/q/52362532

http://stackoverflow.com/comment/91742511
has text: the ordering is not important.
type: QuestionComment
comment on: http://stackoverflow.com/q/52399091
score: 0
type: Comment

http://stackoverflow.com/comment/91640772
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52347674
has text: Use `unique` with the `axis` kwd.

http://stackoverflow.com/q/52412177
has answer: http://stackoverflow.com/a/52412499
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: Regular expression to match between two strings?
has comment: http://stackoverflow.com/comment/91769008
has comment: http://stackoverflow.com/comment/91768202
tagged with: python
tagged with: regex
duplicate of: http://stackoverflow.com/q/24867342
type: AnsweredQuestion
has body: Regular Expression to match everything between the date and the closing square bracket: 2018-09-19 15:15:27,272 - AppLog - INFO - ****************************************** Log Report - Consume Cycle BWYgqW-ConsumeCycle ****************************************** Uptime: 11723.089329242706s Jobs Run: 281098 Jobs Current: 75 Q Avg Read Time: 0.014049809202426435 Q Msgs Read: 5347 Worker Load: ['0.92', '0.95', '0.99'] ****************************************** 2018-09-19 15:16:42,089 - AppLog - INFO - ****************************************** Log Report - Consume Cycle eehEes-ConsumeCycle ****************************************** Uptime: 11710.040764093399s Jobs Run: 287010 Jobs Current: 75 Q Avg Read Time: 0.006846889048917865 Q Msgs Read: 6649 Worker Load: ['0.99', '0.99', '0.98'] ****************************************** I have tried many regex to match between the date(2018-09-19) and closing square bracket ] (including). The dates will be changing along with the year as well. (I know that this is a repeated question but I am struggling a lot with this)
upvote count: 0
has comment: http://stackoverflow.com/comment/91768253
linked to: http://stackoverflow.com/q/24867342
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91768148
accepted answer: http://stackoverflow.com/a/52412499
score: -1
has comment: http://stackoverflow.com/comment/91768469
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91768578

http://stackoverflow.com/a/52391188
answers question: http://stackoverflow.com/q/52372118
has comment: http://stackoverflow.com/comment/113661596
type: Answer
downvote count: 2
upvote count: 1
has body: Mlflow's mlflow.keras and mlflow logging APIs persists your model and reload it as desired, which you presumably know and are doing it right. If you reload the model saved in h5 format, and supply your new input processed the minmax scalar, it should work. On another note, we have a mlflow-user group on google. Please post this there too. You can find the URL here:https://mlflow.org/#community Cheers Jules
score: -1

http://stackoverflow.com/q/52366753
tagged with: http://stackoverflow.com/tag/pdf
linked to: http://stackoverflow.com/q/8185438
answer count: 1
tagged with: python
type: AnsweredQuestion
tagged with: reportlab
type: Question
accepted answer: http://stackoverflow.com/a/52382430
linked to: http://stackoverflow.com/q/35184311
score: 0
tagged with: platypus
has answer: http://stackoverflow.com/a/52382430
has body: I am trying to create a pdf document with many pages. Each page contains an image on top of which are displayed texts with hyperlinks to other pages. I have managed to do this using reportlab.pdfgen and rectangle links, unfortunately the reader used (an e-reader) does not recognize this type of links. Instead of it, I managed to create text embedded hyperlinks (using How to add a link to the word using reportlab?) which are recognizes by my e-reader but I didn't manage to overlay them on an image. I tried to use the solution provided in this post (reportlab: add background image by using platypus) to use an image as background but it doesn't work. When I set the document's pagesize to the size of the image, the paragraph isn't shown. When I set it to a bigger size than the size of the image, the paragraph is shown above the image not overlaying it. Here's my code: from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import BaseDocTemplate, PageTemplate, Frame, Paragraph def draw_static(canvas, doc): # Save the current settings canvas.saveState() # Draw the image canvas.drawImage(r'path\to\the\image.png', 0, 0, width=500, height=500) # Restore setting to before function call canvas.restoreState() # Set up a basic template doc = BaseDocTemplate('test.pdf', pagesize=(500, 500)) # Create a Frame for the Flowables (Paragraphs and such) frame = Frame(doc.leftMargin, doc.bottomMargin, 500, 500, id='normal') # Add the Frame to the template and tell the template to call draw_static for each page template = PageTemplate(id='test', frames=[frame], onPage=draw_static) # Add the template to the doc doc.addPageTemplates([template]) # All the default stuff for generating a document styles = getSampleStyleSheet() story = [] link = ' Text ' P = Paragraph(link, styles["Normal"]) story.append(P) doc.build(story) PS: This code is not complete (doesn't create multiple pages, etc ...) but is just a minimal example for trying to overlay text embedded hyperlinks on …
has title: How to overlay text hyperlink on top of an image using reportlab?

http://stackoverflow.com/q/52357733
accepted answer: http://stackoverflow.com/a/52357768
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91660993
tagged with: python
has comment: http://stackoverflow.com/comment/91661551
type: AnsweredQuestion
has title: How to read from a text file and store multiple values to a key in dictionary
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/91660934
has comment: http://stackoverflow.com/comment/91660958
has body: My text file is of the form: ABC,_XYZ 45.1976844 -69.458819 AWA,_WES 44.946356 -90.315969 AXA,_WWA 36.3055851 -104.2588701 How do I store this in a dictionary with the letters including ',' and '_' are the keys and the numbers are two different values of that key.
has answer: http://stackoverflow.com/a/52357768

http://stackoverflow.com/q/52386849
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91761846
type: Question
tagged with: django-models
has comment: http://stackoverflow.com/comment/91718481
score: 0
has title: Django filter by field named 'id' in JSONField
has comment: http://stackoverflow.com/comment/91719450
has comment: http://stackoverflow.com/comment/91720174
has comment: http://stackoverflow.com/comment/91719176
has comment: http://stackoverflow.com/comment/91780535
has body: I have Django application and PostgreSQL database. My problem is that I cannot filter by field named 'id' in JSONField. My model looks like that: class SnapshotAuditing(models.Model): data = JSONField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) And I populate it like that: snapshot = SnapshotAuditing( data={ 'id': student.id, 'some_value': some_value, } ) snapshot.save() Than I want to perform the following select request: price_change = SnapshotAuditing.objects.filter( data__id=student.id ).order_by('created').first() But I get this error: bl/transfers.py:98: in get_coefficient_and_hours_unused data__id=student.id ../env2.7.14/lib/python2.7/site-packages/django/db/models/manager.py:85: in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ../env2.7.14/lib/python2.7/site-packages/django/db/models/query.py:784: in filter return self._filter_or_exclude(False, *args, **kwargs) ../env2.7.14/lib/python2.7/site-packages/django/db/models/query.py:802: in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) ../env2.7.14/lib/python2.7/site-packages/django/db/models/sql/query.py:1250: in add_q clause, _ = self._add_q(q_object, self.used_aliases) ../env2.7.14/lib/python2.7/site-packages/django/db/models/sql/query.py:1276: in _add_q allow_joins=allow_joins, split_subq=split_subq, ../env2.7.14/lib/python2.7/site-packages/django/db/models/sql/query.py:1210: in build_filter condition = self.build_lookup(lookups, col, value) ../env2.7.14/lib/python2.7/site-packages/django/db/models/sql/query.py:1102: in build_lookup lhs = self.try_transform(lhs, name, lookups) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = &lt;django.db.models.sql.query.Query object at 0x1182f6dd0&gt;, lhs = Col(student_snapshotauditing, student.SnapshotAuditing.data), name = 'id', rest_of_lookups = ['id'] de…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91719298
has comment: http://stackoverflow.com/comment/91718916
has comment: http://stackoverflow.com/comment/91719680
tagged with: django

http://stackoverflow.com/comment/91868885
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52402822
has text: Sorry for the late reply, but I would love to see that!
score: 0

http://stackoverflow.com/a/52387141
has comment: http://stackoverflow.com/comment/91721339
downvote count: 0
has body: You can concatenate two dataframes as one, after that you can remove all dupicates df1 ID B C D 0 A0 B0 C0 D0 1 A1 B1 C1 D1 2 A2 B2 C2 D2 3 A3 B3 C3 D3 cite_id ID B C D 4 A2 B4 C4 D4 5 A3 B5 C5 D5 6 A6 B6 C6 D6 7 A7 B7 C7 D7 pd.concat([df1,cite_id]).drop_duplicates(subset=['ID'], keep=False) Out: ID B C D 0 A0 B0 C0 D0 1 A1 B1 C1 D1 6 A6 B6 C6 D6 7 A7 B7 C7 D7
type: Answer
has comment: http://stackoverflow.com/comment/91719946
has comment: http://stackoverflow.com/comment/91739850
has comment: http://stackoverflow.com/comment/91721209
score: 1
answers question: http://stackoverflow.com/q/52386915
upvote count: 1

http://stackoverflow.com/comment/91691111
type: Comment
type: QuestionComment
has text: Is the self-signed certificate generated on the same computer you are trying to connect to it? It sure looks like a certificate authority issue, and self-signed almost certainly confirms it.
score: 0
comment on: http://stackoverflow.com/q/52370470

http://stackoverflow.com/comment/91712871
score: 0
type: Comment
has text: Problem is: how is flask supposed to split the two? What is the *separator* in between.
type: QuestionComment
comment on: http://stackoverflow.com/q/52384451

http://stackoverflow.com/comment/91770283
has text: The ``print`` example outputs the entire list, the ``log`` example outputs each element. Which do you need?
type: Comment
comment on: http://stackoverflow.com/q/52413215
score: 0
type: QuestionComment

http://stackoverflow.com/q/52318734
downvote count: 0
has title: Create Names column in Pandas DataFrame
tagged with: pandas
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52318812
possible better answer: http://stackoverflow.com/a/52319271
favorite count: 0
has answer: http://stackoverflow.com/a/52318842
has answer: http://stackoverflow.com/a/52319271
type: Question
tagged with: python
answer count: 3
accepted answer: http://stackoverflow.com/a/52318812
has body: I am using the Python Package names to generate some first names for QA testing. The names package contains the function names.get_first_name(gender) which allows either the string male or female as the parameter. Currently I have the following DataFrame: Marital Gender 0 Single Female 1 Married Male 2 Married Male 3 Single Male 4 Married Female I have tried the following: df.loc[df.Gender == 'Male', 'FirstName'] = names.get_first_name(gender = 'male') df.loc[df.Gender == 'Female', 'FirstName'] = names.get_first_name(gender = 'female') But all I get in return is the are just two names: Marital Gender FirstName 0 Single Female Kathleen 1 Married Male David 2 Married Male David 3 Single Male David 4 Married Female Kathleen Is there a way to call this function separately for each row so not all males/females have the same exact name?
upvote count: 1

http://stackoverflow.com/q/52327163
has title: Range() including its bounds for positive and negative steps
has answer: http://stackoverflow.com/a/52330594
has answer: http://stackoverflow.com/a/52327467
has answer: http://stackoverflow.com/a/52327228
upvote count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91608189
has body: I want to do a simple program that prints all the numbers in a range A to B, including B. For ranges having bounds in increasing order, I know that I have to add 1 to the upper bound, like: range(A, B+1) But adding 1 to B won't work when the bounds are in decreasing order, like range(17, 15, -1). How can I code it to work for both increasing and decreasing ranges?
answer count: 5
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91601281
type: Question
has comment: http://stackoverflow.com/comment/91607204
has comment: http://stackoverflow.com/comment/91601654
has answer: http://stackoverflow.com/a/52327337
has answer: http://stackoverflow.com/a/52327380

http://stackoverflow.com/a/52354200
has body: If the numbers are separated by a single space your can use the following code: n = int(input()) matrix = [] for i in range(n): row = [int(x) for x in input().split()] matrix.append(row) If you have different separator then space you can put as argument in the split() function.
type: Answer
has comment: http://stackoverflow.com/comment/91653483
answers question: http://stackoverflow.com/q/52353860
accepted answer of: http://stackoverflow.com/q/52353860
type: AcceptedAnswer
score: 0

http://stackoverflow.com/a/52343141
has body: You unravel your list and put it into a dictionary using dict.setdefault() : data = [(4157, 1, 1), (4157, 1, 10), (4157, 2, 1), (4157, 2, 10), (4157, 3, 1), (4157, 3, 10), (4157, 4, 1), (4157, 4, 10), (4182, 1, 1)] d = {} for k,v,p in data: key = d.setdefault(k,{}) key[v]=p print(d) Output: {4157: {1: 10, 2: 10, 3: 10, 4: 10}, 4182: {1: 1}} You can acess it by: print( d[4157][3] ) # 10 The result is shorter then your source-data because you replace the first value by the second one: (4157, 1, 1) =&gt; (4157, 1, 10) # 10 replaces 1 (4157, 2, 1) =&gt; (4157, 2, 10) # etc. (4157, 3, 1) =&gt; (4157, 3, 10) (4157, 4, 1) =&gt; (4157, 4, 10) You could instead aggregate them like so: for k,v,p in data: key = d.setdefault(k,{}) key2 = key.setdefault(v,[]) key2.append(p) print(d) To get an output of: {4157: {1: [1, 10], 2: [1, 10], 3: [1, 10], 4: [1, 10]}, 4182: {1: [1]}} and access it by print( d[4157][3] ) # [1, 10]
has comment: http://stackoverflow.com/comment/91632640
answers question: http://stackoverflow.com/q/52343065
has comment: http://stackoverflow.com/comment/91632655
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91649094
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52343065

http://stackoverflow.com/a/52283325
has comment: http://stackoverflow.com/comment/91536856
type: Answer
has comment: http://stackoverflow.com/comment/91514963
has comment: http://stackoverflow.com/comment/91537410
has body: The open window is not shown by a simple fact, the local variables are deleted when its scope is finished, in your case window = Disclaimer() is a local variable that will be deleted so a possible solution is: def acknowledge_warning(self): self.window = Disclaimer() self.window.show() self.close() Although a better option is to create a class or function where the logic of the interaction between windows is implemented, in the following part I show an example: class WarningScreen(QtWidgets.QDialog, Ui_SomeWarningScreen): closed = QtCore.pyqtSignal() def __init__(self, parent=None): super(WarningScreen, self).__init__(parent) self.setupUi(self) self.accept_button_2.clicked.connect(self.close) self.accept_button_2.clicked.connect(self.closed) class DisclaimerScreen(QtWidgets.QDialog, Ui_UsageDislaimer): def __init__(self, parent=None): super(DisclaimerScreen, self).__init__(parent) self.setupUi(self) class Controller: def __init__(self): self.warning = WarningScreen() self.disclaimer = DisclaimerScreen() self.warning.closed.connect(self.disclaimer.show) self.warning.show() if __name__ == "__main__": import sys APP = QtWidgets.QApplication(sys.argv) w = Controller() sys.exit(APP.exec_())
has comment: http://stackoverflow.com/comment/91515260
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/91536865
has comment: http://stackoverflow.com/comment/91515471
has comment: http://stackoverflow.com/comment/91515375
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91515072
has comment: http://stackoverflow.com/comment/91537549
accepted answer of: http://stackoverflow.com/q/52282780
has comment: http://stackoverflow.com/comment/91515176
answers question: http://stackoverflow.com/q/52282780
has comment: http://stackoverflow.com/comment/91536400

http://stackoverflow.com/q/52375466
tagged with: tzdata
has comment: http://stackoverflow.com/comment/91736593
score: 0
tagged with: tcl
has comment: http://stackoverflow.com/comment/91716257
has comment: http://stackoverflow.com/comment/91695901
type: UnansweredQuestion
has title: Python app taking a long time to open using cx_freeze
tagged with: python
has comment: http://stackoverflow.com/comment/91736385
has body: I am building an app with tkinter, cx_freeze and I have Anaconda installed. The app is taking a really long time to open (30 seconds). I think it has something to do with the tzdata that is in the ananconda tcl folders as I can see it opening these up when I ran a process monitor on it. If I delete these from my anaconda folders, will this break anything? Is there a way around this? from cx_Freeze import setup, Executable import os.path base = None PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__)) os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6') os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6') executables = [Executable("RunExcelMacro.py", base=base)] packages = ["idna","tkinter","os","win32com.client"] options = { 'build_exe': { 'packages':packages,'include_files':[ os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'), os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll'), ], }, } #os.environ['TCL_LIBRARY'] = r'C:\ProgramData\Anaconda3\tcl\tcl8.6' #os.environ['TK_LIBRARY'] = r'C:\ProgramData\Anaconda3\tcl\tk8.6' setup( name = "Background Excel Executor", options = options, version = "1.0", description = 'Runs an excel macro in the background', executables = executables )
has comment: http://stackoverflow.com/comment/91695940
tagged with: tkinter
answer count: 0
type: Question
tagged with: anaconda
has comment: http://stackoverflow.com/comment/91736355

http://stackoverflow.com/comment/91700192
type: AnswerComment
comment on: http://stackoverflow.com/a/52366909
has text: How to add a count function to it and print it at the last? means count of how many lines of that.
type: Comment
score: 0

http://stackoverflow.com/comment/91570882
type: Comment
has text: Hi Pedro....thank you for the answer. I have tried to iterate each string using this method:
type: AnswerComment
comment on: http://stackoverflow.com/a/52299186
score: 0

http://stackoverflow.com/q/52403954
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/91751741
upvote count: 2
has comment: http://stackoverflow.com/comment/91752580
has comment: http://stackoverflow.com/comment/91751766
type: Question
has answer: http://stackoverflow.com/a/52404191
has comment: http://stackoverflow.com/comment/91751629
has comment: http://stackoverflow.com/comment/91751652
has comment: http://stackoverflow.com/comment/91751695
has comment: http://stackoverflow.com/comment/91751592
has comment: http://stackoverflow.com/comment/91752081
has comment: http://stackoverflow.com/comment/91751812
has body: I'm writing a placeholder Point and Rectangle function, but I want to use Zelle's graphics module's ones if they're present class Pt: def __init__(self, x, y): self.x = x self.y = y if ('graphics' in sys.modules): return graphics.Point(x, y) class R: def __init__(self, tLPoint, w, h): self.P1 = tLPoint self.P2 = Pt(tLPoint.x + w, tLPoint.y + h) self.x = tLPoint.x self.y = tLPoint.y if ('graphics' in sys.modules): return graphics.Rectangle(P1, P2) That's the code I've got so far, but __init__ gets annoyed when you return something through it. What I want to do is to return the Zelle's graphics version if it exists, instead of the custom one. I'm not entirely sure what to do with this, any help is appreciated.
possible better answer: http://stackoverflow.com/a/52404214
answer count: 2
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91751903
has answer: http://stackoverflow.com/a/52404214
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91751947
has title: How do I override a written function when a certain module is imported?
tagged with: python
has comment: http://stackoverflow.com/comment/91751788
has comment: http://stackoverflow.com/comment/91751830
accepted answer: http://stackoverflow.com/a/52404191

http://stackoverflow.com/a/60010751
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I was trying to solve the same thing! Your post helped me on the trail. pylint has several categories of checks: C convention related checks R refactoring related checks W various warnings E errors, for probable bugs in the code F fatal, if an error occurred which prevented pylint from doing further processing. So, if you want to block everything except E and F, in ~/.pylintrc do: [MESSAGES CONTROL] disable=C,R,W
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52300046
answers question: http://stackoverflow.com/q/52300046

http://stackoverflow.com/a/52317619
answers question: http://stackoverflow.com/q/52317109
score: 0
type: Answer
has body: Java bytes are signed (-128 to 127), but that doesn't meant you can't store values from 0 to 255 instead, its just the way to output them that changes. public static void main(String[] args) { byte test = (byte)255; System.out.println(test); System.out.println(test &amp; 0xFF); } Output: -1 255

http://stackoverflow.com/q/52381343
has comment: http://stackoverflow.com/comment/91707519
tagged with: database
has comment: http://stackoverflow.com/comment/91707018
has answer: http://stackoverflow.com/a/52381431
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/91707289
favorite count: 0
accepted answer: http://stackoverflow.com/a/52381431
tagged with: python-2.7
has body: I have a database as follows: indexID matchID order userClean Probability 0 0 1 0 clean 35 1 0 2 1 clean 75 2 0 2 2 clean 25 5 3 4 5 clean 40 6 3 5 6 clean 85 9 4 5 9 clean 74 12 6 7 12 clean 23 13 6 8 13 clean 72 14 7 8 14 clean 85 15 9 10 15 clean 76 16 10 11 16 clean 91 19 13 14 19 clean 27 23 13 17 23 clean 10 28 13 18 28 clean 71 32 20 21 32 clean 97 33 20 22 33 clean 30 What I want to do is, for each repeated indexID, I would like to choose the entry that is of higher probability and mark that as clean and the other as dirty. The output should look something like this: indexID matchID order userClean Probability 0 0 1 0 dirty 35 1 0 2 1 clean 75 2 0 2 2 dirty 25 5 3 4 5 dirty 40 6 3 5 6 clean 85 9 4 5 9 clean 74 12 6 7 12 dirty 23 13 6 8 13 clean 72 14 7 8 14 clean 85 15 9 10 15 clean 76 16 10 11 16 clean 91 19 13 14 19 dirty 27 23 13 17 23 dirty 10 28 13 18 28 clean 71 32 20 21 32 clean 97 33 20 22 33 dirty 30
type: Question
has title: Choosing the larger probability from a specific indexID
has comment: http://stackoverflow.com/comment/91707052
score: 1
upvote count: 1
tagged with: python
answer count: 1

http://stackoverflow.com/q/52277707
has answer: http://stackoverflow.com/a/52277734
type: AnsweredQuestion
score: 3
tagged with: list
has answer: http://stackoverflow.com/a/52277939
downvote count: 0
accepted answer: http://stackoverflow.com/a/52277734
favorite count: 0
has body: I have a dataframe that looks as follow A B 0 1 4 1 2 5 2 3 6 and a list names = ['x','y'] I want to get a dataframe that kind of performs and outer join with that list. The desired result is: A B name 0 1 4 x 1 1 4 y 2 2 5 x 3 2 5 y 4 3 6 x 5 3 6 y
answer count: 3
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/52277880
upvote count: 3
has title: Merge a pandas dataframe with a list through an outer join
possible better answer: http://stackoverflow.com/a/52277880
type: Question

http://stackoverflow.com/a/62960893
type: Answer
has body: Installing Python version 3.6 and then installing opencv with the command: pip install opencv-python==3.3.0.9 resolved this issue for me
score: 0
answers question: http://stackoverflow.com/q/52349669

http://stackoverflow.com/q/52306461
linked to: http://stackoverflow.com/q/51555668
downvote count: 0
tagged with: tensorflow
type: Question
score: 3
has title: How to sample batch from a specific class?
upvote count: 3
has answer: http://stackoverflow.com/a/52487528
accepted answer: http://stackoverflow.com/a/52487528
answer count: 1
favorite count: 0
has body: I'd like to train a classifier on one ImageNet dataset (1000 classes each with around 1300 images). For some reason, I need each batch to contain 64 images from a specific class (provided as int or placeholder). How to do it efficiently with the latest TensorFlow? This is a follow-up question to How to sample batch from only one class at each iteration. My current thought is to use tf.data.Dataset.filter: specific_class = 2 # as an example dataset = tf.data.TFRecordDataset(filenames) # __parser_fun__ produces datum tuple (x, y) dataset = dataset.map(__parser_fun__, num_parallel_calls=num_threads) dataset = dataset.shuffle(20000) # print(dataset) gives &lt;ShuffleDataset shapes: ((3, 128, 128), (1,)), # types: (tf.float32, tf.int64)&gt; dataset = dataset.filter(lambda x, y: tf.equal(y[0], specific_class)) dataset = dataset.batch(64) dataset = dataset.repeat() iterator = dataset.make_one_shot_iterator() x_batch, y_batch = iterator.get_next() A minor problem with filter is that I need to construct an iterator every time I want to sample from a new class. Another idea is to use tf.contrib.data.rejection_resample but it seems prohibitive computationally (or is it?). I wonder if there is other efficient way to sample batches from a particular class?
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/52303961
type: Question
tagged with: phantomjs
has title: 'phantomjs' executable may have wrong permissions
has body: This script works fine on Google Cloud Service. But i get error on Amazon Web Service EC2: (operation system: linux 64bit) selenium.common.exceptions.WebDriverException: Message: 'phantomjs' executable may have wrong permissions. Full Code: /usr/local/lib/python3.7/site-packages/selenium/webdriver/phantomjs/webdriver.py:49: UserWarning: Selenium support for PhantomJS has been deprecated, please use headless versions of Chrome or Firefox instead warnings.warn('Selenium support for PhantomJS has been deprecated, please use headless ' Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/common/service.py", line 76, in start stdin=PIPE) File "/usr/lib64/python3.7/subprocess.py", line 756, in __init__ restore_signals, start_new_session) File "/usr/lib64/python3.7/subprocess.py", line 1499, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) PermissionError: [Errno 13] Permission denied: '/usr/local/share/phantomjs-2.1.1-linux-x86_64/bin/phantomjs' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "turkish.py", line 114, in &lt;module&gt; bot = TransBot() File "turkish.py", line 13, in __init__ self.driver = webdriver.PhantomJS(executable_path='/usr/local/share/phantomjs-2.1.1-linux-x86_64/bin/phantomjs') File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/phantomjs/webdriver.py", line 56, in __init__ self.service.start() File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/common/service.py", line 88, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'phantomjs' executable may have wrong permissions. I try move '/usr/local/bin' and '/usr/local/share' phantomjs file. Same error. What do you suggest? Sorry my english.
answer count: 2
has answer: http://stackoverflow.com/a/52304270
downvote count: 0
tagged with: amazon-ec2
favorite count: 0
accepted answer: http://stackoverflow.com/a/52304270
possible better answer: http://stackoverflow.com/a/60201173
has answer: http://stackoverflow.com/a/60201173
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: selenium

http://stackoverflow.com/q/52386370
upvote count: 1
has comment: http://stackoverflow.com/comment/91717173
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52386602
has comment: http://stackoverflow.com/comment/91718000
has answer: http://stackoverflow.com/a/52386709
has title: Python Class DRY
has comment: http://stackoverflow.com/comment/91717678
tagged with: class
score: 0
answer count: 3
favorite count: 0
has comment: http://stackoverflow.com/comment/91717106
has body: I wrote the following python class. Now I repeat if settings.MIXPANEL_ID:in every function and I wonder if there is a better way to write this Class? class MixpanelClass: def __init__(self): if settings.MIXPANEL_ID: mp = Mixpanel(settings.MIXPANEL_ID) def mp_track_event(user_id, event, property=None): if settings.MIXPANEL_ID: mp.track(user_id, event, property) def mp_people_set(user_id, property): if settings.MIXPANEL_ID: mp.people_set(user_id, property) def mp_people_increment(user_id, property): if settings.MIXPANEL_ID: mp.people_increment(user_id, property) def mp_people_track_charge(user_id, revenue, property): if settings.MIXPANEL_ID: mp.people_track_charge(user_id, revenue, property) def mp_get_distinct_id(request): if settings.MIXPANEL_ID: mp_cookie_name = 'mp_' + settings.MIXPANEL_ID + '_mixpanel' mp_cookie = request.COOKIES.get(mp_cookie_name, None) if mp_cookie: unquoted = unquote(mp_cookie) dictionary = literal_eval(unquoted) return dictionary.get('distinct_id')
possible better answer: http://stackoverflow.com/a/52386709
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52386602
has comment: http://stackoverflow.com/comment/91717775
has comment: http://stackoverflow.com/comment/91717315
has answer: http://stackoverflow.com/a/52386853

http://stackoverflow.com/comment/91776911
type: Comment
comment on: http://stackoverflow.com/q/52416781
has text: https://en.wikipedia.org/wiki/Karnaugh_map
score: 4
type: QuestionComment

http://stackoverflow.com/a/52382663
type: Answer
has comment: http://stackoverflow.com/comment/91735496
score: 10
upvote count: 10
has comment: http://stackoverflow.com/comment/91736264
has comment: http://stackoverflow.com/comment/104580092
has comment: http://stackoverflow.com/comment/91743998
answers question: http://stackoverflow.com/q/52300242
downvote count: 0
has body: I'm not accustomed with Mac install paths, from what the basictex faq says, I gather the executeables should live in /usr/local/texlive/bin/x86_64-darwin Running which xelatex in a terminal might also help finding where the command is, but that only works if the directory is already in your PATH variable. Another method would be running find / -name 'xelatex' if it is not within your PATH so you might find it that way (might take a while as this will search you whole harddrive). Once you've found it and added the path to your PATH variable, you should also check if the jupyter has the correct PATH by running import os print(os.environ['PATH']) within a notebook.

http://stackoverflow.com/a/52459275
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52424812
has body: After a positive match using template matching, get the patch from the large image and use more image comparison methods to validate your match. You have to compare two images of the same size. E.g. histogram matching as suggested above, template matching with other norms, comparison of statistics (mean, variance, higher moments), etc. Another option is to check the score of the "second best match". The score should be smaller than the "best match". This makes sure that there is no other similar patch in your larger image. This should eliminate your "1x1 white pixel" false match. If your template is rotated, you may need more sophisticated methods to find and extract an initial patch location. Please keep in mind that it is not possible to avoid false positives in all cases. There should be a counter example always. Especially if your template is small. For reasonable template sizes, take a look at the recommended patch sizes for feature based matching Methods (SIFT, SURF, ..) or optical flow matching. First guess - your template should be bigger than 21x21 Pixel

http://stackoverflow.com/comment/91626958
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52338831
has text: After you have edited the question, I will post a solution for the `idx`.

http://stackoverflow.com/q/52398066
type: Question
has comment: http://stackoverflow.com/comment/91741882
has comment: http://stackoverflow.com/comment/91741536
tagged with: django-models
has comment: http://stackoverflow.com/comment/91741003
has title: Type object 'User' has no attribute 'objects' (AbstractUser) python
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91742898
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/91741858
has comment: http://stackoverflow.com/comment/91742266
favorite count: 0
has comment: http://stackoverflow.com/comment/91741997
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91742578
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91741749
score: 3
has answer: http://stackoverflow.com/a/52399774
upvote count: 3
has comment: http://stackoverflow.com/comment/91743762
has body: app name backend User object is returning error : users = User.objects.filter(fb_userid=fb_user_id) AttributeError: type object 'User' has no attribute 'objects' models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): fb_userid = models.CharField(max_length=256) avatar = models.ImageField(upload_to='avatars/', blank=True, null=True) views.py from backend.models import * def fb_login(request): # permission_classes = (permissions.AllowAny,) if request.method == 'POST': if 'fb_user_id' not in request.data: return Response({'error':'missing fb_user_id'}, status=status.HTTP_404_NOT_FOUND) fb_user_id = str(request.data['fb_user_id']) users = User.objects.filter(fb_userid=fb_user_id) if users.count() == 0: user, created = User.objects.get_or_create(username=fb_user_id, email='fb@fb.net') if created: user.save() else: user = users[0] token = Token.objects.get_or_create(user=user)[0] # Likes likeIds = [] likes = ImageLike.objects.filter(user_id=user.id) for like in likes: likeIds.append(like.image.id) # Saved Places savedIds = [] saved = SavedRestaurants.objects.filter(user_id=user.id) for save in saved: savedIds.append(save.restaurant.id) jsonData = { 'token': token.key, 'saved': savedIds, 'likes': likeIds } return Response(jsonData) settings.py AUTH_USER_MODEL = 'backend.User' User object is returning error : users = User.objects.filter(fb_userid=fb_user_id) AttributeError: type object 'User' has no attribute 'objects'

http://stackoverflow.com/q/52316354
has title: problem installing and importing modules in python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52316877
has comment: http://stackoverflow.com/comment/91584554
has comment: http://stackoverflow.com/comment/91580729
type: Question
tagged with: opencv
has body: I am installing python on windows10 and trying to install the opencv and numpy extentions in the command window. I get no error installing them and it says it is successfully installed. But when I try to check the installation and import cv2 it does not recognize it and give me the error: no module named cv2. can anybody help me with this problem? Is there something wrong in installation process or do I need to install something else? I checked the newest version of each and used the compatible one with my system. Thanks.
has answer: http://stackoverflow.com/a/52318035
has comment: http://stackoverflow.com/comment/91580128
tagged with: numpy
score: 0
has answer: http://stackoverflow.com/a/52316565
has answer: http://stackoverflow.com/a/52316877
has answer: http://stackoverflow.com/a/52318766
possible better answer: http://stackoverflow.com/a/52316565
has comment: http://stackoverflow.com/comment/91580401
linked to: http://stackoverflow.com/q/26069254
linked to: http://stackoverflow.com/q/44102738
tagged with: python
has comment: http://stackoverflow.com/comment/91603753
answer count: 4

http://stackoverflow.com/q/52348594
has comment: http://stackoverflow.com/comment/91691525
tagged with: jupyter-notebook
answer count: 0
downvote count: 0
has body: I'm using virtualenvwrapper-win to manage environments, I created one, pip-installed a bunch of packages but when I try to import them from jupyter notebook or lab it only looks in the main directory and not in the environments. I tried using the conda environments and had the same problem, so I suspect the problem is in the jupyter configuration, which I haven't meddled with much but might have messed up at some point. sys.executable returns 'c:\\anaconda3\\python.exe', but I suspect it should be using the one in the virtual environment right?
type: UnansweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/91643400
has title: Jupyter notebook not using packages in virtual environment
tagged with: ipython
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/37085665
favorite count: 0
has comment: http://stackoverflow.com/comment/91644033
has comment: http://stackoverflow.com/comment/91643809
tagged with: python

http://stackoverflow.com/a/52416754
has comment: http://stackoverflow.com/comment/114235997
accepted answer of: http://stackoverflow.com/q/52416574
score: 9
answers question: http://stackoverflow.com/q/52416574
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/115884169
type: Answer
has body: IIUC ffill with groupby cumcount df.my_counter.ffill()+df.groupby(df.my_counter.notnull().cumsum()).cumcount()/10 Out[92]: 0 1.0 1 2.0 2 2.1 3 3.0 4 3.1 5 3.2 6 8.0 dtype: float64
upvote count: 9

http://stackoverflow.com/q/52298821
type: AnsweredQuestion
has title: How to draw relplot with boxplot then only frequencies specified in seaborn
has body: Let we have such data: import pandas as pd import seaborn as sns data = np.array([[5.2, 500, 1], [7.2, 450, 1],[6.2, 350, 1],[4.6, 400,1 ],[5.9, 212,1], [6.2, 350, 2],[4.6, 400,2 ],[5.9, 212,2]]) df = pd.DataFrame({'val':data[:,0],'size':data[:,1], 'time':data[:,2]}) val - actual mean value, which were calculated from dataset with size specified in size column Drawing boxplot: ax = sns.boxplot (x = 'time', y="val", data=df) ax = sns.swarmplot(x = 'time', y="val", data=df, color=".25", size = df.size ) it will draw obviously without taking into account real mean - which should sum of val divided by sum of size for each time (why all dots are with the same size) Drawing relplot help to draws sizes of dots with proper size, but how to draw there true boxplot: ax = sns.relplot(x = 'time', y="val", size="size",dashes = True, sizes=(40, 400), alpha=.5, palette="muted", height=6, data=df)
upvote count: 1
tagged with: plot
type: Question
accepted answer: http://stackoverflow.com/a/52311187
tagged with: matplotlib
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
tagged with: seaborn
has answer: http://stackoverflow.com/a/52311187
tagged with: python

http://stackoverflow.com/q/52353686
upvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/91652179
possible better answer: http://stackoverflow.com/a/52353730
linked to: http://stackoverflow.com/q/2823316
linked to: http://stackoverflow.com/q/2257441
has comment: http://stackoverflow.com/comment/91652186
has answer: http://stackoverflow.com/a/52353747
has body: I am looking to generate a random word list from a set of characters in python. Problem here:- It is Generating like:- aaaaaa aaaaab aaaaac ...... So on I want to add random function so it generate same length with randomization of alphabets it has like:- a15bef f45acd 9bbac0 ...... So on Look With same length but random. How to add random function to it? #Code import itertools chrs = 'abcdef0123456789' # Change your required characters here n = 6 # Change your word length here for xs in itertools.product(chrs, repeat=n): print(''.join(xs)) please help me to solve it.
has answer: http://stackoverflow.com/a/52353819
has title: How to generate random word from a set of characters in python
accepted answer: http://stackoverflow.com/a/52353819
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91652165
has answer: http://stackoverflow.com/a/55584987
has answer: http://stackoverflow.com/a/52353730
tagged with: python
answer count: 4
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/52408463
answer count: 1
has comment: http://stackoverflow.com/comment/91772805
has comment: http://stackoverflow.com/comment/91760730
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has title: Searching for only the first value in an array in a csv file
has comment: http://stackoverflow.com/comment/91761288
tagged with: python
has comment: http://stackoverflow.com/comment/91761153
has comment: http://stackoverflow.com/comment/91761361
has comment: http://stackoverflow.com/comment/91760673
has comment: http://stackoverflow.com/comment/91762108
has comment: http://stackoverflow.com/comment/91773215
downvote count: 1
has comment: http://stackoverflow.com/comment/91761221
type: Question
has comment: http://stackoverflow.com/comment/91762412
has comment: http://stackoverflow.com/comment/91761513
has comment: http://stackoverflow.com/comment/91760852
score: -1
has comment: http://stackoverflow.com/comment/91768957
has body: So i am creating a account login system which searches a database for a username (and its relevant password) and, if found, will log the user on. This is what the csv file currently looks like ['dom', 'enter password'] This is written in one field (on an excel spreadsheet), and was written to the file when the user registered. However when I try to log on, the program will only log on if that is what is entered in the field, when I would like it to log on when dom is entered. Here is the code which reads the csv file to see if the username/password is found on the file: def Get_Details(): user_namev2=user_name.get().lower() #Make it so entry box goes red if passwords password is incorrect, and red if username is incorrect/not fault user_passwordv2=user_password.get().lower() with open ('Accounts.csv', 'r') as Account_file: reader = csv.reader(Account_file) for row in reader: for field in row: if field == user_namev2: print ("In file") Here is how the username and password get written to the csv file upon registering an account. if re.match(user_password2v2, user_passwordv2): print("Passwords do match") user_info = [] user_info.append(user_namev2) user_info.append(user_passwordv2) with open ('Accounts.csv', 'a') as Account_file: writer = csv.writer(Account_file) writer.writerow([user_info]) Bottom() Any ideas on how i can search the csv file so that only a certain part of the string is searched and matched with user_namev2
has answer: http://stackoverflow.com/a/52415397
upvote count: 0

http://stackoverflow.com/comment/91674167
score: 0
has text: @VivekKumar very helpful, I have learnt something useful and I am sure anyone else stumbling on this question/answer will find it of use.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52346725

http://stackoverflow.com/comment/91738927
type: Comment
type: AnswerComment
has text: Possibly best of all is to just print that whole thing and then copy paste/output it into the file. That way if the list truly is massive it doesn't have to be done at runtime.
score: 0
comment on: http://stackoverflow.com/a/52397090

http://stackoverflow.com/q/52415446
has answer: http://stackoverflow.com/a/52415556
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52415556
tagged with: python
has answer: http://stackoverflow.com/a/52415559
type: AnsweredQuestion
has body: I'm trying to do the following expression with dict comprehension and a ternary operation in python: for num in ar: if num in seen_dict: seen_dict[num] += 1 else: seen_dict[num] = 1 I tried this: seen_dict = { num: seen_dict[num] += 1 for num in ar if num in seen_dict else seen_dict[num] = 1} and several permutations thereof, but I keep getting syntax errors. Is it possible to do what I want? UPDATE This is the correct syntax, but not my dict only comes back with 1's: seen_dict = { num: (seen_dict[num] + 1) if num in seen_dict else 1 for num in ar } Can someone explain why this doesn't function the same way as the for loop? Thank you.
accepted answer: http://stackoverflow.com/a/52415653
has comment: http://stackoverflow.com/comment/91774488
type: Question
tagged with: ternary
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52415653
has title: Incrementing dict values with dict comprehension
tagged with: dictionary-comprehension

http://stackoverflow.com/q/52285212
has comment: http://stackoverflow.com/comment/91518702
type: Question
has comment: http://stackoverflow.com/comment/91518767
score: 0
answer count: 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91518783
tagged with: python
tagged with: dictionary
has body: I'm having trouble figuring this out as Python's getsizeof() doesn't return the memory consumption of objects the dictionary refers to. If I had a few functions that could be called depending on a given input: def foo(x): mapping = {'a':func1, 'b':func1, 'c':func2, 'd':func2, 'e':func2, 'f':func3, ...etc.} return mapping[x]() and some of the inputs resulted in the same function being called, is storing multiple copies (or is it references?) of the function going to result in a larger memory footprint? I'm trying to determine if it would be more memory efficient to create an intermediary dictionary that stores only one copy of the function: functions = {0:func1, 1:func2, 2:func3, ...etc.} and replace all the function values in "mapping" with the corresponding integer to save space. I am somewhat aware of how mutable and immutable objects work in Python and my initial conclusion is that all values that refer to the same function do not result in more copies of the function taking up memory. Is this correct? In a somewhat related question, if I were to print out an objects id, using id(), do all objects that have the same id refer to the same location in memory (and therefore not take up more memory in a dictionary)?
tagged with: memory-management
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52285264
accepted answer: http://stackoverflow.com/a/52285264
has title: Python mutable vs immutable dictionary memory usage

http://stackoverflow.com/a/53364291
score: 1
accepted answer of: http://stackoverflow.com/q/52428684
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I've implemented a list box that applies the second visualization concept (bars at the top and bottom) by default. It is called additional_urwid_widgets.IndicativeListBox and can be installed via pip. For a stand alone example, which illustrates the functionality of the widget, see here. For more (and simpler) examples, see here. For a more detailed explanation of the parameters and options, see the corresponding github wiki entry. Some Examples Minimal #! /usr/bin/env python3 # -*- coding: utf-8 -*- from additional_urwid_widgets import IndicativeListBox # installed via pip import urwid # installed via pip # Color schemes that specify the appearance off focus and on focus. PALETTE = [("reveal_focus", "black", "light cyan", "standout")] # The list box is filled with buttons. body = [urwid.Button(letter) for letter in "abcdefghijklmnopqrstuvwxyz"] # Wrap the list items into an 'urwid.AttrMap', so that they have an other appearance when focused. # Instead of an simple list-like object you can/should create a 'urwid.ListWalker'. attr_body = [urwid.AttrMap(entry, None, "reveal_focus") for entry in body] ilb = IndicativeListBox(attr_body) loop = urwid.MainLoop(ilb, PALETTE) loop.run() Display items above/below #! /usr/bin/env python3 # -*- coding: utf-8 -*- from additional_urwid_widgets import IndicativeListBox # installed via pip import urwid # installed via pip # Color schemes that specify the appearance off focus and on focus. PALETTE = [("reveal_focus", "black", "light cyan", "standout")] # The list box is filled with buttons. body = [urwid.Button(letter) for letter in "abcdefghijklmnopqrstuvwxyz"] # Wrap the list items into an 'urwid.AttrMap', so that they have an other appearance when focused. # Instead of an simple list-like object you can/should create a 'urwid.ListWalker'. attr_body = [urwid.AttrMap(entry, None, "reveal_focus") for entry in body] ilb = IndicativeListBox(attr_body, topBar_endCovered_prop=("{} above ...", None, None), bottomBar_endCovered_prop=("{}…
upvote count: 1
answers question: http://stackoverflow.com/q/52428684

http://stackoverflow.com/q/52336388
tagged with: horizontal-line
score: 1
downvote count: 1
has title: How to remove horizontal and vertical lines on image using opencv and python
type: Question
has comment: http://stackoverflow.com/comment/91665406
has comment: http://stackoverflow.com/comment/91629206
has comment: http://stackoverflow.com/comment/91673695
favorite count: 0
has comment: http://stackoverflow.com/comment/91619915
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: opencv
linked to: http://stackoverflow.com/q/42461211
has body: I am new to python. I have to remove horizontal and vertical lines on my graph image using opencv and python. Here is my image. This is a graph containing a curve, I want to compare different curves but not the grid: Thanks

http://stackoverflow.com/a/52357727
answers question: http://stackoverflow.com/q/52357676
upvote count: 1
has comment: http://stackoverflow.com/comment/91660269
has body: First, you should convert your TIME column to DateTime. Then group by time and date to find out how many people worked on each date at each hour. Finally, group by the hour again and get the mean: df.groupby([pd.to_datetime(df.TIME).dt.hour, df.DATE]).size()\ # raw counts .groupby('TIME').mean() # mean counts #TIME #10 1 #11 1 #16 1 #22 1 A more compact (and possibly less efficient) option, thanks to @Wen (who is always helpful): df.groupby([pd.to_datetime(df.TIME).dt.hour, df.DATE]).size()\ .mean(level='TIME')
downvote count: 0
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/91660355

http://stackoverflow.com/comment/91852718
has text: This error only starts to emerge when using much more points than given by me above.
comment on: http://stackoverflow.com/a/52384739
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/91721478
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52388194
has text: Also, will each `DataFrame` have the same number of rows, with the same `set` of `'ID'`s

http://stackoverflow.com/comment/91620065
score: 2
has text: Please provide a minimal example of your problem, what result you expect and what result your have
type: Comment
comment on: http://stackoverflow.com/q/52336411
type: QuestionComment

http://stackoverflow.com/comment/91583283
has text: YES. Use drop_tables() before create_tables().
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52311278
score: 1

http://stackoverflow.com/comment/91739219
comment on: http://stackoverflow.com/q/52397002
score: 0
type: Comment
has text: Going back to caret, the goal of caret is to give you good implementations of good models, so the really obscure ones you can find for R are less likely in caret. Therefore, the models in caret are exactly the sort that are also probably available in Python.
type: QuestionComment

http://stackoverflow.com/comment/91763132
comment on: http://stackoverflow.com/q/52408993
has text: @NotEinstein i tried to clarify in my answer
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52335450
tagged with: spatial
has title: Error in generation queen spatial weigth matrix
tagged with: geopandas
tagged with: python
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: pysal
has body: I tried to generate a queen spatial weight matrix with pysal to calculate Moran's I. The shapefile used is here , called br_unidades_da_federacao. I executed the code w = ps.queen_from_shapefile('BRUFE250GC_SIR.shp') but received an error message that 3 observations were islands ( no neighbors): ids 0, 19 and 24. I plotted the shapefile and marked the observations with the id to show that it is not islands. id 0 and id 19 has 2 neighboors and id 24 has 3 neighboors. The image is below What is wrong in the code?
score: 1
type: Question
downvote count: 0

http://stackoverflow.com/q/52334593
has title: Quickly find joint pairs in a python list of numpy arrays
has comment: http://stackoverflow.com/comment/91616487
answer count: 1
has body: I have a list of numpy arrays and want to get the indices of the joint pairs. Basically, if I have the following list of lists: lst = [[1, 2, 3, 5], [1, 2, 9], [5, 6], [9]] I want the following: [[0, 1], [0, 2], [1, 3]] Here's what I have so far, but it's slow: out = out for i, item in enumerate(lst): for j in range(i+1, len(lst)): if not set(item).isdisjoint(lst[j]): out.append([i, j]) I appreciate your help.
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
tagged with: performance
has answer: http://stackoverflow.com/a/52335026
score: 1
tagged with: set
upvote count: 1
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/52335026
has comment: http://stackoverflow.com/comment/91617022

serverless-framework
tag name: serverless-framework
type: Tag
tags question: http://stackoverflow.com/q/52382555

http://stackoverflow.com/a/77759321
downvote count: 0
answers question: http://stackoverflow.com/q/52296735
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/137092377
has body: Since I couldn't find any library or easy way to draw an arc, I actually implemented it from scratch (in collaboration with my student Ederson Cássio) by drawing a PolyLine with many points, carefully computed, as suggested by @MCO . The algorithm is based on the geometry of an arc but, since it's a bit complicated instead of presenting it here, I think it's better to look at our implementation in the source code. It's been highly testes to you can simply reuse it if you need. The code is available as open source at https://gitlab.com/interscity/bike-science/-/blob/master/bikescience/arrow.py The python function draw_arrow() draws an arc arrow. It worked well for my intent. I could easily draw hundreds of arcs in a fraction of a second. It's used, for example, in this online interactive dashboard that shows the bicycle flows in the city of São Paulo: http://bikescienceweb.interscity.org/ (for the English version, click on the "en" on the footer.

http://stackoverflow.com/q/52334484
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52334608
has comment: http://stackoverflow.com/comment/91616269
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91616312
has answer: http://stackoverflow.com/a/52334637
score: 1
has title: Pandas How to ensure unique header/column values?
has answer: http://stackoverflow.com/a/52337166
type: Question
downvote count: 0
favorite count: 0
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/91616373
has body: I have a Pandas df that was not well-formatted and needed to force the header/column values to be one of the rows of my original df (which has duplicate values). The problem is that the header now has duplicates, for e.g: 2.0, 2.0, 10.0, 10.0, ..., 10.0, 16.0, 16.0, 16.0, 21.0, 21.0, 21.0, ... I want to ensure the header/columns values have unique values like so: 2.0, 2.1, 10.0, 10.1, 10.2, 10.3, ... , 10.8, 10.9, 16.0, 16.1, 16.2, .... and so on. The new values can exceed X.9 if needed, it shouldn't matter for my purposes if I get X.10, X.11, X.12, .... and so on. I tried using df.columns = df.columns.unique() but then I got an error saying that "ValueError: Length mismatch: Expected axis has 76 elements, new values have 37 elements". I have looked at other methods as well like df.duplicates() and df.drop_duplicates() but neither of those seems to be able to provide what it is that I am after. Thanks!

http://stackoverflow.com/comment/91518123
comment on: http://stackoverflow.com/q/52284547
type: QuestionComment
has text: @Bazingaa In the Middle is the whole plot, which i want to export. Picturesections of IDE and PDF are below. The two commands doesn't improve the export result.
type: Comment
score: 0

http://stackoverflow.com/q/52327099
has title: Relationship between two microservices with different database by means of api rest
has body: How can I make a relationship between two APIs, where an application is in node.js with the mongodb and another in python with mysql, I need to make a relation between them of 1: N between client:sales, in one I have the register client (name, cpf) and the other part is a sale, but for me to carry out the sales I need customer data. In a traditional application this relationship would be through a foreign key, as we are talking about two separate applications how could this relationship be made ??
tagged with: microservices
tagged with: python
tagged with: node.js
has answer: http://stackoverflow.com/a/52327376
type: UnansweredQuestion
type: Question
score: 0
tagged with: api
answer count: 1

http://stackoverflow.com/a/52370788
has comment: http://stackoverflow.com/comment/91694439
has body: In the Python OpenCV bindings, if you want to pass something to a OpenCV function that should be interpreted as a scalar, you should use a tuple with 4 elements. The size is important, that's what allows the wrapper code to recognise it as such. This corresponds to the C++ type cv::Scalar, which also holds 4 values. Only the values that are needed are used (corresponding to the channel depth of the other operand), the rest is ignored. Example: import cv2 import numpy as np img = np.ones((4,4,3), np.uint8) print cv2.add(img, (1,2,255,0)) Console output: [[[ 2 3 255] [ 2 3 255] [ 2 3 255] [ 2 3 255]] [[ 2 3 255] [ 2 3 255] [ 2 3 255] [ 2 3 255]] [[ 2 3 255] [ 2 3 255] [ 2 3 255] [ 2 3 255]] [[ 2 3 255] [ 2 3 255] [ 2 3 255] [ 2 3 255]]]
answers question: http://stackoverflow.com/q/52359728
type: Answer
accepted answer of: http://stackoverflow.com/q/52359728
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91693927
has comment: http://stackoverflow.com/comment/91694879
has comment: http://stackoverflow.com/comment/91694756
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/52361954
score: 1
has body: This happens because, you have multiple threads enabled in flask by default. Tensorflow models are not working well with multiple threads. You can read more about this in the below links https://github.com/keras-team/keras/issues/5640 https://github.com/tensorflow/tensorflow/issues/14356 The following workaround worked for me global graph graph = tf.get_default_graph() with graph.as_default(): model.compile() model.fit() with graph.as_default(): model.predict()
has comment: http://stackoverflow.com/comment/91712794
answers question: http://stackoverflow.com/q/52353540
upvote count: 1
has comment: http://stackoverflow.com/comment/91866614
type: Answer
has comment: http://stackoverflow.com/comment/91890686
downvote count: 0

http://stackoverflow.com/comment/91765000
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52398204
has text: @Karl, It sounds good concept but I have variable log files and the location and name of log files are determined by slave_list first column value. Not sure how to start with it. Is it good to loop through variable log files?
score: 0

http://stackoverflow.com/a/52296097
has body: datetime.datetime.now() is not a proper SQL syntax, and thus cannot be executed by read_sql(). I suggest either using the correct SQL syntax that computes current time, or creating variables for each datetime.datetime.now() and datetime.today() - timedelta(7) and replacing them in your string. edit: Do not follow the second suggestion. See comments below by Martijn Pieters.
score: 2
has comment: http://stackoverflow.com/comment/91540258
answers question: http://stackoverflow.com/q/52296014
downvote count: 0
has comment: http://stackoverflow.com/comment/91540293
has comment: http://stackoverflow.com/comment/91541092
upvote count: 2
type: Answer

http://stackoverflow.com/comment/91644481
comment on: http://stackoverflow.com/q/52349592
has text: You have 3 parentheses at the end of `print` which should only be 1.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/134959648
has text: I am in the same boat, and I have learned to ask SHOULD I be calculating R-squared for my SVR models, and the answer is no. The R-squared metric is misleading for nonlinear models and does not help you assess goodness-of-fit like you think it is. Here is a great explanation why R-squared is not for nonlinear models like SVR: https://statisticsbyjim.com/regression/r-squared-invalid-nonlinear-regression/ And here is an alternative metric, the pseudo R-squared: https://towardsdatascience.com/the-complete-guide-to-r-squared-adjusted-r-squared-and-pseudo-r-squared-4136650fc06c
score: 1
comment on: http://stackoverflow.com/q/52391030
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91685624
comment on: http://stackoverflow.com/q/52370489
has text: I could swear I saw the same question a week or two ago.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52278469
tagged with: azure
type: UnansweredQuestion
tagged with: azure-active-directory
tagged with: python
has body: I am attempting to use Azure Active Directory to allow users from my company's Microsoft domain login to my Flask webapp. I was getting an error that said: Message: AADSTS90130: Application ... is not supported over the /common or /consumers endpoints. Please use the /organizations or tenant-specific endpoint. So I did some research and found this documentation which says I can set a "tenant" parameter, but when I run this: blueprint = make_azure_blueprint( client_id="client_id_here", client_secret="client_secret_here", tenant="tenant_here" ) I get an error that: TypeError: make_azure_blueprint() got an unexpected keyword argument 'tenant' Does anyone know what I'm doing wrong? How do I set the Azure tenant in Flask Dance?
has title: Flask Make Azure Blueprint - got an unexpected argument 'tenant'
score: 0
type: Question
has answer: http://stackoverflow.com/a/52320694
answer count: 1
tagged with: flask

http://stackoverflow.com/comment/104223054
type: Comment
type: QuestionComment
has text: I think it was already answered here https://stackoverflow.com/questions/42228292/pymongo-valueerror-nattype-does-not-support-utcoffset-when-using-insert-many
score: 0
comment on: http://stackoverflow.com/q/52429644

http://stackoverflow.com/comment/91552143
type: QuestionComment
comment on: http://stackoverflow.com/q/52301848
has text: The code you have provided is not enough to test your code. What you have provided does not make much sense without some more context. I would never build a method that looks like this because it not very efficient and relatively redundant.
score: 0
type: Comment

http://stackoverflow.com/q/52387404
has answer: http://stackoverflow.com/a/52387548
has body: can you please show me how to add a 2-digit unique code in every user's input. The problem scenario is, if the program takes 4 inputs from the user (input1, input2, input3, input4), the program should also assign a unique 2-digit code in every input. this is just a small part of my assignment, but if you could guide me through how to get it, it will be a great help for me. You may give me a hint if you feel don't want to give the real answer, but this one's quite important for me as once I've got this I can get through all the rest of the codes :) here's what I have done so far: I want to utilise the numbers generated by this for loop. But, they should be used once only. for i in range(99): rnd = print(f'{i:02}') Asking a user input. Input1 = print(input("enter your first input: ")) Input2 = print(input("enter your second input: ")) Input3 = print(input("enter your third input: ")) Input4 = print(input("enter your fourth input: ")) here is the example output: 45 Input1 90 Input2 88 Input3 10 Input4 Thanks very much
downvote count: 4
has comment: http://stackoverflow.com/comment/91719532
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91719575
accepted answer: http://stackoverflow.com/a/52387548
score: -3
has title: Assigning a 2-digit unique code in a variable
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91719821
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91719323

http://stackoverflow.com/q/52385309
has body: I produced numerous plots in a Jupyer Notebook, so it shows up with a scrollbar. Like this: When I download it as html, the scrollbar disappear, and I get the plots just below each other, making the html too long: I mind that it is too long because I have cells after the plots, and I don't want the viewer of the html to have to scroll over hundreds of plots to see the next cell. How can I keep the scrollbar when I download as html? My client cannot open ipynb files. If presenting it nicely in html is not possible, how should I do it, not making the client having to scroll over hundreds of plots to see the next cell, but still being able to access those plots? The scrollbar would solve this problem, so that's why it is my aim to create a scrollbar.
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
score: 1
tagged with: jupyter-notebook
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: How can I download Jupyter Notebook as html, and keep scrollbars on the side?
type: Question

http://stackoverflow.com/q/52329521
answer count: 3
tagged with: pymysql
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52329564
has answer: http://stackoverflow.com/a/76955535
linked to: http://stackoverflow.com/q/37329370
has body: I would like to pass database as parameter sql = 'SELECT * FROM %s.table1' values = 'db-1' cursor.execute(sql, values) The problem is that %s is escaped using single quotes and it generates an error: Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''qualys_scan'.new_table' at line 1 On the other hand, using a simple parameter replacement: 'SELECT * FROM %s.table1'.format(values) is exploitable by sql injection. Any suggestion how to handle this? Approach for different mysql modules will be also helpful.
type: Question
tagged with: python
has title: Passing database name to sql statement as parameter with pymysql
has answer: http://stackoverflow.com/a/52331015
score: 0

http://stackoverflow.com/comment/91683121
has text: The first is a _relative_, the second an _absolute_ path. A relative path is interpreted relative to the current working directory your process is in, an absolute path is interpreted from the systems file system root node (`/`).
type: Comment
type: QuestionComment
score: 8
comment on: http://stackoverflow.com/q/52369398

http://stackoverflow.com/q/52333284
score: -1
answer count: 1
favorite count: 0
tagged with: prediction
tagged with: zero
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52333770
tagged with: python
has title: Random Forest not predicting zeros
downvote count: 2
has comment: http://stackoverflow.com/comment/91613819
upvote count: 1
type: Question
tagged with: random-forest
tagged with: missing-data
has body: I'm running a random forest on a data-set which contains a lot of zeros. These zeros represent a count of something (or absence thereof) and therefore are meaningful, by contrast to data that could be classed as 'missing'. When I run the predictions I am finding that my RF seems to be reluctant to predict zero, almost like it is not viewing 0 as a number and so defaults to 1 instead. Is there a way I can address this? I just find it odd that zero is not appearing as a prediction at any time.

http://stackoverflow.com/comment/91691164
has text: Ok I have updated the answer. That's only the way to do I think
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52371589

http://stackoverflow.com/a/52388754
type: Answer
answers question: http://stackoverflow.com/q/52387440
has body: Use map with set_index: import pandas as pd from io import StringIO csv1 = StringIO("""date yearMonth deviceCategory channelGrouping eventCategory Totalevents 20160719 201607 desktop Direct _GW_Legal_RM_false 149 20160719 201607 desktop Direct _GW_Risk_RM_false 298 20160719 201607 desktop Direct _GW_Risk_RM_true 149 20160719 201607 desktop Direct _GW__Product-Sign-In__ 895 20160719 201607 desktop Organic Search _GW_Legal_RM_false 149 20160719 201607 desktop Organic Search _GW_Risk_RM_false 746 20160719 201607 desktop Organic Search _GW__Product-Sign-In__ 1342 20160719 201607 desktop Referral _GW__Product-Sign-In__ 1044 20160719 201607 mobile Direct _GW_Legal_RM_false 149 20160719 201607 mobile Social _GW_Legal_RM_false 149 20160719 201607 tablet Direct _GW_Legal_RM_false 149 20160720 201607 desktop Branded Paid Search _GW_Legal_RM_false 149 20160720 201607 desktop Direct _GW_Legal_RM_false 149 20160720 201607 desktop Direct _GW__Product-Sign-In__ 746 20160720 201607 desktop Non-Branded Paid Search _GW_Legal_RM_false 149 20160720 201607 desktop Non-Branded Paid Search _GW_Risk_RM_false 149 20160720 201607 desktop Organic Search _GW_Legal_RM_false 1939 20160720 201607 desktop Organic Search _GW_Risk_RM_false 298""") csv2= StringIO("""eventCategory event_type _GW_Legal_RM_false Legal _GW_Legal_RM_true Legal _GW_Legal_RM_ Legal _GW_Risk_RM_false Risk _GW_Risk_RM_true Risk _GW_Risk_RM_ Risk _GW__Product-Sign-In__ Sign-in""") df1 = pd.read_csv(csv1,sep='\s\s+') df2 = pd.read_csv(csv2, sep='\s\s+') df1['event_type'] = df1['eventCategory'].map(df2.set_index('eventCategory')['event_type']) df1 Output: date yearMonth deviceCategory channelGrouping eventCategory Totalevents event_type 0 20160719 201607 desktop Direct _GW_Legal_RM_false 149 Legal 1 20160719 201607 desktop Direct _GW_Risk_RM_false 298 Risk 2 20160719 201607 desktop Direct _GW_Risk_RM_true 149 Risk 3 20160719 201607 desktop Direct _GW__Product-Sign-In__ 895 Sign-in 4 20160719 201607 desktop Organic Search _GW_Leg…
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91723560
upvote count: 1
has comment: http://stackoverflow.com/comment/91732228

http://stackoverflow.com/comment/91620097
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52333598
has text: I still can't digest this error. If Postgres is trying to kill/delete the connection may be because they are idle then it should be able to handle multiple requests as well. I just can't think of a reason that it should throw an error like this and breaking my test environment

http://stackoverflow.com/q/52284282
has body: I want to merge two dataframes on column profile_ID in Income df and index CommodityClass in CompProfile df. Income profile_ID type col1 col2 0 O-COMP-1006 Small_Off 4.1427e+07 4.0027e+07 1 O-COMP-1006 Small_Off 4.7915e+07 4.6515e+07 2 O-COMP-1006 Small_Off 6.10424e+07 5.96424e+07 3 O-COMP-1006 Small_Off 6.83726e+07 6.69726e+07 4 O-COMP-1008 Small_Off 7.28167e+07 7.14167e+07 5 O-COMP-1009 Small_Off 7.6147e+07 7.4747e+07 7 O-COMP-1006 Small_Off 8.02798e+07 7.88798e+07 8 O-COMP-1006 Small_Off 8.17172e+07 8.03172e+07 9 O-COMP-1006 Small_Off 8.42322e+07 8.28322e+07 10 O-COMP-1005 Small_Off 8.54957e+07 8.40747e+07 11 O-COMP-1006 Small_Off 8.67782e+07 8.53358e+07 12 O-COMP-1006 Small_Off 8.80798e+07 8.66159e+07 13 O-COMP-1007 Small_Off 8.9401e+07 8.79151e+07 14 O-COMP-1006 Small_Off 9.0742e+07 8.92338e+07 and CompProfile col1 col2 col3 CommodityClass profile_ID NaN NaN NaN O-COMP-1001 0.0 0.0 0.0 O-COMP-1002 0.0 0.0 0.0 O-COMP-1003 0.0 0.0 0.0 O-COMP-1004 0.0 0.0 0.0 O-COMP-1005 0.0 0.0 0.0 O-COMP-1006 1.0 0.0 0.0 O-COMP-1007 0.0 0.0 1.0 O-COMP-1008 0.0 0.0 0.0 O-COMP-1009 0.0 1.0 0.0 I use pd.merge( Income, CompProfile, how='left', \ left_on = 'profile_ID', right_index=True, \ suffixes = ("_USD","_frac") ) and get an error ValueError: You are trying to merge on object and int64 columns. If you wish to proceed you should use pd.concat I checked both the column and index that I am merging on, and they are of type object. I tried using join, but got the same error. Income.join(CompProfile, on= 'profile_ID',lsuffix = "_USD",rsuffix = "_frac") I also tried to reset the index of CompProfile and merge on columns: CompProfile.reset_index() pd.merge( Income, CompProfile, how='left', \ left_on = 'profile_ID', right_on='CommodityClass', \ suffixes = ("_USD","_frac") ) In this case I get KeyError: 'CommodityClass' I also tried removing "profile_ID" row from CompProfile, but it didn't change anything. CompProfile.head(10).to_dict() {'col1': {'profile_ID': nan, 'O-COMP-1001': 0.0, 'O-…
has title: Merging two dataframes on columns of the same data type, but getting ValueError
score: 0
has comment: http://stackoverflow.com/comment/91516840
tagged with: pandas
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52284902
has comment: http://stackoverflow.com/comment/91516785
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52284902
type: Question

http://stackoverflow.com/a/53877601
has comment: http://stackoverflow.com/comment/94737043
has comment: http://stackoverflow.com/comment/94739288
score: 0
has body: You should be able to read the environment variables on Python using the following: import os print os.environ['GOOGLE_CLOUD_KEYFILE_JSON']
type: Answer
answers question: http://stackoverflow.com/q/52394413
has comment: http://stackoverflow.com/comment/95067898

http://stackoverflow.com/comment/91579723
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52316001
has text: datetime.datetime.utcfromtimestamp(your timestamp)

http://stackoverflow.com/comment/91736456
has text: Basically what I want is to tell it if either of these values are missing from the given columns, set the value to zero.
comment on: http://stackoverflow.com/q/52389514
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52368510
has comment: http://stackoverflow.com/comment/91743455
has title: How to edit data from a database using QLineEdit or Something else
has body: I have QTableView filled with data from a database,I made it to on one click mark some row but now I have a problem... I want to open a new window with a double click, which will contain QLineEdit with already existing data from the database and if necessary, change them and record them to the database? How can i do it? EDIT: I succeeded to print data from database but I have not yet displayed as a result in a new window in QLineEdit code: import sys from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets import QLineEdit from PyQt5.QtWidgets import QPushButton from PyQt5.QtWidgets import QVBoxLayout, QTableView, QAbstractItemView,QLabel,QLineEdit,QTextEdit,QGridLayout from PyQt5.QtWidgets import QWidget from PyQt5 import QtSql,QtWidgets,QtGui,QtCore import sqlite3 as mdb class sqlite_conect(object): def sqlite_conect(self, find_text, find_function): self.connection = mdb.connect('imenik.db') self.cursor = self.connection.cursor() self.find_text1 = "%" + find_text + "%" db = QtSql.QSqlDatabase.addDatabase("SQLITE3"); ok = db.open() def createConnection(): db = QtSql.QSqlDatabase.addDatabase("QSQLITE") db.setDatabaseName("imenik.db") if not db.open(): QtWidgets.QMessageBox.critical(None, "Cannot open database", "Unable to establish a database connection.\n" "This example needs SQLite support. Please read " "the Qt SQL driver documentation for information how " "to build it.\n\n" "Click Cancel to exit.", QtWidgets.QMessageBox.Cancel) return False return True class Glavni_prozor(QWidget): def __init__(self): super(Glavni_prozor, self).__init__() self.setFixedSize(1024, 768) self.edit_window = edit_window(self) layout = QVBoxLayout(self) self.tabelaEditovanje = QTableView() self.tabelaEditovanje.setGeometry(50, 50, 300, 200) self.tabelaEditovanje.setSelectionMode(QAbstractItemView.SingleSelection) self.tabelaEditovanje.setSelectionBehavior(QAbstractItemView.SelectRows) self.tabelaEditovanje.doubleClicked.connect(self.select_id) se…
tagged with: pyqt
tagged with: sqlite
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52447989
tagged with: python
has comment: http://stackoverflow.com/comment/91741755
has comment: http://stackoverflow.com/comment/91743874
type: AnsweredQuestion
upvote count: 2
score: 1
tagged with: pyqt5
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52447989

http://stackoverflow.com/comment/91515107
type: Comment
has text: To make this a fair comparison, unless this is Python 2, you should probably start with `b = list(range(2000000))`. Otherwise your pure-Python version is allocating only half the memory, because it doesn’t make a list until after the first filter. (I suspect that won’t make the problem go away and you’ll still have a good question—but it would be an even better question because you ruled out one possibility.)
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/52283346

http://stackoverflow.com/comment/91617363
comment on: http://stackoverflow.com/q/52334940
has text: Did you try `discover_page.find_all("a", class_="author track")`? The `~` looks a bit weird there. `discover_page.select('a[class="author track"]')` should also work.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52306635
tagged with: reticulate
downvote count: 0
answer count: 1
has title: Cannot import geopandas using reticulate in RStudio when knitting with knitr
favorite count: 0
has answer: http://stackoverflow.com/a/52322592
tagged with: http://stackoverflow.com/tag/r
tagged with: geopandas
tagged with: python
accepted answer: http://stackoverflow.com/a/52322592
type: AnsweredQuestion
tagged with: knitr
score: 1
upvote count: 1
type: Question
has body: I am trying to knit an Rmd file using reticulate and Python inside of a virtualenv. The following is my R set up chunk: ```{r r-setup} library(reticulate) venv_path &lt;- "/path/to/venv/" use_virtualenv(venv_path, required = TRUE) ``` This works as expected. However, the next step breaks when I try to import geopandas: ```{python} import geopandas as gpd ``` The traceback is as follows: Error in py_module_import... OSError: Could not find lib c or load any variants... The traceback error points to the shapely package from shapely.geometry import shape, Point File. Other Python libraries load with no issue within the chunk e.g. import os. From these messages, I'm guessing that it is not loading the OGR/GDAL bindings. However, I'm not sure how to solve this. import geopandas runs without error when I run the chunk inside of the notebook e.g. not knitting. It also works within the repl_python() shell of my project. So the issue seems to be principally with knitr and knitting. My RStudio version is: 1.1.456. The output of session_info() is: sessionInfo() R version 3.5.1 (2018-07-02) Platform: x86_64-apple-darwin17.6.0 (64-bit) Running under: macOS High Sierra 10.13.6 Matrix products: default BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib LAPACK: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libLAPACK.dylib locale: [1] en_NZ.UTF-8/en_NZ.UTF-8/en_NZ.UTF-8/C/en_NZ.UTF-8/en_NZ.UTF-8 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] reticulate_1.10 stringr_1.3.1 dplyr_0.7.6 ggplot2_3.0.0 loaded via a namespace (and not attached): [1] Rcpp_0.12.18 pillar_1.3.0 compiler_3.5.1 plyr_1.8.4 [5] bindr_0.1.1 tools_3.5.1 digest_0.6.17 packrat_0.4.9-3 [9] jsonlite_1.5 evaluate_0.11 tibble_1.4.2 gtable_0.2.0 [13] lattice_0.20-35 pkgconfig_2.0.2 rlang_0.2.2 Matrix_1.2-14 [17] yaml_2.2.0 bindrcpp_0.2.2 withr…

http://stackoverflow.com/comment/91763030
comment on: http://stackoverflow.com/q/52409419
type: Comment
type: QuestionComment
has text: ok got it! so the code I've written achieves what I want to do?
score: 0

named-entity-recognition
tags question: http://stackoverflow.com/q/52384517
type: Tag
tag name: named-entity-recognition

http://stackoverflow.com/q/52278525
tagged with: python
has comment: http://stackoverflow.com/comment/91506283
has title: Nuitka TypeError compiler error object of type 'generator' has no len()
has comment: http://stackoverflow.com/comment/91508193
answer count: 0
tagged with: nuitka
score: 1
has comment: http://stackoverflow.com/comment/91658588
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91509523
has body: When I compile with Nuitka (nuitka --standalone file.py) I get the following type error: Traceback (most recent call last): File "C:\Users\Tearzz\AppData\Local\Programs\Python\Python36\lib\site-packages\nuitka\build\inline_copy\bin\..\lib\scons-3.0.1\SCons\Taskmaster.py", line 241, in execute if not t.retrieve_from_cache(): File "C:\Users\Tearzz\AppData\Local\Programs\Python\Python36\lib\site-packages\nuitka\build\inline_copy\bin\..\lib\scons-3.0.1\SCons\Node\FS.py", line 2925, in retrieve_from_cache return self.get_build_env().get_CacheDir().retrieve(self) File "C:\Users\Tearzz\AppData\Local\Programs\Python\Python36\lib\site-packages\nuitka\build\inline_copy\bin\..\lib\scons-3.0.1\SCons\Environment.py", line 1016, in get_CacheDir cd = SCons.CacheDir.CacheDir(path) File "C:\Users\Tearzz\AppData\Local\Programs\Python\Python36\lib\site-packages\nuitka\build\inline_copy\bin\..\lib\scons-3.0.1\SCons\CacheDir.py", line 163, in __init__ if os.path.isdir(path) and len(f for f in os.listdir(path) if os.path.basename(f) != "config") != 0: TypeError: object of type 'generator' has no len() I've already reinstalled Nuitka and pip installed Scons successfully. But I keep getting this error when it compiles. I'm not sure what's going on and I can't find answers to my problem other places.
tagged with: scons
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91658558
tagged with: compiler-errors
has comment: http://stackoverflow.com/comment/91509303
type: UnansweredQuestion

http://stackoverflow.com/comment/91792440
score: 0
type: Comment
type: QuestionComment
has text: I use git shell only as bash on windows. The sources are manager in SVN in the project. I wanted only to convert XML-files, because the parser seems to break, when mixed line endings occure. Other files should remain as is.
comment on: http://stackoverflow.com/q/52424786

http://stackoverflow.com/comment/91491702
type: QuestionComment
has text: hint: one approach might be to use [`groupby`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html) in combination with [`shift`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html)
comment on: http://stackoverflow.com/q/52272229
score: 0
type: Comment

http://stackoverflow.com/a/52348919
downvote count: 0
has body: What I came up with was to generate a sequence for each i, then have an enclosing comprehension flatten those into a single list: [x for y in ((i*j if i%2 else i+j for j in range(0, 2)) if i == 3 else (i,) for i in range(3, 5)) for x in y] # [0, 3, 4] Obviously, this is way more complicated and difficult to read than the nested version, and probably performs more poorly.
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52348813
score: 2

http://stackoverflow.com/comment/91686538
type: QuestionComment
comment on: http://stackoverflow.com/q/52370048
score: 0
type: Comment
has text: I don't think mcc() is the bottleneck. Even if you just do dot product (dot()) it takes a lot of time. What do you mean parallelize? using Tensorflow or something? Why does R do it quickly out of the box?

http://stackoverflow.com/a/52408398
type: Answer
has comment: http://stackoverflow.com/comment/91761043
score: 2
upvote count: 2
has body: You can do something like this: But the approach is more specific to your problem. print {key:dict2.get(key.split(',')[0]+')')for key in dict1} # {'X(0,0)': 'area1', 'X(0,1)': 'area1', 'X(1,0)': 'area2', 'X(1,1)': 'area2'} Conversion of X(0,0) to X(0) do like this, In [29]: 'X(0,0)'.split(',') Out[29]: ['X(0', '0)'] In [30]: 'X(0,0)'.split(',')[0]+')' Out[30]: 'X(0)'
answers question: http://stackoverflow.com/q/52408268
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52408268

http://stackoverflow.com/q/52415187
type: Question
has comment: http://stackoverflow.com/comment/91774355
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91774835
tagged with: jupyter-notebook
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91775330
has title: jupyter notebook matplotlib figureframe changes size unexpectedly
tagged with: python
has comment: http://stackoverflow.com/comment/91774186
has body: I'm trying to have a jupyter notebook shows a progression of plots in a for loop. The code works, but for some reason the size of the figure changes after the for loop is done. Here's a set of minimal code to illustrate this (in jupyter notebook) import numpy as np import matplotlib import matplotlib.pyplot as plt %matplotlib notebook for i in range(10): plt.gca().scatter(np.random.rand(10), np.random.rand(10)) plt.gcf().canvas.draw() plt.gcf().canvas.flush_events() plt.pause(0.5) A gif illustrating the issue is attached. This problem has been driving me crazy and changing margins or using tight_layouts() do not help. It seems to be related to how FigureFrame object is rendered. Thanks for the help!
has answer: http://stackoverflow.com/a/52415713
tagged with: matplotlib

http://stackoverflow.com/comment/91581213
has text: Is there another way to contact you other than here? I have more questions about this code and how I can make it work further but i don't want to clog up this.
comment on: http://stackoverflow.com/a/52305215
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52401161
upvote count: 16
has body: If you read the source code of pathlib.Path.open you'll find that it simply does: return io.open(str(self), mode, buffering, encoding, errors, newline, opener=self._opener) and according to io's documentation: io.open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) This is an alias for the builtin open() function. So you are correct that pathlib.Path.open is just a wrapper for the built-in open function.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52400957
answers question: http://stackoverflow.com/q/52400957
type: Answer
downvote count: 0
score: 16

http://stackoverflow.com/comment/91790037
has text: Be careful if you are using p.name() to identify processes, as it may be possible for unrelated processes to have the same name. It may be safer to use p.exe() to match the executable path instead.
comment on: http://stackoverflow.com/a/52423209
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91662430
has text: Shall I update your code with these fixes? With them this is what I consider an acceptable answer, and I don't want to post my updated version as an answer, where you have done most of the hard work. I can also get you a link to the modified code if you want.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52324580

seaborn
tags question: http://stackoverflow.com/q/52385428
tags question: http://stackoverflow.com/q/52392438
tags question: http://stackoverflow.com/q/52337711
tags question: http://stackoverflow.com/q/52285104
tag name: seaborn
tags question: http://stackoverflow.com/q/52301288
tags question: http://stackoverflow.com/q/52364815
tags question: http://stackoverflow.com/q/52393084
tags question: http://stackoverflow.com/q/52312174
tags question: http://stackoverflow.com/q/52390757
tags question: http://stackoverflow.com/q/52298821
tags question: http://stackoverflow.com/q/52346148
tags question: http://stackoverflow.com/q/52389106
tags question: http://stackoverflow.com/q/52403381
tags question: http://stackoverflow.com/q/52314599
tags question: http://stackoverflow.com/q/52369437
tags question: http://stackoverflow.com/q/52314094
tags question: http://stackoverflow.com/q/52399990
tags question: http://stackoverflow.com/q/52314676
tags question: http://stackoverflow.com/q/52360977
tags question: http://stackoverflow.com/q/52289579
tags question: http://stackoverflow.com/q/52317441
tags question: http://stackoverflow.com/q/52348044
tags question: http://stackoverflow.com/q/52345983
tags question: http://stackoverflow.com/q/52366087
tags question: http://stackoverflow.com/q/52312350
tags question: http://stackoverflow.com/q/52284034
tags question: http://stackoverflow.com/q/52392855
tags question: http://stackoverflow.com/q/52420515
tags question: http://stackoverflow.com/q/52308749
tags question: http://stackoverflow.com/q/52412406
tags question: http://stackoverflow.com/q/52334938
tags question: http://stackoverflow.com/q/52392728
type: Tag
tags question: http://stackoverflow.com/q/52318464
tags question: http://stackoverflow.com/q/52291423
tags question: http://stackoverflow.com/q/52297501

http://stackoverflow.com/comment/91519261
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52283839
has text: nope that didnt work , thanks for suggestion though unless im calling the frame incorrectly.
score: 0

http://stackoverflow.com/comment/91560987
has text: I didn't find such a tag so added 'python' tag. Thx!
comment on: http://stackoverflow.com/q/52305670
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91674610
type: Comment
comment on: http://stackoverflow.com/a/52356815
score: 0
type: AnswerComment
has text: See my updated answer that does not include a header. I forgot you need to start enumerating from 1.

http://stackoverflow.com/q/52415743
score: 0
tagged with: python
tagged with: discord
type: UnansweredQuestion
has title: YT Search on Discord Bot
upvote count: 1
downvote count: 1
type: Question
tagged with: discord.py
answer count: 1
favorite count: 0
has body: i would like to know how to make my bot play music based on YouTube search rather than having to copy in a URL. Here's my code for playing music right now, @client.command(pass_context=True) async def play(ctx, url): server = ctx.message.server await client.say ('Music now playing...') voice_client = client.voice_client_in(server) player = await voice_client.create_ytdl_player(url, after=lambda: check_queue(server.id)) players[server.id] = player player.start() What is it that I need to add to make it play search results instead of URL's. Thanks!
has answer: http://stackoverflow.com/a/52429081

http://stackoverflow.com/comment/91794435
has text: The `@login_required` decorator will not help you with this. You should add a manual test to the view function itself.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52425647

http://stackoverflow.com/comment/91751269
type: Comment
type: QuestionComment
has text: Can you share the error traceback please?
comment on: http://stackoverflow.com/q/52402622
score: 0

http://stackoverflow.com/q/52352825
accepted answer: http://stackoverflow.com/a/52353136
has body: I am a new python user and would like to ask about does it possible to combine or merge the data frames that come from the different data frames but they have one column that has the same information? Data 1 Data2 DocID GroupID DocID ClassID 123 A12 123 X 123 A24 123 Y 124 A24 124 Z 124 C12 124 F 125 A12 125 G I hope the result will be like this Results DocID 123 124 125 Group_ID Class_ID A12 X 1 0 0 A24 Y 1 0 0 A24 Z 0 1 0 C12 F 0 0 1 A12 G 0 0 1 Thank you for helping in advance T___T
type: Question
has comment: http://stackoverflow.com/comment/91650601
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/91664139
tagged with: python
has answer: http://stackoverflow.com/a/52353136
type: AnsweredQuestion
has title: Python: How to combine specific columns from two different data frames

http://stackoverflow.com/q/52427123
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
type: Question
has answer: http://stackoverflow.com/a/69352052
has body: Below is what I would like to input as my testing event and is what my lambda python function knows how to process. { "body": '{"email":"example@example.com","password":"Example1"}', "path": "/SignIn" } However, you can't configure this as a testing event in aws lambda because you get the following–somewhat justified–error: There is an error in your JSON event. Please correct it before saving. It is somewhat justified because there shouldn't be any single quotes in JSON. However, it won't work if I use all double quotes either. Any ideas? Loopholes?
has comment: http://stackoverflow.com/comment/91798351
tagged with: amazon-web-services
has title: Testing aws lambda python function with nested json
has comment: http://stackoverflow.com/comment/91798081
answer count: 1
downvote count: 0
favorite count: 0
tagged with: aws-lambda
tagged with: python
has comment: http://stackoverflow.com/comment/91800374
score: 2
upvote count: 2

http://stackoverflow.com/comment/91687974
score: 1
comment on: http://stackoverflow.com/q/52371062
has text: Note: this feature in Python is called slicing. Just thought I'd give you this terminology so you can do more effective searches in the future.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91776758
comment on: http://stackoverflow.com/q/52416449
score: 0
type: Comment
has text: [[10, 5, 3], [10, 3, 12 ], [12, 5, 5]] so this would be filtered as [ [5,3,3], [5,5]]
type: QuestionComment

http://stackoverflow.com/comment/98573751
type: AnswerComment
type: Comment
has text: @Sigur - No, `lines[0]` is always the first line in the list, as each is deleted, the *next* line becomes `lines[0]`. So for 3 times, the code removes the first line.
score: 1
comment on: http://stackoverflow.com/a/52308021

http://stackoverflow.com/comment/91661351
score: 0
type: Comment
type: QuestionComment
has text: I executed the code that you posted: `df'Open','Volumes'.corr()`.
comment on: http://stackoverflow.com/q/52358417

http://stackoverflow.com/a/52280599
upvote count: 2
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52280531
score: 2
has body: Negate your column, groupby A, and use transform: s= (~df.match).groupby(df.A).transform('sum') Next use loc to select desired values: df.loc[s.le(2)] A match 437 8 True 438 8 True 439 8 True 440 8 True 441 8 True 442 8 False 488 2 False 489 2 True 490 2 True In one line: df.loc[(~df.match).groupby(df.A).transform('sum').le(2)]
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52280531

http://stackoverflow.com/comment/91643931
comment on: http://stackoverflow.com/q/52349325
type: QuestionComment
type: Comment
has text: The parentheses are completely redundant and would be removed by the interpreter.
score: 0

http://stackoverflow.com/comment/91696369
score: 0
has text: If you intended to send a `£` in your byte sequence, then the issue may be related to incorrect encodings. As for the syntax error, that was my bad. I had added an extra parenthesis at the end of the return statement.
type: AnswerComment
comment on: http://stackoverflow.com/a/52358905
type: Comment

http://stackoverflow.com/q/52343186
score: 0
has answer: http://stackoverflow.com/a/52343546
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91649386
has comment: http://stackoverflow.com/comment/91632776
tagged with: arduino
type: Question
linked to: http://stackoverflow.com/q/23100704
has body: I'm doing a preliminary script for reading the serial port when i send the "1" over serial for infinite time every 3 minutes. I need a thread script because this it will have to be integrated with others function together serial . The serial port is connected to an arduino with sensor but i'm not sure program is formally corrected. Anyone can help me please? Thanks #!/usr/bin/python import time import serial import threading import time import io ser=serial.Serial('/dev/ttyUSB0', 57600, timeout=3) def printit(): threading.Timer(180.0, printit).start() ser.write(b'1\n') lettura=ser.readline() print lettura try: printit() except: print "Error: unable to start thread" while 1: pass
has title: python thread serial read infinite loop

http://stackoverflow.com/a/52403318
has comment: http://stackoverflow.com/comment/114867515
score: 106
has comment: http://stackoverflow.com/comment/114855842
has comment: http://stackoverflow.com/comment/91755185
answers question: http://stackoverflow.com/q/52403065
type: Answer
has comment: http://stackoverflow.com/comment/91754632
has comment: http://stackoverflow.com/comment/91752504
accepted answer of: http://stackoverflow.com/q/52403065
upvote count: 106
has comment: http://stackoverflow.com/comment/91754659
has body: Are you sure you need that pattern? --foo and --foo <value>, together, for a boolean switch, is not a common pattern to use. As for your issue, remember that the command line value is a string and, type=bool means that you want bool(entered-string-value) to be applied. For --foo False that means bool("False"), producing True; all non-empty strings are true! See Why is argparse not parsing my boolean flag correctly? as well. Instead of supporting --foo / --foo <string value>, I would strongly recommend you use --foo to mean True, drop the argument value, and instead add a --no-foo option to explicitly set False: parser.add_argument('--foo', default=False, action='store_true') parser.add_argument('--no-foo', dest='foo', action='store_false') The dest='foo' addition on the --no-foo switch ensures that the False value it stores (via store_false) ends up on the same args.foo attribute. As of Python 3.9, you can also use the argparse.BooleanOptionalAction action class: parser.add_argument("--foo", action=argparse.BooleanOptionalAction) and it'll have the same effect, handling --foo and --no-foo to set and clear the flag. You'd only need a --foo / --no-foo combination if you have some other configuration mechanism that would set foo to True and you needed to override this again with a command-line switch. --no- is a widely adopted standard to invert a boolean command-line switch. If you don't have a specific need for a --no-foo inverted switch (since just omitting --foo would already mean 'false'), then just stick with the action='store_true' option. This keeps your command line simple and clear! However, if your use case or other constraints specifically require that your command line must have some kind of --foo (true|false|0|1) support, then add your own converter: def str_to_bool(value): if isinstance(value, bool): return value if value.lower() in {'false', 'f', '0', 'no', 'n'}: return False elif value.lower() in {'true', 't', '1', 'yes', 'y'}: return True raise ValueE…
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91530841
type: QuestionComment
comment on: http://stackoverflow.com/q/52289934
score: 2
has text: The question is not clear. Are you saying that you put reST syntax inside the HTML content, which in turn you expect the `raw` directive to process as reST? If so, that's not possible. Instead you can have an opening `raw` directive with HTML, then your reST, then a closing `raw` directive.
type: Comment

http://stackoverflow.com/q/52294179
answer count: 2
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/91536237
has comment: http://stackoverflow.com/comment/91536726
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/91536939
has comment: http://stackoverflow.com/comment/91536519
has answer: http://stackoverflow.com/a/52294800
has body: I'm currently making this program that was given to me by my school and it's to write your own name in ASCII text art but that was just copying and pasting. I am trying to make it so the user enters an input and there their name is output. My program currently works except it doesnt stay on one line. My code: name = input("What is your name: ") splitname = list(name) for i in range(len(splitname)): f=open(splitname[i] + ".txt","r") contents = f.read() print(contents) And this is what it outputs: I would like to get it all onto one line if possible, how would I do so?
has title: Can't import data from files into one line
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52294483
favorite count: 0
type: Question

http://stackoverflow.com/comment/91574316
comment on: http://stackoverflow.com/a/52312650
has text: Excellent explanation. Thanks. Although it will require deeper investigation and more time to digest the details, it answers my question.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/52271644
favorite count: 0
tagged with: python
upvote count: 11
type: AnsweredQuestion
tagged with: autoencoder
has title: Extract encoder and decoder from trained autoencoder
score: 11
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/52282558
tagged with: keras-layer
answer count: 1
has body: I want to divide the autoencoder learning and applying into two parts following https://blog.keras.io/building-autoencoders-in-keras.html and using the fashion-mnist data for testing purposes: Load the images, do the fitting that may take some hours or days and use a callback to save the best autoencoder model. That process can be some weeks before the following part. Use this best model (manually selected by filename) and plot original image, the encoded representation made by the encoder of the autoencoder and the prediction using the decoder of the autoencoder. I have problems (see second step) to extract the encoder and decoder layers from the trained and saved autoencoder. For step one I have the very simple network as follows: input_img = Input(shape=(784,)) # encoded representation encoded = Dense(encoding_dim, activation='relu')(input_img) # lossy reconstruction decoded = Dense(784, activation='sigmoid')(encoded) # full AE model: map an input to its reconstruction autoencoder = Model(input_img, decoded) # encoder: map an input to its encoded representation encoder = Model(input_img, encoded) # placeholder for an encoded input encoded_input = Input(shape=(encoding_dim,)) # last layer of the autoencoder model decoder_layer = autoencoder.layers[-1] # decoder decoder = Model(encoded_input, decoder_layer(encoded_input)) The networks are: autoencoder.summary() _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_5 (InputLayer) (None, 784) 0 _________________________________________________________________ dense_5 (Dense) (None, 32) 25120 _________________________________________________________________ dense_6 (Dense) (None, 784) 25872 ================================================================= and encoder.summary() _________________________________________________________________ Layer (type) Output Shape Param # ===========================…
downvote count: 0
accepted answer: http://stackoverflow.com/a/52282558
tagged with: keras

http://stackoverflow.com/comment/95282018
type: Comment
comment on: http://stackoverflow.com/a/52362473
score: 2
type: AnswerComment
has text: This ended up working for me among numerous supposed solutions. Thanks a lot.

http://stackoverflow.com/a/52376843
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52375305
type: Answer
has body: Solved it by splitting the image into pieces, processing them one by one and combining them. To avoid visible "split lines" in the output image, I repeat the process described above with different piece sizes and calculate the mean. I ended up with this: def inference(self, filename, self_ensemble=False): img_q = Image.open(filename) scale = 4 if img_q.width &gt; 400: total = np.zeros((img_q.height * scale, img_q.width * scale, 3)) #repeat 7 times with different piece size for x in range(7): total += self.inference_inter(filename, scale, 32 * (x + 8), ensemble=self_ensemble) total = total / 7.0 image = misc.toimage(total, cmin=0, cmax=255) fn_res = filename.replace(".png", "_result.png").replace(".jpg", "_result.jpg") misc.imsave(fn_res, image) else: img_in = misc.imread(filename) / 255.0 res = self.sess.run(self.out, feed_dict={ self.x: [img_in], self.is_training: False, self.lr_input: 0.0 })[0] * 255.0 image = misc.toimage(res, cmin=0, cmax=255) fn_res = filename.replace(".png", "_result.png").replace(".jpg", "_result.jpg") misc.imsave(fn_res, image) def inference_inter(self, filename, scale, pat_size, ensemble=True): img_in = misc.imread(filename) / 255.0 img_q = Image.open(filename) res = np.zeros((img_q.height * scale, img_q.width * scale, 3)) for qx in range(0, img_q.width, pat_size): for qy in range(0, img_q.height, pat_size): res[(qy * scale):((qy + pat_size) * scale)][(qx * scale):((qx + pat_size) * scale)] = self.sess.run(self.out, feed_dict={ self.x: [img_in[qy:(qy + pat_size)][qx:(qx + pat_size)]], self.is_training: False, self.lr_input: 0.0 })[0] * 255.0 return res
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/52375305

http://stackoverflow.com/q/52414348
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: boost
has comment: http://stackoverflow.com/comment/91773826
type: Question
has answer: http://stackoverflow.com/a/52418440
has title: Boost Python Numpy - Undefined reference to initialize
has comment: http://stackoverflow.com/comment/91773252
tagged with: numpy
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/52418440
favorite count: 0
tagged with: python-3.x
has body: I am having problems when linking the following code: #include &lt;boost/python.hpp&gt; #include &lt;boost/python/numpy.hpp&gt; BOOST_PYTHON_MODULE (MyLibrary) { Py_Initialize() ; boost::python::numpy::initialize() ; ... } which returns: undefined reference to `boost::python::numpy::initialize(bool)' I am using Boost 1.68 with Python 3.6, compiled as follows: ./bootstrap.sh --with-python=/usr/bin/python3 --with-python-version=3.6 --with-python-root=/usr/lib/python3.6 ./b2 --with-python link=shared install And I am linking using: /usr/bin/c++ -shared -o MyLibrary.so MyLibrary.cpp.o -L/usr/local/lib -lpython3.6m /usr/local/lib/libboost_python36.so Any idea...?
tagged with: python
tagged with: c++

http://stackoverflow.com/comment/91516776
score: 0
comment on: http://stackoverflow.com/a/52284151
type: Comment
has text: Yes...your question about the WHERE clause let me look at it closely and then I saw it. Thanks.
type: AnswerComment

http://stackoverflow.com/comment/91560605
has text: @winteralfs edit your question, do not add it in the comments.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52306342
type: Comment

http://stackoverflow.com/q/52428667
tagged with: python
type: Question
score: 0
tagged with: facebook
answer count: 1
accepted answer: http://stackoverflow.com/a/53185337
has body: We are busy upgrading from the Marketing API to the Business API (not graph API and not marketing API) for Facebook. The documentation states that one should be able to create a test.py with the following code: import sys sys.path.append('/opt/homebrew/lib/python2.7/site-packages') sys.path.append('/opt/homebrew/lib/python2.7/site-packages/facebook_business-3.0.0-py2.7.egg-info') from facebook_business.api import FacebookAdsApi from facebook_business.adobjects.adaccount import AdAccount my_app_id = 'your-app-id' my_app_secret = 'your-appsecret' my_access_token = 'your-access-token' FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token) my_account = AdAccount('your-adaccount-id') campaigns = my_account.get_campaigns() print(campaigns) This requires an app secret proof which I am obtaining with the following hash: facebook_app_id = 'xxxxx' facebook_app_secret = 'xxxxx' facebook_app_token = 'xxxxx|xxxxx'.format(facebook_app_id,facebook_app_secret) import hmac,hashlib app_secret_proof = hmac.new(facebook_app_secret.encode('utf-8'), msg=facebook_app_token.encode('utf-8'), digestmod=hashlib.sha256).hexdigest() print(app_secret_proof) The is the error I get: Traceback (most recent call last): File "test.py", line 12, in &lt;module&gt; FacebookAdsApi.init(my_app_id,my_app_secret,my_access_token,my_appsecret_proof) File "/Users/facebook_business/api.py", line 202, in init cls.set_default_account_id(account_id) File "/Users/facebook_business/api.py", line 225, in set_default_account_id "Account ID provided in FacebookAdsApi.set_default_account_id " ValueError: Account ID provided in FacebookAdsApi.set_default_account_id expects a string that begins with 'act_' None of the ID's start with act_, I am currently using the App ID that is at the top left of the app dashboard which one should I be using? Marketing API
has title: Facebook Business API request campaigns via python
has answer: http://stackoverflow.com/a/53185337
type: AnsweredQuestion
tagged with: facebook-marketing-api

http://stackoverflow.com/comment/91621342
comment on: http://stackoverflow.com/q/52336707
score: 0
type: Comment
type: QuestionComment
has text: Thanks for the help, @Swift.

http://stackoverflow.com/q/52320059
type: AnsweredQuestion
downvote count: 0
type: Question
score: 3
has comment: http://stackoverflow.com/comment/91589039
has title: Creating a new Sequential model inside a for loop (using Keras)
tagged with: neural-network
has body: I want to try training my model with different hyperparameters, so I've setup a series of nested for loops to iterate through them. model = None batch_generator = None for sequence_length in all_sequence_length: for label_periods in all_label_periods: for num_layers in all_num_layers: for num_units in all_num_units: loadFiles() createmodel() trainmodel() The first iteration creates a model like this: Layer (type) Output Shape Param # ================================================================= cu_dnnlstm_1 (CuDNNLSTM) (None, 100, 75) 45300 _________________________________________________________________ dropout_1 (Dropout) (None, 100, 75) 0 _________________________________________________________________ cu_dnnlstm_2 (CuDNNLSTM) (None, 100, 75) 45600 _________________________________________________________________ dropout_2 (Dropout) (None, 100, 75) 0 _________________________________________________________________ cu_dnnlstm_3 (CuDNNLSTM) (None, 100, 75) 45600 _________________________________________________________________ dropout_3 (Dropout) (None, 100, 75) 0 _________________________________________________________________ cu_dnnlstm_4 (CuDNNLSTM) (None, 100, 75) 45600 _________________________________________________________________ dropout_4 (Dropout) (None, 100, 75) 0 _________________________________________________________________ cu_dnnlstm_5 (CuDNNLSTM) (None, 100, 75) 45600 _________________________________________________________________ dropout_5 (Dropout) (None, 100, 75) 0 _________________________________________________________________ dense_1 (Dense) (None, 3) 228 ================================================================= I then call model.fit_generator() to train the model and that executes fine. The model is then created again in the next loop iteration and the summary looks like this: Layer (type) Output Shape Param # ================================================================= cu_dnnlstm_6 (CuDNNLSTM) (None, 100, 75) 45300…
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/91588725
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/52320889
accepted answer: http://stackoverflow.com/a/52320889
tagged with: python

http://stackoverflow.com/q/52340319
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/52369721
favorite count: 0
accepted answer: http://stackoverflow.com/a/52369721
linked to: http://stackoverflow.com/q/7395444
upvote count: 3
has comment: http://stackoverflow.com/comment/91627867
has body: Is there a way in pytest to add an attribute to a test, say for example "smoke test" or "regression" and then run only those tests?
tagged with: python
has title: Executing specific tests using pytest
downvote count: 0
type: AnsweredQuestion
score: 3
tagged with: pytest

http://stackoverflow.com/q/52429988
tagged with: async-await
upvote count: 14
accepted answer: http://stackoverflow.com/a/52430071
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52430071
tagged with: python
tagged with: generator
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/46789093
downvote count: 0
has body: I need to process several pages of data from server. I would like to make a generator for it like this. Unfortunately I get TypeError: 'async_generator' object is not iterable async def get_data(): i = 0 while i &lt; 3: i += 1 data = await http_call() # call to http-server here yield data data = [i for i in get_data()] # inside a loop Next variant raises TypeError: object async_generator can't be used in 'await' expression data = [i for i in await get_data()] # inside a loop
type: Question
score: 14
has title: How to use asynchronous generator in Python 3.6?
linked to: http://stackoverflow.com/q/52582685

http://stackoverflow.com/q/52334558
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/35071393
has title: Runge-Kutta 4th order method to solve second-order ODES
type: Question
has comment: http://stackoverflow.com/comment/91631130
score: 5
has comment: http://stackoverflow.com/comment/91631194
upvote count: 5
accepted answer: http://stackoverflow.com/a/52368592
has comment: http://stackoverflow.com/comment/91631106
has body: I am trying to do a simple example of the harmonic oscillator, which will be solved by Runge-Kutta 4th order method. The second-order ordinary differential equation (ODE) to be solved and the initial conditions are: y'' + y = 0 y(0) = 0 and y'(0) = 1/pi The range is between 0 and 1 and there are 100 steps. I separated my 2nd order ODE in two first-order ODEs, using u as auxiliary variable: y' = u u' = -y The analytical solution is sinusoidal y(x) = (1/pi)^2 sin(pi*x). My Python code is below: from math import pi from numpy import arange from matplotlib.pyplot import plot, show # y' = u # u' = -y def F(y, u, x): return -y a = 0 b = 1.0 N =100 h = (b-a)/N xpoints = arange(a,b,h) ypoints = [] upoints = [] y = 0.0 u = 1./pi for x in xpoints: ypoints.append(y) upoints.append(u) m1 = h*u k1 = h*F(y, u, x) #(x, v, t) m2 = h*(u + 0.5*k1) k2 = h*F(y+0.5*m1, u+0.5*k1, x+0.5*h) m3 = h*(u + 0.5*k2) k3 = h*F(y+0.5*m2, u+0.5*k2, x+0.5*h) m4 = h*(u + k3) k4 = h*F(y+m3, u+k3, x+h) y += (m1 + 2*m2 + 2*m3 + m4)/6 u += (k1 + 2*k2 + 2*k3 + k4)/6 plot(xpoints, ypoints) show() All code was corrected as suggested by LutzL. See comments below. The code is running but my numerical solution does not match with the analytical solution. I made a graph showing the two solutions below. I compared my script with some other's codes (https://math.stackexchange.com/questions/721076/help-with-using-the-runge-kutta-4th-order-method-on-a-system-of-2-first-order-od) on internet and I cannot see the error. In the link, there are two codes, a Matlab one and Fortran one. Even then, I cannot find my mistake. Can anyone help me?
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52368592
tagged with: runge-kutta
tagged with: ode

http://stackoverflow.com/a/52400502
answers question: http://stackoverflow.com/q/52391451
type: AcceptedAnswer
upvote count: 23
type: Answer
downvote count: 0
score: 23
has body: Just use parameter pad in margin. Check example from docs here. Code: import plotly.offline as py import plotly.graph_objs as go labels = ['Alice','Bob','Carl'] vals = [2,5,4] data = [go.Bar(x=vals, y=labels, orientation='h')] layout = go.Layout( margin=dict( pad=20 ), title = 'hbar', ) fig = go.Figure(data=data,layout=layout) py.plot(fig, filename='horizontal-bar.html') And plot should be looks something like that:
accepted answer of: http://stackoverflow.com/q/52391451

http://stackoverflow.com/comment/91629131
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52341055
has text: Thanks @khachik I considered doing a large dictionary build but I would have a duplicate issue because there are some duplicates that wouldn't have action taken. For example, 'serial' could have multiple matches but I would only be taking action on one row that matched. If I did go this route and possibly combined column values for a unique key, would I just do a 'for row' once through to build a large dictionary and then run through once more referencing back against the large dictionary that was built? This would be two loops through rather than the large combination that it currently is.

http://stackoverflow.com/comment/91686165
has text: Please _do not_ use the edit feature to add any sort of pleading. Remember that it is volunteers who help here, and they will not be hurried by deadlines. Read the link I have offered to understand that the community feels strongly about this. In any case, such commentary will be irrelevant after your deadline, and ought to be removed for the benefit of future readers.
score: 0
comment on: http://stackoverflow.com/q/52352448
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52358290
tagged with: object
has title: python class object attribute
tagged with: class
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52358425
tagged with: python
has comment: http://stackoverflow.com/comment/91661182
has comment: http://stackoverflow.com/comment/91661269
has answer: http://stackoverflow.com/a/52358438
has comment: http://stackoverflow.com/comment/91661214
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52358641
has comment: http://stackoverflow.com/comment/91661260
has body: object-oriented programming is pretty new to me. I am just trying to learn a bit about classes and methods. I am trying to write a simple class called 'Object' and then define a few geometrical objects e.g. circle, rectangle etc. I then want to have attributes such as 'area' and 'circumference' where I would like to access the area of a circle as: class object: import numpy as np pi = np.pi def circle(self): def area(self, radius): self.area=self.radius**2 * self.pi s = object() print(s.__dict__) print(s.circle.area(5)) Upon run, I am getting: {} Traceback (most recent call last): File "/Users/aya/Desktop/test.py", line 12, in &lt;module&gt; print(s.circle.area(5)) AttributeError: 'function' object has no attribute 'area' How do I make s.circle.area(5) work?
type: Question

http://stackoverflow.com/comment/91892933
score: 0
type: AnswerComment
has text: No..actually am running as combined scripts...when i run the command separately it is working fine...but as combined scripts file it is not working..its keep on waiting for the dialog and fails to click on OKButton in success dialog..Tried click_input() too...No luck!!
type: Comment
comment on: http://stackoverflow.com/a/52406874

http://stackoverflow.com/a/52401284
answers question: http://stackoverflow.com/q/52401194
has body: work_tip = "Good code is commented code" new_string = work_tip.replace(' ', '-') print(new_string)
score: 0
type: Answer

http://stackoverflow.com/comment/91810389
comment on: http://stackoverflow.com/q/52406826
has text: For me your script code worked... Variable `u` shape is (21,65,1,10,12).
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52425455
has answer: http://stackoverflow.com/a/53222435
has comment: http://stackoverflow.com/comment/91794403
tagged with: python
type: AnsweredQuestion
tagged with: command-line
has comment: http://stackoverflow.com/comment/91823657
tagged with: warnings
has title: How to determine the module name to filter a specific Python warning?
upvote count: 10
type: Question
has comment: http://stackoverflow.com/comment/91822801
score: 10
has comment: http://stackoverflow.com/comment/91794206
has comment: http://stackoverflow.com/comment/91829321
accepted answer: http://stackoverflow.com/a/53222435
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/93584623
has comment: http://stackoverflow.com/comment/91794262
favorite count: 0
has body: With Python one can filter specific warnings using the following command line syntax: -W action:message:category:module:line But how can one determine the correct value for module for a particular warning? Consider the following example: Using (pipenv --python 3.6.5 install lxml==4.2.4) &gt; python -W error -c "from lxml import etree" Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "src/lxml/etree.pyx", line 75, in init lxml.etree File "src/lxml/_elementpath.py", line 56, in init lxml._elementpath ImportWarning: can't resolve package from __spec__ or __package__, falling back on __name__ and __path__ If one wanted to ignore only that specific import warning, how does one find the module name to use? None of the following commands appear to be correct. They all still emit the warning. python -W error -W ignore::ImportWarning:lxml -c "from lxml import etree" python -W error -W ignore::ImportWarning:lxml.etree -c "from lxml import etree" python -W error -W ignore::ImportWarning:lxml._elementpath -c "from lxml import etree" python -W error -W ignore::ImportWarning:etree -c "from lxml import etree" python -W error -W ignore::ImportWarning:_elementpath -c "from lxml import etree" python -W error -W 'ignore::ImportWarning:lxml[.*]' -c "from lxml import etree"

http://stackoverflow.com/comment/91781201
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52418106
has text: This one works, but the problem is, insert null values on author and comment, which cannot make a reference.

http://stackoverflow.com/comment/91728140
type: Comment
type: QuestionComment
score: 0
has text: You need to use `annotate` correctly. [Here](https://stackoverflow.com/questions/15148149/annotate-a-plot-using-matplotlib) is an example for you
comment on: http://stackoverflow.com/q/52391512

http://stackoverflow.com/comment/91593870
type: Comment
score: 0
has text: wouldn't this override the number after a matched position? should i increase array size then shift then add element?
type: AnswerComment
comment on: http://stackoverflow.com/a/52323242

http://stackoverflow.com/comment/94299288
score: 0
comment on: http://stackoverflow.com/a/52347571
type: AnswerComment
type: Comment
has text: Hello Patrick. How to do the same in time efficient manner. Suppose If I have large data. Injecting special character like word to #word# needs more time.

http://stackoverflow.com/q/52303121
has comment: http://stackoverflow.com/comment/91557104
has comment: http://stackoverflow.com/comment/91608108
has comment: http://stackoverflow.com/comment/91629330
downvote count: 1
has title: CSV uploading issue
has answer: http://stackoverflow.com/a/52330249
type: Question
tagged with: geocode
upvote count: 0
score: -1
answer count: 1
favorite count: 0
has body: I am uploading csv files to https://geocoding.geo.census.gov/ for batch geocoding. After some python code to parse and separate files. I have to manually save each CSV file with excel as a csv again or I get an error "Malformed input file or file not of type .CSV, .TXT, .DAT, .XLS, or .XLSX The data should be in separate columns in a CSV or Excel file. Use a comma separator for text or DAT files" . I opened with a text editor and notice one difference the comma at the end of each line. Is this an encoding issue? example Working 5028156,2700 W BETHANY HOME RD,Phoenix,AZ, Non-working file 5093590,4808 N 15TH ST,Phoenix,AZ
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/91554637
tagged with: python

http://stackoverflow.com/a/52465961
type: AcceptedAnswer
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52371766
answers question: http://stackoverflow.com/q/52371766
downvote count: 0
has body: Here's a solution in python for which I didn't use BigQuery exports. The end result is nonetheless saved in Storage, as newline delimited json files (such that can be then loaded back to BigQuery). It involves a query which might get expensive for very large tables though. I used as an example a table with one ZipCode column and two more columns (col1, col2) but this shouldn't matter. Also, I hard-coded the authentication part. #!/usr/bin/python from argparse import ArgumentParser from google.cloud import bigquery from google.cloud import storage def main(project_id, dataset_id, table_id, bucket_name): client = bigquery.Client.from_service_account_json('service_account.json',project=project_id) dataset = client.dataset(dataset_id) # Create a table for intermediate results table_ref = client.dataset(dataset_id).table('tmp') # Query job with 'tmp' as destination # Group by non grouped/aggregated field ZipCode using ARRAY_AGG job_config = bigquery.QueryJobConfig() job_config.destination = table_ref sql = 'SELECT ZipCode, ARRAY_AGG(STRUCT(col1, col2)) FROM `{}.{}.{}` GROUP BY ZipCode'.format(project_id, dataset_id, table_id) query_job = client.query( sql, location='US', job_config=job_config) query_job.result() storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) rows = client.list_rows(client.get_table(table_ref)) for row in rows: record='' # Rest of row is a list of dictionaries with unicode items for r in row[1:][0]: r = {str(k):str(v) for k,v in r.items()} record+=(str(r))+'\n' # row[0] will have ZipCode which we want to use to name the exported files filename=row[0]+'.json' blob = bucket.blob(filename) print 'Exporting to gs://{}/{}'.format(bucket_name,filename) blob.upload_from_string(record) # Delete the tmp table client.delete_table(table_ref) if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('-p','--project', help="project where the ZipCode table resides", dest='project_id') parser.add_argument('-d','--dataset…
has comment: http://stackoverflow.com/comment/91882525

http://stackoverflow.com/a/52426031
upvote count: 6
has comment: http://stackoverflow.com/comment/115609206
has comment: http://stackoverflow.com/comment/115609727
score: 6
has comment: http://stackoverflow.com/comment/115608956
accepted answer of: http://stackoverflow.com/q/52403961
has comment: http://stackoverflow.com/comment/115613097
has body: The problem was because I was using the drag_and_drop command. Drag and drop now work with both Chrome and Firefox with the following command: source_element = self.browser.find_element_by_xpath("//*[@id='transfer-tape-listing-nst" + str(drive) + "']/tbody/tr[2]") dest_element = self.browser.find_element_by_xpath("//*[@id='transfer-location-listing']/tbody/tr[2]/td[1]") time.sleep(5) try: ActionChains(self.browser).click_and_hold(source_element).move_to_element(dest_element).release(dest_element).perform() # ActionChains(self.browser).drag_and_drop(source_element, dest_element) alert = self.browser.switch_to_alert() # xpath throws an exception some times alert.accept() except: pass The browser setup and the version of the drivers are the ones I have in my question. Note that I have also swapped CSS with XPath in case this affected the selection of the elements. Hope this helps!
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52403961
has comment: http://stackoverflow.com/comment/93935040
type: Answer

http://stackoverflow.com/a/52431849
accepted answer of: http://stackoverflow.com/q/52429033
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/91810879
has body: So right now you are trying to access the request.form in a get request. However, the form will always be empty in a get request because that's the nature of a get request. So only when you access the route @app.route('/matchup-history/<string:matchup_type>' trough a post request, will it be able to redirect in the right way. This working miniapp displays it nicely: from flask import Flask, render_template_string, request app = Flask(__name__) TEMPLATE_STRING = """ {{request.form['matchup_type']}} Regular Season Playoffs """ @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'GET': return render_template_string(TEMPLATE_STRING) else: return render_template_string(TEMPLATE_STRING) The first time you open the page, you see only the radio button. But as soon as you click on a radio button, it POSTS the form, and therefore you will see the selected value on top of the page now. If you click again, you post the form again, etc. So how should you solve it? I think that there is no need to do a POST request with this form, because you're not updating any data, you're just querying. from flask import Flask, render_template_string, request app = Flask(__name__) TEMPLATE_STRING = """ {% for owner in owners %} {{owner['name']}} {% endfor %} Regular Season Playoffs Queried data goes here """ owners = [{'id': 1, 'name': 'bob'}, {'id': 2, 'name': 'gary'}, {'id': 3, 'name': 'tom'}] matchup_types = 'regular', 'playoffs' @app.route('/history', methods=['GET']) def history(): owner_id = request.args.get('owner_id', None, type=int) if owner_id not in [owner['id'] for owner in owners]: owner_id = owners[0]['id'] matchup_type = request.args.get('matchup_type', None) if matchup_type not in matchup_types: matchup_type = matchup_types[0] # now you know the owner_id and the matchup type, and know that both are valid, do some query to get table data return render_template_string(TEMPLATE_STRING, owners=owners, selected_owner_id=owner_id, selected_matchup_type=matchup_…
has comment: http://stackoverflow.com/comment/91808104
has comment: http://stackoverflow.com/comment/91812380
has comment: http://stackoverflow.com/comment/92064524
answers question: http://stackoverflow.com/q/52429033
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91809437
score: 1
has comment: http://stackoverflow.com/comment/91808637

http://stackoverflow.com/comment/91807659
has text: The nice thing about `minAreaRect()` if you can get it to work is it will give you the angle over which to find the girth at tons of points throughout the whale. To clarify my above comments, I understand what you're trying to do, but I don't know what is the best metric for you---I think you'd need to decide what constraints you want for connecting them, and then hopefully the problem becomes well-defined and then a solution can be worked out.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52411321
score: 0

http://stackoverflow.com/q/52384753
has answer: http://stackoverflow.com/a/52385131
accepted answer: http://stackoverflow.com/a/52385131
score: 0
answer count: 1
tagged with: python-3.x
tagged with: static
has title: Understanding static class variables across processes in Python
tagged with: python
has body: I was creating different daemon workers with the same class as their target using multiprocessing module. This class import different modules dynamically based on the context and storing those modules in the class scoped static dictionary. I was started thinking, due to class level static dictionary, will all the imports made by all past workers (which might be already terminated) be available/present in all future workers? So I debugged and realized that this was not happening indeed and imports by past workers were not present future worker, as desired. But started wondering why so. So I created small example imitating the same. Below are two examples. Both involve same Cmodule.py which contains the worker's target class C. The difference is just in temp.py, that too, only in argument of mup.Process(). First example fails, in the sense that member of the static dict in class C added by past worker is present in future worker. While this is not the case with second example. Cmodule.py class C: staticDict = {} def __init__(self, condition): if condition: C.staticDict['a'] = 'a' else: C.staticDict['b'] = 'b' self.printStaticDict() def printStaticDict(self): print(C.staticDict) Example 1 - temp.py import multiprocessing as mup from Cmodule import * def newProc3(): c = C(True) def newProc4(): c = C(False) newProc3Obj = mup.Process(newProc3()) newProc4Obj = mup.Process(newProc4()) newProc3Obj.start() newProc4Obj.start() Example 2 - temp.py import multiprocessing as mup from Cmodule import * def newProc3(): c = C(True) def newProc4(): c = C(False) newProc3Obj = mup.Process(target=newProc3) //this differs from example 1 newProc4Obj = mup.Process(target=newProc4) //this differs from example 1 newProc3Obj.start() newProc4Obj.start() Example 1 - output {'a': 'a'} {'a': 'a', 'b': 'b'} Example 2 - output {'a': 'a'} {'b': 'b'} Note that in example 1 output, key value 'a':'a' is retained in second worker, but that is not the case in example 2. So, what is the difference between …
type: AnsweredQuestion
tagged with: multithreading
tagged with: multiprocessing
type: Question

http://stackoverflow.com/q/52288130
score: 3
tagged with: python
has title: keywords matching of list elements with pandas column
tagged with: python-3.x
upvote count: 3
accepted answer: http://stackoverflow.com/a/52288250
answer count: 1
has comment: http://stackoverflow.com/comment/91524014
tagged with: dataframe
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/52288250
has body: I have list of elements as: A= ['loans','s-class','veyron','trump','rihana','drake','election'] I also have another pandas dataframe B with columns category and words which is comma seperated string as:- category words audi a4, a6 bugatti veyron, chiron mercedez s-class, e-class dslr canon, nikon apple iphone,macbook,ipod finance sales,loans,sales price politics trump, election, votes entertainment spiderman,thor, ironmen music beiber, rihana,drake ........ .............. ......... ......... All I want to map elements of list A with column words and assign corresponding category into a new list.So, expected output would be. matched_categories=['finance','mercedez','bugatti','politics','music','music','politics']
favorite count: 0
type: Question
tagged with: pandas

http://stackoverflow.com/q/52280027
has comment: http://stackoverflow.com/comment/91508402
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52280391
has comment: http://stackoverflow.com/comment/91508101
linked to: http://stackoverflow.com/q/5843518
has comment: http://stackoverflow.com/comment/91508460
has comment: http://stackoverflow.com/comment/91508588
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91508747
has answer: http://stackoverflow.com/a/52280458
has comment: http://stackoverflow.com/comment/91509080
has comment: http://stackoverflow.com/comment/91508545
has body: I have list of strings and I have to remove all special characters (, - ' " .). My code is import glob import re files = [] for text in glob.glob("*.txt.txt"): with open(text) as f: fileRead = [ line.lower() for line in f] files.append(fileRead) files1 = [] for item in files : files1.append(''.join(item)) I have used lot of options including "replace", "strip" and "re". when I use strip (shown below), the code runs but no changes are seen in output. files1 = [line.strip("'") for line in files1] When I use re, I get TypeError: expected string or bytes-like object. I changed to list of strings from list of lists so that I can use re. This method is stated many times but did not solve the problem for me. files1 = re.sub(r"[-()\"#/@;:&lt;&gt;{}`+=~|.!?,]", "", files1) I am not able to use replace as it throws an attribute error that replace cannot be used on lists. Please suggest me how can I get rid of all special characters.
type: Question
has title: strip or remove all special characters from list of strings in python
has answer: http://stackoverflow.com/a/52280600

http://stackoverflow.com/comment/91656817
comment on: http://stackoverflow.com/a/52355862
type: Comment
has text: You could do that. Or in the first loop you could save the `row[2]` values in a local list, just as you do with the `row[0]` values, and then refer to that list instead of reading the file again.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52297008
upvote count: 0
has answer: http://stackoverflow.com/a/52297070
favorite count: 0
accepted answer: http://stackoverflow.com/a/52297070
tagged with: python
type: AnsweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/52297256
type: Question
duplicate of: http://stackoverflow.com/q/2152898
has title: Python - find an expression in a list filled with strings
possible better answer: http://stackoverflow.com/a/52297256
score: -1
has body: I would like to find a specific entry in a list filled with strings. For example, I would like to find all the strings that contain the number ".0130." (like the 3rd line below) The file looks like this: https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/001/MYD021KM.A2018001.0140.006.2018002030901.hdf https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/001/MYD021KM.A2018001.0135.006.2018002030858.hdf https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/001/MYD021KM.A2018001.0130.006.2018002030850.hdf https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/001/MYD021KM.A2018001.0125.006.2018002030903.hdf I read the file like this: data_links = [] f=open(workdir1+"/download.txt", "r") for i in f: data_links.append(i.rstrip()) f.close() How could I look for all the entries containing the section ".0130."?
answer count: 2

http://stackoverflow.com/q/52354104
tagged with: django-queryset
answer count: 1
favorite count: 0
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52354284
score: 4
has title: Django Query set for counting records each month
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52354284
type: Question
upvote count: 4
has body: class Orders(models.Model): orderid = models.IntegerField(db_column='orderID', primary_key=True) pickupdate = models.DateField(db_column='pickupDate', blank=True, null=True) I want to display total records in the Model for each month. The solution that I have found require me to enter year Orders.objects.filter(pickupdate__year = '2006').values_list('pickupdate__month').annotate(total = Count('orderid') The results from the queryset above are like this : &lt;QuerySet [(1, 31), (2, 27), (3, 31), (4, 30), (5, 31), (6, 29), (7, 30), (8, 31), (9, 30), (10, 31), (11, 30), (12, 31)]&gt; I want that the queryset able to get the monthly range automatically from the database,without the need to put year to the queryset The data that I want to display is like this : Month | Total January 2007 | 1 February 2007| 2 etc enter code here
downvote count: 0

http://stackoverflow.com/comment/91618224
comment on: http://stackoverflow.com/q/52335455
score: 0
type: Comment
type: QuestionComment
has text: is your date is missing in a row or some values associated with the date are missing, can you clairify ?

http://stackoverflow.com/q/52343936
has answer: http://stackoverflow.com/a/52358732
type: UnansweredQuestion
tagged with: python
tagged with: tkinter
linked to: http://stackoverflow.com/q/16745507
has title: python opencv and tkinter capture webcam problem
score: 0
has body: hello everyone i have a code for read video from webcam and show it into the tkinter window with timer threading. when user click show button, app make a thread and run it every x second to show frame by frame. here's the problem : every several frame app shows first frame that captured from video source. that's weird i know but i cant find out why!!! here's my code: import tkinter as tk from tkinter import ttk from tkinter import * import threading import cv2 import PIL.Image, PIL.ImageTk from PIL import Image from PIL import ImageTk import time class App(threading.Thread): def __init__(self, root, window_title, video_source=0): self.root = root self.root.title(window_title) self.video_source = video_source self.show_switch=False self.showButton = Button(self.root, text="PlayStream",command=self.showStram,width=15, padx="2", pady="3",compound=LEFT) self.showButton.pack() # Create a canvas that can fit the above video source size self.canvas = tk.Canvas(root, width = 530, height = 397, cursor="crosshair") self.canvas.pack() self.root.mainloop() def updateShow(self): # Get a frame from the video source cap=cv2.VideoCapture(0) while True: if(cap.isOpened()): #read the frame from cap ret, frame = cap.read() if ret: #show frame in main window self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(frame)) self.canvas.create_image(0, 0, image = self.photo, anchor = tk.NW) else: break raise ValueError("Unable to open video source", video_source) if self.show_switch==False: cap.release() return False time.sleep(0.0416666666666667) #release the cap cap.release() def showStram(self): if self.show_switch: self.showButton["text"]="StartStream" # self.showButton.configure(image=self.playIcon) self.show_switch=False else: self.showButton["text"]="StopStream" self.show_switch=True # self.showButton.configure(image=self.stopIcon) self.showTimer=threading.Thread(target=self.updateShow,args=()) #self.showTimer.daemon=True self.showTimer.start() App(tk.Tk(), "Main")
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/91634690
answer count: 1

http://stackoverflow.com/comment/91721287
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52387970
type: AnswerComment
has text: please explain what happens here and what is df1 and df2 related to id only or id and url DF?

http://stackoverflow.com/comment/91738906
comment on: http://stackoverflow.com/q/52397145
score: 0
has text: It is mandatory for the HTML form to have the attribute `enctype="multipart/form-data"` set correctly. Otherwise the `request.FILES` will be empty. [From here](https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52346297
has body: I'm working on a python client that will asynchronously download vinyl cover art. My problem is that I'm new to python (especially asynchronous python) and I don't think my code is running ansychronously. I have another client written in Node.js that is able to get approx. 40 images/sec whereas this python one is only managing to get around 1.5/sec. import aiohttp import asyncio from os import path,makedirs caa_base_url = "https://coverartarchive.org/release" image_download_dir = path.realpath('images') # small,large, None = Max image_size = None async def getImageUrls(release_mbid,session): async with session.get(f'{caa_base_url}/{release_mbid}') as resp: if resp.status == 404 or resp.status == 403: return return [release_mbid,await resp.json()] async def getImage(url,session): try: async with session.get(url) as resp: return [url,await resp.read()] except (aiohttp.ServerDisconnectedError): return await getImage(url,session) async def getMBIDs(mb_page_url): async with aiohttp.ClientSession() as session: async with session.get(mb_page_url) as resp: mb_json = await resp.json() tasks = [] async with aiohttp.ClientSession() as caa_session: for release in mb_json["releases"]: task = asyncio.ensure_future(getImageUrls(release["id"],caa_session)) tasks.append(task) responses = await asyncio.gather(*tasks) async with aiohttp.ClientSession() as caa_image_session: for response in responses: if response is not None: caaTasks = [] release_mbid = response[0] result = response[1] for image in result["images"]: if image["front"] == True: caaTask = asyncio.ensure_future(getImage(image["image"],caa_session)) caaTasks.append(caaTask) image_responses = await asyncio.gather(*caaTasks) for image_response in image_responses: image_url = image_response[0] image_binary = image_response[1] new_file_dir = path.join(image_download_dir,release_mbid) if not path.isdir(new_file_dir): makedirs(new_file_dir) file_name = image_url[image_url.rfind("/")+1:] file_path = path.join(new_file_dir,file_na…
has comment: http://stackoverflow.com/comment/91638282
has title: API calls not running ansynchronously
answer count: 0
score: 1
upvote count: 1
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/91638547
has comment: http://stackoverflow.com/comment/91651610
has comment: http://stackoverflow.com/comment/91649556
has comment: http://stackoverflow.com/comment/91656459
has comment: http://stackoverflow.com/comment/91638327
favorite count: 0
tagged with: python-3.x
tagged with: python-asyncio
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52366048
has answer: http://stackoverflow.com/a/52368441
tagged with: python
upvote count: 2
downvote count: 1
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/39970703
accepted answer: http://stackoverflow.com/a/52368441
has title: Pandas filter dataframe for positive and negative values
score: 1
has body: I have a pandas dataframe with 3 columns where: Category dtype - string Date dtype - datetime Values dtype - float df = pd.DataFrame() df['category'] = ['a', 'b', 'b', 'b', 'c', 'a', 'b', 'c', 'c', 'a'] df['date'] = ['2018-01-01', '2018-01-01', '2018-01-03', '2018-01-05', '2018-01-01', '2018-01-02', '2018-01-06', '2018-01-03', '2018-01-04','2018-01-01'] df['values'] = [1, 2, -1.5, 2.3, 5, -0.7, -5.2, -5.2, 1, -1.1] df Dataframe view I want to filter for rows that have a positive value and a negative value (with the least difference) close to that date per category. So, essentially an output that looks like: df = pd.DataFrame() df['category'] = ['a', 'a','b', 'b', 'c', 'c'] df['date'] = ['2018-01-01', '2018-01-01', '2018-01-01', '2018-01-03', '2018-01-01', '2018-01-03'] df['values'] = [1, -1.1, 2, -1.5, 5, -5.2] df Filtered Dataframe I have looked at similar queries on SO (Identifying closest value in a column for each filter using Pandas, How do I find the closest values in a Pandas series to an input number?) The first one utilises idxmin, which returns first occurence, not the closest in value. The second link is speaking about a specific value as an input - I don't think a pure np.argsort works in my case. I can imagine using a complex web of if statements to do this, but, I'm not sure what the most efficient way of doing this is with pandas. Any guidance would be greatly appreciated.
type: Question
has comment: http://stackoverflow.com/comment/91679087
linked to: http://stackoverflow.com/q/30112202
answer count: 1
has comment: http://stackoverflow.com/comment/91676217
favorite count: 0
tagged with: pandas

http://stackoverflow.com/comment/91530891
score: 0
comment on: http://stackoverflow.com/q/52291170
type: Comment
type: QuestionComment
has text: @Jean-FrançoisFabre Question seems related but there is no accepted answer, and doesn't solve my use case.

http://stackoverflow.com/q/52337985
tagged with: python
has comment: http://stackoverflow.com/comment/91635466
answer count: 0
type: UnansweredQuestion
tagged with: classification
tagged with: machine-learning
has title: Retraining a MobileNet with large images
tagged with: tensorflow
upvote count: 5
has comment: http://stackoverflow.com/comment/91623876
type: Question
has comment: http://stackoverflow.com/comment/91638433
score: 5
downvote count: 0
has body: I'm trying to retrain the Tensorflow for Poets MobileNets tutorial with my own images (800x600px, colour so I think x3) and I think the issue is that I'm using images that are too big. I've gotten to this page in the tutorial https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/#7 and everything has worked fine, but once I put my new image path and image size in, it gives me this error: ERROR:tensorflow:The Mobilenet input size should be '224', '192', '160', or '128', but found '480000' for architecture 'mobilenet_0.50_480000' ERROR:tensorflow:Did not recognize architecture flag The tutorial says Input image resolution: 128,160,192, or 224px. Unsurprisingly, feeding in a higher resolution image takes more processing time, but results in better classification accuracy. The relative size of the model as a fraction of the largest MobileNet: 1.0, 0.75, 0.50, or 0.25. And you are supposed to enter that information with this code: IMAGE_SIZE=224 ARCHITECTURE="mobilenet_0.50_${IMAGE_SIZE}" Is this a limit of the mobilenet? Can it not do bigger images? One other possibility is that my images are all pngs and the tutorial is all jpegs, but I don't see anywhere to specify filetype. Any suggestions would be most appreciated
favorite count: 0

http://stackoverflow.com/comment/91594194
score: 0
has text: Are these two lines one whole string? Two string elements in a list?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52323388

http://stackoverflow.com/a/52287293
score: 0
answers question: http://stackoverflow.com/q/52287067
has body: You could use recursion to delete keys from the nested dictionaries. Below is a working example. import json def update_dict(original_dict, keys): return_dict = original_dict.copy() for k in keys: if isinstance(k, dict): _key = list(k.keys())[0] return_dict[_key] = update_dict(original_dict[_key], k.values()) else: try: del return_dict[k] except KeyError: pass return return_dict def equal_dicts(d1, d2, ignore_keys=()): d1_, d2_ = update_dict(d1, ignore_keys), update_dict(d2, ignore_keys) return json.dumps(d1_, sort_keys=True) == json.dumps(d2_, sort_keys=True) data1 = { "A": "123456789", "B": { "firstElement": "abc", "lastElement": "def" }, "C": { "firstElement": "chi", "lastElement": "abc" } } data2 = { "A": "78901234", "B": { "firstElement": "abc", "lastElement": "def" }, "C": { "firstElement": "chi", "lastElement": "jul" } } print(equal_dicts(data1, data2, ('A', 'dateTime', 'trxId', {'C':'lastElement'}))) I'm not sure if this meets your requirements, but you can now pass in a dictionary. It will only delete the keys in that dictionary from the expected parent.
type: Answer
has comment: http://stackoverflow.com/comment/91522414
has comment: http://stackoverflow.com/comment/91522695

http://stackoverflow.com/q/52331032
has comment: http://stackoverflow.com/comment/91608977
accepted answer: http://stackoverflow.com/a/52331292
score: 4
has comment: http://stackoverflow.com/comment/91609032
has answer: http://stackoverflow.com/a/52331437
upvote count: 4
tagged with: python-2.7
downvote count: 0
has answer: http://stackoverflow.com/a/52331292
has comment: http://stackoverflow.com/comment/91609046
favorite count: 0
has body: I have this list: myList = [a, a, a, b, b, a, c, c, b, a] I want to count the inflow and the outflow for every unique item. Inflow for 'a' = number of appearances = 5 (when a transition ENTERS in 'a') Outflow for 'a' = number of different characters after 'a' = 2 (when a transition EXITS from 'a' to another character) For inflow I have this and it works: myListDict = {} for item in myList: myListDict.setdefault(item, 0) myListDict[item] += 1 But I don't really know how to do this in a fast and elegant way for the outflow, on a single overall iteration, if possible.
possible better answer: http://stackoverflow.com/a/52331423
answer count: 3
has comment: http://stackoverflow.com/comment/91609113
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52331423
type: Question
has title: How to get inflow/outflow for every item from a list?

http://stackoverflow.com/comment/91709562
score: 0
comment on: http://stackoverflow.com/q/52381875
type: QuestionComment
type: Comment
has text: I think you might be right , I just added the minimal code

http://stackoverflow.com/comment/129355829
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52320145
has text: I think there are open issues in GitHub regarding this https://github.com/numpy/numpy/issues/834 and https://github.com/numpy/numpy/issues/835

http://stackoverflow.com/q/52405726
favorite count: 0
has answer: http://stackoverflow.com/a/52420352
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91756314
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91755658
has comment: http://stackoverflow.com/comment/91779214
has comment: http://stackoverflow.com/comment/91755279
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91779189
has body: I've got a pandas data frame. In every cell there is a dict: id | A | B | ... 1 | {"a": 1, "b":1} |{"d": 1, "e":1} | ... 2 | {"a": 2, "b":3} |{"d": 5, "e":6} | ... ... 10 | {"a": 1, "b":1} |{"d": 1, "e":3} | ... I'd like to update one cell (e.i 1,A ): df.loc[1,"A"].update({"c":2}) This procedure updates every single cell which has the same dict, so in this case there would be (1,A and 10,A would be changed): id | A 1 | {"a": 1, "b":1, "c":2} 2 | {"a": 2, "b":3} ... 10 | {"a": 1, "b":1, "c":2} How can I force python to update only 1,A? This is how I create data frame: df = pd.read_csv( file_path, sep='\t', names=['id', 'A'], compression='gzip', converters={1:ast.literal_eval})
has comment: http://stackoverflow.com/comment/91755478
type: Question
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91755212
has comment: http://stackoverflow.com/comment/91780287
has comment: http://stackoverflow.com/comment/91779207
tagged with: python-2.7
tagged with: pandas
has comment: http://stackoverflow.com/comment/91755894
upvote count: 1
has comment: http://stackoverflow.com/comment/91820696
has title: Modify dict in dataframe cell
answer count: 1
has comment: http://stackoverflow.com/comment/91758355

http://stackoverflow.com/comment/91695481
has text: This should work https://pastebin.com/6f1j5Ybn . Let me know if it's ok. Thanks. I noticed that it may be related to ties resolution in the ranks.. maybe your code give different tie values? Since the data is very sparse and I expect a lot of ties.
comment on: http://stackoverflow.com/a/52373253
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52344812
answer count: 1
has answer: http://stackoverflow.com/a/52344991
tagged with: python
has title: How do i use getopt.getopt method in python?
type: AnsweredQuestion
type: Question
has body: I would like to add warning and critical alert condition if inputfile == "android": pass then check the number stored in variable e and f and check whether it is under normal or warning or critical level as whatever the arguments we passed. Secondly this script gives no output when run in python3.6 #!/usr/bin/python import requests, os, json, sys, getopt f = 10 e = 20 def main(argv): inputfile = '' try: opts, args = getopt.getopt(argv,"hi:o:w:c:",["ent","lable","help","warning","critical"]) except getopt.GetoptError: print ("Usage: test.py -i <inputfile>") sys.exit(2) for opt, arg in opts: if opt == '-h': print ("test.py -i <inputfile>") sys.exit() # elif opt in ("-i", "--app"): elif opt == '-i': inputfile = arg if inputfile == "android": '''call a function here (hiding sensitive information) Using e and f variable instead''' print ("Input is"), inputfile print("Active:"), f else: print("Parameter not found") sys.exit(2) # elif opt in ("-o", "--lable"): elif opt == '-o': inputfile = arg print("Active:"), e if __name__ == "__main__": main(sys.argv[1:]) Right Now: #python script -i android Output Active: 10 Expected: #python script -i android -w 5 -c 20 Output WARNING - Active: 10
accepted answer: http://stackoverflow.com/a/52344991
score: 0

http://stackoverflow.com/a/52386386
score: 3
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91852787
accepted answer of: http://stackoverflow.com/q/52384940
upvote count: 3
answers question: http://stackoverflow.com/q/52384940
type: Answer
has body: Have you seen the Multi-index feature in xarray? It may not be exactly what you are looking for and there are some limitations (e.g. serialisation to netCDF is not yet supported as far as i know), but maybe that is okay for you. The idea is to turn measurement_number into a pandas multiindex with latitude and longitude as virtual coordinates. You can then use .sel on multiindex coordinates aswell -> Multi-level indexing

http://stackoverflow.com/q/52374725
upvote count: 5
tagged with: python
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/91694352
has answer: http://stackoverflow.com/a/52375407
accepted answer: http://stackoverflow.com/a/52375407
score: 4
tagged with: flask
has comment: http://stackoverflow.com/comment/91694736
has title: How to break out of an infinite loop with flask and python using http?
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
has body: I would like to break out of an infinite loop using flask and a http get. from flask import Flask, render_template, jsonify from serialtest import get_dist app = Flask(__name__) def test(): while True: print('keep going!') @app.route('/start') def start(): return test() @app.route('/stop') def stop(): # stop the function test return 'stopped' if __name__ == "__main__": app.run(host='0.0.0.0', port=5000, debug=True, threaded=True) I want to use Flask as a http server and serve a web client that can start test() with a click event and http get, then stop test() with a different click event.

http://stackoverflow.com/q/52410626
type: Question
has title: Multiprocessing backed parallel loops cannot be nested below threads, setting n_jobs=1
tagged with: plotly-dash
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/27646052
tagged with: scikit-learn
favorite count: 0
tagged with: python
has body: I have developed a Python script that basically reads an excel file and trains a model using sklearns GridSearchCV, using the n_jobs statement: def create_table(): my_model = GridSearchCV(GradientBoostingRegressor(), tuned_parameters, cv=5, scoring='neg_mean_absolute_error', n_jobs=7) my_model.fit(x_data, y_data) return(my_model.predict(new_x_data)) This perfectly works when executing it. But now I am trying to execute it from a button click in a Dash app Multiprocessing backed parallel loops cannot be nested below threads, setting n_jobs=1 My Dash app is like this: def generate_html_table(dataframe, max_rows=50): return html.Table( # Header [html.Tr([html.Th(col) for col in dataframe.columns])] + # Body [html.Tr( [html.Td(dataframe.index[i])] + [html.Td(dataframe.iloc[i][col]) for col in dataframe.columns]) for i in range(min(len(dataframe), max_rows))] ) app = dash.Dash() app.layout = html.Div([ html.H1(children='Region Forecast', style={'textAlign': 'center'} ), html.Button(id='submit-button', n_clicks=0, children='Submit', style={ 'margin': 'auto', 'display': 'block' }), html.Table(id='output-table', children = generate_html_table(pd.DataFrame())) ]) @app.callback(Output('output-table', 'children'), [Input('submit-button', 'n_clicks')]) def reactive_compute(n_clicks): print('inside reactive compute') my_table = create_my_table() return(generate_html_table(my_table)) if __name__ == '__main__': app.run_server(debug=True) I've seen this question, but it doesn't help me because I do not handle the multiprocessing myself (it's the scikitlearn function): Multiprocessing backed parallel loops cannot be nested below threads The app would have to work only on local, I am not planning to put it on a web server. Can I keep the parallel model fitting from the Dash app and if it is possible, how should I best approach this ?
type: UnansweredQuestion
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/52779925

http://stackoverflow.com/comment/91662956
type: QuestionComment
has text: Re: trendiness -- basically, some of the models for being "more parallel" can, especially if poorly implemented (and historically, they often *were* poorly implemented), have much more overhead than the async approach. Switching between threads involves context-switching from userspace to kernelspace; jumping between two different call-stack contexts in a single process is much lower overhead than switching threads.
score: 0
comment on: http://stackoverflow.com/q/52356645
type: Comment

http://stackoverflow.com/comment/91572950
type: Comment
score: 2
comment on: http://stackoverflow.com/q/52312950
has text: What's desired output, btw, i don't fully understand the question
type: QuestionComment

http://stackoverflow.com/comment/91574263
type: Comment
comment on: http://stackoverflow.com/a/52313371
score: 0
type: AnswerComment
has text: mse_c 0.00010744558385406445 mse_cv 0.0001440547449662863

http://stackoverflow.com/comment/91766489
type: Comment
comment on: http://stackoverflow.com/q/52410714
score: 0
type: QuestionComment
has text: Can you please edit in the full traceback for that?

http://stackoverflow.com/a/52305060
score: 2
has comment: http://stackoverflow.com/comment/91573898
has body: This uses the reverse foreign key relation (&lt;model&gt;_set) that is implicitly added to all models with foreign keys to build up your data in a dictionary. data = {"countries": []} for country in Country.objects.all(): country_data = {"country": country, "states": []} for state in country.state_set.all(): state_data = {"state": state, "cities": []} for city in state.city_set.all(): city_data = {"city": city, "projects": []} for project in city.project_set.all(): city_data["projects"].append(project) state_data["cities"].append(city_data) country_data["states"].append(state_data) data["countries"].append(country_data) Which should return a dictionary roughly like the following: { "countries": [ { "country": &lt;Country object&gt;, "states": [ { "state": &lt;State object&gt;, "cities": [ { "city": &lt;City object&gt;, "projects": [ &lt;Project object&gt;, ] } ] } ] } ] }
has comment: http://stackoverflow.com/comment/91573746
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52304983
answers question: http://stackoverflow.com/q/52304983
upvote count: 2
type: Answer

http://stackoverflow.com/comment/91495353
type: Comment
comment on: http://stackoverflow.com/a/52273511
score: 1
type: AnswerComment
has text: thanks, it worked, if someone gets the same issue, don't forget to switch to a ModelForm form, else the CreateForm won't be able to be saved from the view !

http://stackoverflow.com/a/52360884
type: Answer
answers question: http://stackoverflow.com/q/52360674
has body: you can do it inside the init method itself then change the perform_move method, try this class LightsOutPuzzle(object): def __init__(self, board): self.board = board board = [not i for i in board] print(board) def get_board(self): return self.board def perform_move(self, row, col): self.board[row][col] = not self.board[row][col] print(self.board) return LightsOutPuzzle(self.board) def main(): LightsOutPuzzle([False, False, False]) if __name__ == '__main__': main()
score: 0

http://stackoverflow.com/comment/91918762
comment on: http://stackoverflow.com/q/52342124
score: 0
type: Comment
type: QuestionComment
has text: Sorry about late reply. It only shows the last table. What I want is to create a visual and to display it one after another. Kinda like multiple print() statement but for visuals.

http://stackoverflow.com/q/52312857
downvote count: 0
has answer: http://stackoverflow.com/a/52465218
favorite count: 0
has title: MITMProxy how to remove flows so they do not show up in MITMWeb
has body: I'd like to use MITMProxy Python scripting to remove flows that i find useless from the web interface. Lets say i kill a flow def request(flow): if("ads" in flow.request.url): flow.kill() But also i would like killed connections to not show up in my MITMWeb interface. An example can be found here: https://i.sstatic.net/F1YWL.jpg I am unable to find a way programatically to delete the requests from the list. I would only like to see the connections that make it through. Any ideas?
tagged with: mitmproxy
tagged with: python
tagged with: ads
has answer: http://stackoverflow.com/a/69185214
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91572676
has comment: http://stackoverflow.com/comment/91572726
answer count: 2

http://stackoverflow.com/a/52347709
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/91641315
has comment: http://stackoverflow.com/comment/91645608
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52346525
type: Answer
accepted answer of: http://stackoverflow.com/q/52346525
has body: you can display your notebook from https://nbviewer.jupyter.org/ and host your notebook on https://gist.github.com/. In some cases I found that my notebook wouldn't quite render on gist but for the most part github should render your notebook for you. I use nbviewer as a backup for whenever github refuses to render the notebook; just copy the link of your gist into nbviewer and it should do the rest for you. example: https://gist.github.com/pollend/7ab5bd156b15473be4421821e26cc469

http://stackoverflow.com/comment/91568274
has text: It sounds like something is trying to query the role table while the modules are loading (e.g. `Role.objects.all()`), but we can't tell where the problem is from the code you posted. Please include the full traceback in your question.
score: 1
comment on: http://stackoverflow.com/q/52310586
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91584165
type: Comment
has text: `exec(f.read(), safe_dict, safe_dict)` will make it work and you can find the explanation in [this post](https://stackoverflow.com/questions/2904274/globals-and-locals-in-python-exec)
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52317544

http://stackoverflow.com/a/52304776
has body: Apologies my I missed this in my initial search. Read response AT command with pySerial Serial response is displayed with: response = ser.read(2) Also with the code phone.write(bytes([26])) I was able to send an SMS from within IDLE but it wouldn't send anything from the command prompt. To fix this I had to change it to phone.write('\x1A')
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52285680

http://stackoverflow.com/q/52304452
has comment: http://stackoverflow.com/comment/91556446
has title: Let's encrypt Failed authorization procedure
score: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
has body: I'm using Debian 9 and NGINX to deploy my app Django. When I type: sudo certbot --nginx -d example.com -d www.example.com I get the next error: Failed authorization procedure. example.com (http-01): urn:acme:error:tls :: The server experienced a TLS error during domain verification :: Fetching https://example.com/.well-known/acme- challenge/H9WJVzPYJ93jewGJjkUFFKQJBJ8-YT7t9z-Sw_PQQUg: remote error: tls: internal error IMPORTANT NOTES: - The following errors were reported by the server: Domain: example.com Type: tls Detail: Fetching https://example.com/.well-known/acme- challenge/H9WJVzPYJ93jewGJjkUFFKQJBJ8-YT7t9z-Sw_PQQUg: remote error: tls: internal error To fix these errors, please make sure that your domain name was entered correctly and the DNS A/AAAA record(s) for that domain contain(s) the right IP address. Additionally, please check that you have an up-to-date TLS configuration that allows the server to communicate with the Certbot client. I do not know what I'm doing wrong...
type: Question
has comment: http://stackoverflow.com/comment/91556463
tagged with: nginx

http://stackoverflow.com/q/52411234
favorite count: 0
has comment: http://stackoverflow.com/comment/91766192
upvote count: 2
tagged with: shallow-copy
has body: I found lots of discussions related to "shallow copy" in Python, but I cannot find my exact issue. As per my understanding, creating a shallow copy still contains references to the original values of the list. This holds true in following case of a two-dimensional list. &gt;&gt;&gt; x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] &gt;&gt;&gt; y = list(x) &gt;&gt;&gt; x.append(['New value']) &gt;&gt;&gt; x [[1, 2, 3], [4, 5, 6], [7, 8, 9], ['New value']] &gt;&gt;&gt; y [[1, 2, 3], [4, 5, 6], [7, 8, 9]] &gt;&gt;&gt; x[0][0] = 'A' &gt;&gt;&gt; x [['A', 2, 3], [4, 5, 6], [7, 8, 9], ['New value']] &gt;&gt;&gt; y [['A', 2, 3], [4, 5, 6], [7, 8, 9]] Now, in one-dimensional list, I didn't find this effect. &gt;&gt;&gt; a = [1,2,3,4,5] &gt;&gt;&gt; b = list(a) &gt;&gt;&gt; a.append(10) &gt;&gt;&gt; a [1, 2, 3, 4, 5, 10] &gt;&gt;&gt; b &gt;&gt;&gt; [1, 2, 3, 4, 5] &gt;&gt;&gt; a[0] = 'A' &gt;&gt;&gt; a ['A', 2, 3, 4, 5, 10] &gt;&gt;&gt; b [1, 2, 3, 4, 5] Can anyone please clarify what is behind this difference?
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: list
has answer: http://stackoverflow.com/a/52411287
has title: Shallow copy in 1-D list vs 2-D list
has comment: http://stackoverflow.com/comment/91766160
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/52411292
has comment: http://stackoverflow.com/comment/91766751
answer count: 3
has comment: http://stackoverflow.com/comment/91770092
accepted answer: http://stackoverflow.com/a/52411292
possible better answer: http://stackoverflow.com/a/52411356
has answer: http://stackoverflow.com/a/52411356

http://stackoverflow.com/comment/91802183
comment on: http://stackoverflow.com/q/52429229
score: 0
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/14852821/aligning-rotated-xticklabels-with-their-respective-xticks/14854007#14854007 https://matplotlib.org/gallery/ticks_and_spines/ticklabels_rotation.html

http://stackoverflow.com/comment/91613569
score: 0
has text: It works well! My problem is that the array has a dtype of unint32 in the beginning and it is really large (6GB). When the relabeling is done I want to save it as 8bit or 16bit depending how many different unique numbers are in the array. The OrdererdDict causes a memory error. So is there a way to reduce the memory consuption?
type: Comment
comment on: http://stackoverflow.com/a/52328755
type: AnswerComment

http://stackoverflow.com/a/52388793
score: 1
answers question: http://stackoverflow.com/q/52388039
accepted answer of: http://stackoverflow.com/q/52388039
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91722801
type: Answer
has body: Can you import httplib, it must resolve the issue
upvote count: 1

http://stackoverflow.com/comment/91724846
score: 0
type: Comment
has text: Thank you. The problem with the for loop is that I have a 3D array of varying lambdas that I am drawing from. Lets say that matrix is a 4 x 4 x 1000. If I want to sample that voxel 10e3 times, that is very time consuming with a for loop. Id rather just pull a 1 x 1 x 1000 vector, squeeze it, and, in one function call, sample it 10e3 times. Then run the four loop 15 more times (for the 4 x 4).
type: AnswerComment
comment on: http://stackoverflow.com/a/52369038

http://stackoverflow.com/comment/91713982
score: 1
has text: move `url(r'^$', blog, name='cover'),` below `url('diaoibou/', blog, name='blog'),`
comment on: http://stackoverflow.com/q/52384416
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52404673
answers question: http://stackoverflow.com/q/52404464
has body: This worked: pip install --user --ignore-installed pandas
score: 0
has comment: http://stackoverflow.com/comment/91753360
type: Answer

http://stackoverflow.com/q/52318088
tagged with: python
has comment: http://stackoverflow.com/comment/91687560
tagged with: cmake
has comment: http://stackoverflow.com/comment/91687620
score: 2
has title: How to get Python module install directory in CMake?
has comment: http://stackoverflow.com/comment/91687280
has comment: http://stackoverflow.com/comment/91688071
has body: I have created a small Python module using C++ and Boost, built with CMake. Now I need to install it into standard python modules directory, however it needs to be a path inside CMAKE_INSTALL_PREFIX, so it can be packaged with standard Debian packaging system. Now I have this, where the last line is obviously wrong, as it is an absolute path to a system directory. cmake_minimum_required(VERSION 3.12) project(foo) # Not Shown: Extract ${PYTHON_VERSION} from interpreter find_package(Python ${PYTHON_VERSION} REQUIRED COMPONENTS Interpreter Development) find_package(Boost 1.55.0 REQUIRED COMPONENTS system python${Python_VERSION_MAJOR}${Python_VERSION_MINOR}) Python_add_library(foo MODULE src/foo.cc src/python_interface.cc ) set_target_properties(foo PROPERTIES PREFIX "") target_link_libraries(foo PUBLIC Boost::python${Python_VERSION_MAJOR}${Python_VERSION_MINOR} ) # This is wrong install(TARGETS foo DESTINATION ${Python_SITEARCH}/foo) I also had a look at Python's distutils and setuptools, however they don't seem suited to standalone use.
type: Question
has comment: http://stackoverflow.com/comment/91687217
has comment: http://stackoverflow.com/comment/91718132
has comment: http://stackoverflow.com/comment/91715895
downvote count: 0
has comment: http://stackoverflow.com/comment/91687591
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91687998

http://stackoverflow.com/comment/91695083
has text: Consider concatenation and resample in a loop
score: 0
comment on: http://stackoverflow.com/q/52374591
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52357960
type: Answer
has body: I have tried to create a python 2 / 3 answer. python 2 input interprets your input, converting to integers if possible for instance. So you cannot have an integer AND a string. When entering quit, since quit isn't known by the interpreter, you get a NameError The only way to make it work would be to type "quit". But that'd be python 2 only still... Let's try to make it portable now. python 3 fails when comparing strings to numbers, because input returns strings. You'll have a hard time creating a code which works for both versions. I'd suggest this: import random # detect/create a portable raw_input for python 2/3 try: raw_input except NameError: raw_input = input while True: ROLL=raw_input("What sided Die would you like to roll(You may enter quit to close)? ") if ROLL.isdigit(): ROLL = int(ROLL) if ROLL in [6,8,10,12,20]: print(random.randint(1, ROLL)) elif ROLL == "quit": break else: print("That's not an option please choose a die...") The first try/except block is there for python 2/3 compatibility. If raw_input exists, use it, else define it as input for python 3. From now on, raw_input is used, and returns strings not integers. Now we have to add this: if ROLL.isdigit() tests if the string could be converted as an integer. If it's possible, it converts it. Now we test if the reply is contained in the choice list, and if it is, we use ROLL for our random (avoids the ton of elif statements). The loop has been turned to inconditional too, no need to initialize ROLL at start. Just break if quit is entered.
has comment: http://stackoverflow.com/comment/91660472
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52357901
upvote count: 1
has comment: http://stackoverflow.com/comment/91660544
has comment: http://stackoverflow.com/comment/91660492

http://stackoverflow.com/a/52407714
type: Answer
has body: The fact that the text file is in the same directory as your program does not make that directory the current working directory. Put the full path to the file in your open() call.
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91759456
has comment: http://stackoverflow.com/comment/91759672
has comment: http://stackoverflow.com/comment/91759045
upvote count: 2
answers question: http://stackoverflow.com/q/52407669

http://stackoverflow.com/comment/91569938
score: 1
type: AnswerComment
has text: I tried the debug=3 and I get : ReadError: bad checksum I know the tar is not corrupted. However I tried another compressed single file and same error occurs. I tried also a new virtualenv (python2.7) same problem. I can confirm I can uncompress the file manually
comment on: http://stackoverflow.com/a/52301509
type: Comment

http://stackoverflow.com/a/52352506
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/91650094
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52352482
upvote count: 2
answers question: http://stackoverflow.com/q/52352482
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91650053
has body: If you know what you are comparing it against you could do list = [] list.append("dog" if returner() == "dog" else "got cat in the bag") otherwise you will have to do list = [] r = returner() list.append(r if r == 'dog' else 'got the cat in the bag') in either case, you can actually make your code even more compact by changing these two lines list = [] list.append("dog" if returner() == "dog" else "got cat in the bag") into list = ["dog" if returner() == "dog" else "got cat in the bag"]

http://stackoverflow.com/comment/91720812
score: 0
type: Comment
type: QuestionComment
has text: @MartinR Updated to make it more clear with expected output and a proper string in Swift
comment on: http://stackoverflow.com/q/52387450

http://stackoverflow.com/comment/91662436
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52358882
type: Comment
has text: @vash_the_stampede: It's not my solution. I just answered what OP wanted. read my above comment. Clearly, he/she is a beginner and I thought of guiding him/her through the mistakes rather than providing one-liners

http://stackoverflow.com/comment/91742266
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/52398066
has text: use `python manage.py shell` to open interactive shell, and inspect the `User` class with `dir(User)`. check if the `User` class is pointing to your `User` model class or not.
type: Comment

http://stackoverflow.com/q/52409774
has comment: http://stackoverflow.com/comment/91764869
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/91763266
has comment: http://stackoverflow.com/comment/91763292
type: Question
has comment: http://stackoverflow.com/comment/91763219
score: 3
upvote count: 5
answer count: 3
has answer: http://stackoverflow.com/a/66786555
has title: override print method in current class python3
linked to: http://stackoverflow.com/q/1218933
favorite count: 0
linked to: http://stackoverflow.com/q/4675728
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91763391
has body: Not sure how I would accomplish overriding the print('something') function do do something else in the class I am in. For example, I have the following code: import app from app.helper import ws_send class TemplateSubJob: def __init__(self, sessiondata, sid, payload): self.session = sessiondata self.sid = sid self.payload = payload def startme(self): ws_send(self.sid, self.payload, 'Send some output to the user...') ws_send(self.sid, self.payload, 'Send something else to the user...') print('test') return b'xlsx_bytes_output' I want to override the function print('something') to take what is passed and do something with it. In my case I want to create a print function that does what ws_send() is doing, except only take a string. Something like the following: def print(string): ws_send(self.sid, self.payload, string) print('now i am being sent through ws_send instead of stdout') How can I accomplish this? UPDATE: The reasoning for this is so anyone who is adding code to mine, does not need to modify their code or script to use my functions. I can hijack the print function that they are already using.
has answer: http://stackoverflow.com/a/59286548
tagged with: python
has answer: http://stackoverflow.com/a/52409845

http://stackoverflow.com/a/52315372
score: 2
answers question: http://stackoverflow.com/q/52311576
has comment: http://stackoverflow.com/comment/91593957
type: AcceptedAnswer
downvote count: 0
has body: In the case of the QGraphicsXXXItem it is not necessary to overwrite any method to enable the movement, it is enough to enable the flag QGraphicsItem::ItemIsMovable. import sys from PySide2 import QtGui, QtWidgets, QtCore class SimpleItem(QtWidgets.QGraphicsItem): def __init__(self): QtWidgets.QGraphicsItem.__init__(self) self.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True) def boundingRect(self): penWidth = 1.0 return QtCore.QRectF(-10 - penWidth / 2, -10 - penWidth / 2, 20 + penWidth, 20 + penWidth) def paint(self, painter, option, widget): rect = self.boundingRect() painter.drawRect(rect) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) scene = QtWidgets.QGraphicsScene() item = SimpleItem() scene.addItem(item) view = QtWidgets.QGraphicsView(scene) view.show() sys.exit(app.exec_())
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52311576
type: Answer
has comment: http://stackoverflow.com/comment/91602154

http://stackoverflow.com/a/52410033
has comment: http://stackoverflow.com/comment/91807479
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52408958
type: AcceptedAnswer
type: Answer
upvote count: 1
has body: First I expand the dataframe by semicolon, then use melt function to create expected output. df1= pd.concat([df, df['Application'].str.split(';', expand=True)], axis=1) df1.melt(['Machine','Vulnerability'], value_name='a').drop('variable', 1) # Machine Vulnerability a # 0 1 vuln1 App1 # 1 1 vuln2 App1 # 2 1 vuln3 App1 # 3 1 vuln1 App2 # 4 1 vuln2 App2 # 5 1 vuln3 App2 # 6 1 vuln1 App3 # 7 1 vuln2 App3 # 8 1 vuln3 App3
score: 1
answers question: http://stackoverflow.com/q/52408958

http://stackoverflow.com/comment/91653012
type: QuestionComment
has text: Did you search for it on SO?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52354178

http://stackoverflow.com/q/52294172
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/52294734
score: 0
has title: How to grep a column and add it in dictionary key as value
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52294889
type: UnansweredQuestion
has body: I have been working in excel and i am trying to fetch a dictionary with keys and values .This is my table: int1 int2 int3 int4 int5 core_6 2 22 32 core_8 23.34.34.45 72.20.20.20 11 33 core_7 core_work 255.255.255.0 12 12 core_12 44 I am trying to make as: {'int1' : 'core_6' '72.20.20.20' ,'255.255.255.0' 'int2': and so on}. The issue i am facing with my code is: import xlrd workbook = xlrd.open_workbook('input.xlsx') workbook = xlrd.open_workbook('input.xlsx', on_demand = True) worksheet = workbook.sheet_by_name("GlobalInfo") my_dict = {} for i in range(2): row = worksheet.row_values(i) my_dict[row[1]] = row[1::] d =dict((k, v) for k,v in my_dict.items() if k is not None and k != '') for x in d: print(d[x]) my_di = {k: '' for k in d[x]} print(my_di) ////take all the int1 as keys worksheet.cell_value(0, 1) num_rows = worksheet.nrows - 1 curr_row = 1 kk = [] while curr_row &lt; num_rows: curr_row += 1 row = worksheet.row(curr_row) kk.append(row[1].value) print(kk) ///this will print value of 1st row But i am not able to add values to the keys i have made. Also i am not able to get values of other rows.
has comment: http://stackoverflow.com/comment/91537035
has comment: http://stackoverflow.com/comment/91536177
type: Question

http://stackoverflow.com/q/52428769
accepted answer: http://stackoverflow.com/a/52429292
tagged with: timezone
tagged with: datetime
tagged with: python
type: AnsweredQuestion
score: 1
has title: Change joined_at timezone discord.py
upvote count: 1
type: Question
tagged with: discord.py
has body: I've tried many methods involving pytz to change the timezone of the discord.py user.joined_at time. It's in UTC and I need it to be in EST. What I did was eastern = timezone('US/Eastern') eastern.zone fmt='%#c jointime=eastern.localize(datetime(user.joined_at)) createtime=eastern.localize(datetime(user.created_at)) embed=discord.Embed(title='User Information:', color=0x0000ff) embed.set_author(name='{0.name}'.format(user),icon_url='{0.avatar_url}'.format(user)) embed.add_field(name='Join Date:', value='{0.name} joined on'.format(user)+jointime.strftime(fmt)) embed.add_field(name='Account Creation:', value='{0.name}\'s account was created on '.format(user)+createtime.strftime(fmt))
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52429292
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/13866926

http://stackoverflow.com/q/52383473
has answer: http://stackoverflow.com/a/52383551
tagged with: python
accepted answer: http://stackoverflow.com/a/52383898
has comment: http://stackoverflow.com/comment/91711210
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91711087
type: Question
has comment: http://stackoverflow.com/comment/91711361
has answer: http://stackoverflow.com/a/52383589
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52383898
answer count: 3
tagged with: pandas
score: 3
has title: Can't get index position from list of Dataframes
has body: I'm trying to get the position of a dataframe from a list of dataframes, by using the built-in method index in python. My code is below: df1 = pd.DataFrame([1, 2, 3]) df2 = pd.DataFrame([4, 5, 6]) df3 = pd.DataFrame([7, 8, 9]) dfs = [df1, df2, df3] for df in dfs: print(dfs.index(df)) Where instead of getting the expected 0, 1 and 2, it only returns 0, followed by ValueError: ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I know this error typically comes from data frames comparison, and I've tried adding the .all() but to no avail. If I change the list to something like a list of strings, ints or a mix of them, no problem whatsoever. I've tried searching around but found nothing on this specific error. I know I can easily add an extra variable that keeps on adding 1 for each iteration of the list, but I'd really like to understand what I'm doing wrong.
possible better answer: http://stackoverflow.com/a/52383551
upvote count: 3

http://stackoverflow.com/q/52307575
tagged with: python
tagged with: list
answer count: 0
has comment: http://stackoverflow.com/comment/91562453
has comment: http://stackoverflow.com/comment/91581619
has comment: http://stackoverflow.com/comment/91582946
type: Question
has comment: http://stackoverflow.com/comment/91581676
has comment: http://stackoverflow.com/comment/91562441
score: 0
has body: The question title may be hard to understand. But let's assume that I have a 2D 8x8 list called chessboard: chessboard = [[0 for x in range(n)]for y in range(n)] And I have a function which adds a knight piece to the specific index. def add_white_knight(chessboard, a, b): chessboard[a][b] = 1 return chessboard And I have function called attack_configuration which only checks if a specific board configuration satisfies some specific rules. So, what I want to do is, before adding a piece to my board, check if it satisfies the required configuration. My attempt was to do if(attack_configuration(add_black_knight(chessboard, i, j))): chessboard = add_black_knight(chessboard, i, j) But I realized that this fails because the chessboard already gets edited inside the if statement. What could be a practical solution to this tiny issue? Thanks.
has title: Do 2D lists get edited when you call a modifying function inside an if logic statement?
has comment: http://stackoverflow.com/comment/91581725
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91562541

http://stackoverflow.com/a/68170732
has body: I tried the solution above but for some reason keyDown('shift') didnt work. I used the solution in this thread: keyDown function not working with shift key pyautogui.keyDown('shiftleft') pyautogui.keyDown('shiftright') pyautogui.hotkey('right','right','ctrl','up') pyautogui.keyUp('shiftleft') pyautogui.keyUp('shiftright')
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52321602

http://stackoverflow.com/q/52392637
tagged with: tkinter
type: Question
score: 0
has title: Overcoming slow button and frame display and patchy backgrounds for a custom ButtonFrame during frame resizing.
answer count: 1
has body: I have written an algorithm that allows a ttk.Frame to wrap multiple buttons within it such that when the buttons take up too much space horizontally the affected buttons will automatically be relocated to a subsequent row. Such button wrapping behaviour will also be exhibited when this ttk.Frame resizes. I have called this a FrameButton class. This widget has issues still: It's button wrapping behavior and the resizing of the frame is very laggy/delayed. Faster response is needed. During resizing, the background color of the frame shows the master widget's background whenever the buttons are removed to facilitate re-position. During repositioning, when a row of buttons exceed the frame width, I had to remove the last button on the row to reposition it the a new row. This procedure causes a grey out effect on the right side of the frame. When I am resizing the height of the frame, the buttons position should not be affected but presently because of the binding used the buttons would still reposition itself to the same position. Such a wrapping behavior is redundant and I would like to avoid it. How can I circumvent/overcome the above mentioned issues? Thank you. FrameButtons.py #!/usr/bin/python3.6.5 # -*- coding: utf-8 -*- #Load python3 modules import tkinter as tk import tkinter.ttk as ttk import platform class FrameButtons(ttk.Frame): def __init__(self, master, **options): background = master.winfo_toplevel().cget('background') style = options.pop( 'style', ttk.Style() ) background = options.pop( 'background', background ) borderwidth = options.pop( 'borderwidth', 0 ) relief = options.pop( 'relief', 'flat' ) texts = options.pop( 'texts', ['0'] ) textwidth = options.pop( 'textwidth', 10 ) debug = options.pop( 'debug', False ) master.update_idletasks() masterwidth = master.winfo_width() masterwidth2 = masterwidth - borderwidth*2 print('masterwidth, w/border = ', masterwidth, masterwidth2) width = masterwidth2 super().__init__( master, style='main.TFrame', width=wid…
accepted answer: http://stackoverflow.com/a/52393141
tagged with: python
has answer: http://stackoverflow.com/a/52393141
type: AnsweredQuestion

http://stackoverflow.com/q/52283702
answer count: 1
linked to: http://stackoverflow.com/q/42869495
tagged with: moving-average
type: UnansweredQuestion
has body: I want to create moving average strategy with rolling funtion and scipy optimization but my code do not optimize rolling. It gives result which I entered as first x0 values. I searched for it in google there are ways to create all rolling possibilities but it takes lot of time. Is there any way to optimize efficiently. Here is my code, thanks in advance; import pandas as pd import os import numpy as np from datetime import datetime import scipy.optimize as opt #read file data = pd.read_csv(r'C:\Users\Kaan\USDTRY-2018_06_01-2018_09_07.csv', encoding='utf-8', header=None, index_col=0) data.columns = ['buy','sell',1,2] data1 = data'buy','sell'.head(100000) # Optimization -------------------------------////////////////////------------------------------------ def objective(x): x1 = x[0] x2 = x[1] x3 = x[2] x4 = x[3] data3 = pd.DataFrame(data=data1) data3['sma1']=data3['buy'].rolling(int(x3)).mean() data3['sma2']=data3['buy'].rolling(int(x4)).mean() data3['sma1-sma2'] = np.round(data3['sma1']-data3['sma2'],5) data3['pos'] = np.where(data3['sma1-sma2'] &gt;= x1, 1, 0) data3['pos'] = np.where((data3['sma1-sma2'] &lt; -x1) ,-1, data3['pos']) data3['pos'] = np.where(abs(data3['sma1-sma2']) &gt; x2, 0, data3['pos']) data3['return'] = np.round(np.log(data3['buy'] / data3['buy'].shift(1)),5) data3['st'] = data3['pos'].shift(1)*data3['return'] return -1*data3['st'].cumsum().apply(np.exp).tail(1)[0] def constraints1(x): return x[3] * x[2] - 0 def constraints2(x): return x[3] - x[2] - 0 b = (0.0,1000000.0) bonds = (b,b,b,b) x0=[0.00205062, 0.19746918, 893, 1990] print(objective(x0)) con1 = {'type':'ineq','fun':constraints1} con2 = {'type':'ineq','fun':constraints2} cons = [con1,con2] sol = opt.minimize(objective, x0, bounds=bonds, constraints=cons) print(sol)
tagged with: python
tagged with: rolling-average
has title: Python Optimization Moving Average
has answer: http://stackoverflow.com/a/52284285
has comment: http://stackoverflow.com/comment/91517318
type: Question
tagged with: optimization
score: 0
tagged with: pandas

http://stackoverflow.com/q/52317458
answer count: 0
type: UnansweredQuestion
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/91624535
has title: flask restplus works in my local docker images but doesn't in azure
tagged with: flask
tagged with: docker
score: 0
tagged with: flask-restplus
linked to: http://stackoverflow.com/q/51292579
tagged with: azure
has body: i did my flask application using flask restplus, i try it locally using runserver.py and i can see my swagger api, i put it on a docker container exposing port 80 and i run it with -p 4000:80 and also works fine, but when i send the image to the container registry in azure, and put it on my webaplication all the other end points works, but just the root that points to the swagger api page doesnt =( i get the message No spec provided. is there some other things that i need to expose? like another port? or might be an azure security? maybe flask restplus needs to get something from internet? like a CND website to get the colors or svgs? thanks guys.
has comment: http://stackoverflow.com/comment/91602481

http://stackoverflow.com/comment/91631893
type: Comment
has text: do you initialize filename? Does webserver process have access to that folder?
comment on: http://stackoverflow.com/q/52342814
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91582543
score: 1
comment on: http://stackoverflow.com/q/52317544
type: QuestionComment
has text: Errors aside, almost certainly your approach is not safe, checkout this post and elegant solution https://stackoverflow.com/a/9558001/6260170
type: Comment

http://stackoverflow.com/comment/91783126
has text: Just a side note: you are only closing the last file.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52419851
type: Comment

http://stackoverflow.com/q/52282580
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91516688
score: 0
tagged with: printing
has body: If a line starts with a number(xyz) in a file, I need to print(or write to a file) this line and the next xyz+1 lines. What's the best way to do this? So far, I've been able to print the line that starts with an int. How do I print the next lines? import glob, os, sys import subprocess file = 'filename.txt' with open(file,'r') as f: data = f.readlines() for line in data: if line[0].isdigit(): print int(line) If I made an iterator out of data, the print function skips a line every time. with open(file,'r') as f: data = f.readlines() x = iter(data) for line in x: if line[0].isdigit(): print int(line) for i in range(int(line)): print x.next() How could I make it stop skipping lines?
answer count: 1
has comment: http://stackoverflow.com/comment/91513351
favorite count: 0
has comment: http://stackoverflow.com/comment/91514185
tagged with: glob
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91513453
has answer: http://stackoverflow.com/a/52282635
has title: Python: Print x lines after a pattern including the line with pattern
upvote count: 1

aes
tags question: http://stackoverflow.com/q/52356956
type: Tag
tag name: aes
tags question: http://stackoverflow.com/q/52376823
tags question: http://stackoverflow.com/q/52343418

http://stackoverflow.com/a/52393316
has body: What about something like: d = {} for row, col in t: vals = df.loc[df.index.str.startswith(row), df.columns.str.startswith(col)].stack().dropna() if len(vals): d[vals.idxmax()] = vals.max()
score: 0
answers question: http://stackoverflow.com/q/52392880
type: Answer

http://stackoverflow.com/a/52358509
score: 0
has body: Use df['Open'] = pd.to_numeric(df['Open'], errors='coerce') df['Volumes'] = pd.to_numeric(df['Volumes'], errors='coerce') You have strings and not numbers in your df, that's why you get a _ as output in Jupiter.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52358417
type: Answer
has comment: http://stackoverflow.com/comment/91667050
has comment: http://stackoverflow.com/comment/91666967
answers question: http://stackoverflow.com/q/52358417

http://stackoverflow.com/comment/91790995
type: Comment
has text: can we see the contents of `mainscript.py`
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52423984

http://stackoverflow.com/comment/92642876
has text: Its a current limitation of that endpoint you can only get items that have an Item Class (or subclass) of IPM.Note
comment on: http://stackoverflow.com/a/52434580
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91591646
type: Comment
type: QuestionComment
has text: last 20 rows with in the group? Or groupby among the last 20?
comment on: http://stackoverflow.com/q/52322000
score: 0

http://stackoverflow.com/comment/91660174
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52357834
has text: Did you read your error message? The last line is pretty unequivocal.

http://stackoverflow.com/a/52299827
has body: Using if-else to only define the function once should shut flake8 up: if 'pycurl' in sys.modules: def pycurl_downloader(url, char_encoding=None): # actual implementation, now we are certain pycurl is there ... else: def pycurl_downloader(*args, **kwargs): raise NotImplementedError
has comment: http://stackoverflow.com/comment/91547944
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52299749
type: Answer
accepted answer of: http://stackoverflow.com/q/52299749
score: 2
upvote count: 2

http://stackoverflow.com/q/52410154
tagged with: python
upvote count: 2
has body: I have a tensorflow UNet-style network. Currently I specify the input and target images as follows: self.inputTensors = tf.placeholder(tf.float32, [None, opt.inputHeight, opt.inputWidth, opt.inputChannels], name='inputTensors') self.targetColors = tf.placeholder(tf.float32, [None, opt.inputHeight, opt.inputWidth, opt.outputChannels], name='targetColors') But I would like it to be able to operate on variable width and height images as well, i.e. self.inputTensors = tf.placeholder(tf.float32, [None, None, None, opt.inputChannels], name='inputTensors') self.targetColors = tf.placeholder(tf.float32, [None, None, None, opt.outputChannels], name='targetColors') And infer the width and height of the intermediate layers. This works fine for my pooling layers or strided convolution layers, but for the upsampling layers I am using tf.image.resize_bilinear (although the question is valid for any of tf.image.resize_images.) Currently my resize bilinear code looks like: def unpool2xBilinear(inputs, name = 'unpool2xBilinear'): sh = inputs.get_shape().as_list() newShape = (sh[1] * 2, sh[2] * 2) return tf.image.resize_bilinear(inputs, newShape) However, this cannot handle unknown input shapes, giving TypeError: unsupported operand type(s) for *: 'NoneType' and 'int' Is there a way to allow resize images to accept input-dependent sizes? Or do I have to build an entirely new graph for each different input image size?
answer count: 1
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/52410517
has title: Resizing tensorflow images with unknown size
tagged with: deep-learning
score: 2
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/52410517

http://stackoverflow.com/comment/91764324
comment on: http://stackoverflow.com/q/52410291
score: 3
type: Comment
type: QuestionComment
has text: Why would you *want* to?

http://stackoverflow.com/q/52396215
type: Question
has answer: http://stackoverflow.com/a/52396342
answer count: 1
score: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: web
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/52396342
tagged with: python
has body: I am trying to learn to web scrape using Python and BeautifulSoup. My problem is when attempting to add "scraped" items to a new list, only the final entry in the relevant tags is displaying when I print the lists. How do I add each combination as a list item? import requests standings = requests.get('http://games.espn.com/ffl/tools/finalstandings?leagueId=379978&amp;seasonId=2012') from bs4 import BeautifulSoup soup = BeautifulSoup(standings.text, 'html.parser') ## Ask BeautifulSoup to find all of the records pat = soup.find_all('tr', attrs={'class':'sortableRow evenRow'}) teams = [] for x in pat: name1 = x.find('a').text record1 = x.find('td', {'class':'sortableREC'}).text pf1 = x.find('td', {'class':'sortablePF'}).text pa1 = x.find('td', {'class':'sortablePA'}).text pfg1 = x.find('td', {'class':'sortablePFG'}).text pag1 = x.find('td', {'class':'sortablePAG'}).text diff1 = x.find('td', {'class':'sortableDIFF'}).text teams.append((name1, record1, pf1, pa1, pfg1, pag1, diff1)) odd =soup.find_all('tr', attrs={'class':'sortableRow oddRow'}) teams2 = [] for team in odd: name2 = team.find('a').text record2 = team.find('td', {'class':'sortableREC'}).text pf2 = team.find('td', {'class':'sortablePF'}).text pa2 = team.find('td', {'class':'sortablePA'}).text pfg2 = team.find('td', {'class':'sortablePFG'}).text pag2 = team.find('td', {'class':'sortablePAG'}).text diff2 = team.find('td', {'class':'sortableDIFF'}).text teams2.append((name2, record2, pf2, pa2, pfg2, pag2, diff2))
type: AnsweredQuestion
tagged with: screen-scraping
has title: python web scraping beautiful soup and adding to a list

http://stackoverflow.com/q/52399118
has title: Access .mdb Database in .zip File with Python
has comment: http://stackoverflow.com/comment/91759114
tagged with: http://stackoverflow.com/tag/zip
linked to: http://stackoverflow.com/q/43258102
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: Hello there, Edited 19.09.2018 14:38 to clarify my problem first of all, thank you for reading my question! I hope that my problem is even solvable, as I couldn't find any answers in my research on this specific task. Context: There is a measurement system that stores measurement data in MS Access .mdb files. The typical size of the files is about 100 to 200 MB and the longest table, which is about 99 % of the space required, has around 400k to 600k datasets. As there are many files, they are packed as .zip archives to reduce the required space (e.g. Compressed: 17131406 bytes, Uncompressed: 245739520 bytes). Approach: If I want to evaluate the measurement data, I need to extract the .zip file first: import zipfile from zipfile import ZipFile """Extract example .zip file into this directory""" path = "C:/20180730_0931.zip" archive = zipfile.ZipFile(path, 'r') archive.extractall(path=None, members=None, pwd=None) Afterwards I can access the extracted database: import pyodbc """Important: 32bit MS driver - 32bit python!""" cnxn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:/20180730_0931.mdb;') cursor = cnxn.cursor() cursor.execute("select * from mytable") for row in cursor.fetchall(): print(row) csr = cnxn.cursor() csr.close() del csr cnxn.close() So, whats the problem? As there are multiple users I think it is a bad solution and can cause problems to just extract the zip file and delete the mdb file afterwards. So my idea was, that the zip file is extracted in a temporary file on the system of the user. As @Goyo pointed out, there are different ways of storing a temporary file (hard drive, a flash drive, an in-memory filesystem, ..). At first I just want to get a working solution, but of course I prefere the fastest possible way. The workflow of the program could look like this: Selelect the zip file and extract it into a temporary file on the user system Connect to the resulting mdb file with pyodbc and fetch all data Close the connectio…
has comment: http://stackoverflow.com/comment/91750225
has comment: http://stackoverflow.com/comment/91744432
has comment: http://stackoverflow.com/comment/91750240
has comment: http://stackoverflow.com/comment/91758661
has comment: http://stackoverflow.com/comment/91785580
has comment: http://stackoverflow.com/comment/91743841
type: Question
has comment: http://stackoverflow.com/comment/91750211
has comment: http://stackoverflow.com/comment/91753559
has comment: http://stackoverflow.com/comment/91751858
has comment: http://stackoverflow.com/comment/91743189
score: 0
has comment: http://stackoverflow.com/comment/91806231

http://stackoverflow.com/q/52391765
has answer: http://stackoverflow.com/a/57631325
has comment: http://stackoverflow.com/comment/91765860
has answer: http://stackoverflow.com/a/52679538
type: Question
has answer: http://stackoverflow.com/a/52391898
tagged with: newline
has title: About new line and space after last row and last column respectively
answer count: 6
has answer: http://stackoverflow.com/a/52391967
score: 0
has answer: http://stackoverflow.com/a/52391820
has answer: http://stackoverflow.com/a/52410052
has comment: http://stackoverflow.com/comment/91728587
has body: What I must get as output, exactly like this : Example-1: Input: 3 Output: 1\n 1 2\n 1 2 3 Example-2: Input: 4 Output: 1\n 1 2\n 1 2 3\n 1 2 3 4 In the first example the input was 3. Hence there are 3 rows. The first row has element 1. The second row contains two elements 1 and 2 and the third row contains 1, 2 and 3 separated by a space. What I actually get to: Example 1- 1 \n Example 2 - 1 \n the below code and I don't 1 2 \n 1 2 \n want this as an output 1 2 3 \n 1 2 3 \n 1 2 3 4 \n There should not be any space after the each element of the last column and no new line after the last row. My code: n = int(input()) i=1 j=1 for i in range(1,n+1): for j in range(1,i+1): if i&gt;=j: print(j, end=" ") if(i!=j): print(end="") print()
type: UnansweredQuestion
tagged with: python
tagged with: design-patterns

http://stackoverflow.com/comment/91660546
type: Comment
comment on: http://stackoverflow.com/q/52357964
score: 0
has text: @RafaelC Ah ok. The df is huge (40.000 rows). But i can try to make an excerpt.
type: QuestionComment

http://stackoverflow.com/comment/91615451
has text: @HendrikWiese how do you manage multiprocessing ? With multiprocessing library or do you simply launch multiple scripts at the same time ?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52332743
type: Comment

http://stackoverflow.com/q/52371526
has comment: http://stackoverflow.com/comment/91687670
score: -3
downvote count: 4
has title: Nested dictionaries to single dictionary in python
has comment: http://stackoverflow.com/comment/91687651
type: AnsweredQuestion
has body: I am editing it I have 2 dictionaries: x= {'Content-Type': 'application/x-www-form-urlencoded'} y= {'Accept': 'application/json'} And I need to create final dictionary z = {x, y} How would I do it? I have headers variable which accepts the following value headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' } Can someone help me to convert following into above format? headers = { {'Content-Type': 'application/x-www-form-urlencoded'}, {'Accept': 'application/json'} } Currently, this one gives me the following error. TypeError: unhashable type: 'dict' thanks for help!
accepted answer: http://stackoverflow.com/a/52372633
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91687669
type: Question
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91687703
answer count: 3
has comment: http://stackoverflow.com/comment/91688520
possible better answer: http://stackoverflow.com/a/52371585
upvote count: 1
has answer: http://stackoverflow.com/a/52371585
has answer: http://stackoverflow.com/a/52372633
has answer: http://stackoverflow.com/a/52372055

http://stackoverflow.com/q/52380351
has comment: http://stackoverflow.com/comment/91705413
favorite count: 0
tagged with: linux
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91705100
tagged with: php
has comment: http://stackoverflow.com/comment/91705332
score: 2
has body: I have a web site and parsing some content from social media or other web sites to keep information up to date. As you know Instagram won't work with "beatifulSoup Python Parser" or maybe others just because you have to log in, and must be able to run js, otherwise it won't load. And it happens with others too. For that reason i do run some js script on client side, using google chrome console, this script saves the data in localStorage which i do use after. The problem is sometimes i do have a low speed internet, or i have to run this script with my pc, it takes a lot of time. Maybe not much but doing in every day time, it becomes really problematic. I wanted to make this job on server side, there is always high internet speed, and i would be able to start the script with my phone, when ever or where ever, and i am trying to figure out how to realize. I need a browser on server side, which would run js, and just everything the same as a client. Start a browser Wait for a page load run some js script Most of the servers do not have the graphic interface and do return on terminal just html code. But there is a lot of host services, java servers and more and more, not only apach or nginx. On java as i know you can create a browser of your own, so it means kinda possible to run browser function on server. The question is, is there any ready tools which i can just use, or maybe to write this kinda functionality, but using libraries, frameworks to be able to write it as fast as possible, not spending a lot of time. Because I am not working over, to create a browser on server side, i just want to be able to run some js. I work with php, js, python. Java only SE and on the client. JavaEE has a lot of libraries and tons of abilities. Maybe somebody knows in which language i could realize this. Any frameworks, or maybe on linux it is possible, or there is a host servers which can run as a client, some companies i think does this kind of staff to make some job automatically. …
upvote count: 2
tagged with: java
linked to: http://stackoverflow.com/q/41467692
type: Question
has title: How to run browser functionality on server?
has comment: http://stackoverflow.com/comment/91706003
tagged with: javascript
has answer: http://stackoverflow.com/a/52382485
has answer: http://stackoverflow.com/a/52398085
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/91510699
type: QuestionComment
type: Comment
has text: *we end up with unforeseen diamond inheritance* <-- well, that shouldn't be unforeseen. Virtually every time you use multiple inheritance in Python 3, it's a diamond inheritance in some shape or form.
comment on: http://stackoverflow.com/q/52272811
score: 0

http://stackoverflow.com/a/52357822
has comment: http://stackoverflow.com/comment/92340554
has comment: http://stackoverflow.com/comment/92336940
has comment: http://stackoverflow.com/comment/92337390
answers question: http://stackoverflow.com/q/52356128
type: Answer
has comment: http://stackoverflow.com/comment/92337173
accepted answer of: http://stackoverflow.com/q/52356128
has comment: http://stackoverflow.com/comment/92339280
upvote count: 4
has body: Here is example code using the scipy.optimize.differential_evolution genetic algorithm, with your data and equation. This scipy module uses the Latin Hypercube algorithm to ensure a thorough search of parameter space and so requires bounds within which to search - in this example, those bounds are based on the data maximum and minimum values. For other problems you might need to supply different search bounds if you know what range of parameter values to expect. import numpy, scipy, matplotlib import matplotlib.pyplot as plt from scipy.optimize import curve_fit from scipy.optimize import differential_evolution import warnings # power law function def func_power_law(x,a,b,c): return a*(x**b)+c test_X = [1.0,2,3,4,5,6,7,8,9,10] test_Y =[3.0,1.5,1.2222222222222223,1.125,1.08,1.0555555555555556,1.0408163265306123,1.03125, 1.0246913580246915,1.02] # function for genetic algorithm to minimize (sum of squared error) def sumOfSquaredError(parameterTuple): warnings.filterwarnings("ignore") # do not print warnings by genetic algorithm val = func_power_law(test_X, *parameterTuple) return numpy.sum((test_Y - val) ** 2.0) def generate_Initial_Parameters(): # min and max used for bounds maxX = max(test_X) minX = min(test_X) maxY = max(test_Y) minY = min(test_Y) maxXY = max(maxX, maxY) parameterBounds = [] parameterBounds.append([-maxXY, maxXY]) # seach bounds for a parameterBounds.append([-maxXY, maxXY]) # seach bounds for b parameterBounds.append([-maxXY, maxXY]) # seach bounds for c # "seed" the numpy random number generator for repeatable results result = differential_evolution(sumOfSquaredError, parameterBounds, seed=3) return result.x # generate initial parameter values geneticParameters = generate_Initial_Parameters() # curve fit the test data fittedParameters, pcov = curve_fit(func_power_law, test_X, test_Y, geneticParameters) print('Parameters', fittedParameters) modelPredictions = func_power_law(test_X, *fittedParameters) absError = modelPredictions - test_Y SE = numpy.s…
downvote count: 0
has comment: http://stackoverflow.com/comment/91819207
has comment: http://stackoverflow.com/comment/92336548
score: 4
has comment: http://stackoverflow.com/comment/91777206
type: AcceptedAnswer

http://stackoverflow.com/a/52316121
has body: Looking at the implementation, you're missing the period at the end of the sentence: if str(e) != 'The volatility is below the intrinsic value.': I don't see the point in this check because that will always be the message the exception is created with.
type: Answer
accepted answer of: http://stackoverflow.com/q/52309471
answers question: http://stackoverflow.com/q/52309471
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91628448
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52417843
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/91778818
has body: I am working on a larger script that walks through a directory structure to perform an action on each file. I am having trouble figuring out how to pass the target directory as an argument in the command line (to be the starting point of the os.walk). Can anyone advise on what I am doing wrong? import os import sys def main(): for root, dirs, files in os.walk(sys.argv[1]) for item in files: print(items) if __name__ == '__main__': main(sys.argv[1])
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/52417952
upvote count: 2
has answer: http://stackoverflow.com/a/52417952
answer count: 1
tagged with: python
has title: define argument in command line for python os.walk script
score: 2

http://stackoverflow.com/q/52324192
favorite count: 0
tagged with: jupyter-notebook
type: UnansweredQuestion
has body: When I run the command jupyter notebook from the bash shell this starts a jupyter notebook server on localhost. Every time I open a new notebook and start executing code, is that a new process on a separate core or a new thread on the same core? Suppose I were to run N different independent notebooks which are CPU heavy, on a machine with M cores If they all run from the same core (same process) with different threads then are the rest of the cores are basically idle? If they run from different cores, then does that mean I can only run M total notebooks at the same time? Or perhaps its a mix of both: the ipython kernel takes care of launching new threads/processes that are beyond my manual control. In which case only M total notebooks would be able actually execute concurrently at the interpreter level, but I could open as many notebooks as my memory would allow.
tagged with: python
has answer: http://stackoverflow.com/a/52324652
has title: Does each jupyter notebook use threads or processes
has answer: http://stackoverflow.com/a/52350182
type: Question
score: 5
has comment: http://stackoverflow.com/comment/91596048
upvote count: 5
answer count: 2
downvote count: 0

http://stackoverflow.com/q/52416610
type: UnansweredQuestion
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/52417408
has title: What is the difference in this re expressions?
type: Question
has comment: http://stackoverflow.com/comment/91776636
score: 0
has body: i am testing the re expressions and the book example was: if re.search('^X\S*: [0-9.]+', line): But with my expression I reach the same result: if re.search('^X\S*: [0-9]', line): What's is the difference?, what do I not see?. Thank you.
answer count: 2
has comment: http://stackoverflow.com/comment/91812957
has answer: http://stackoverflow.com/a/52416649

http://stackoverflow.com/a/52342148
score: 0
answers question: http://stackoverflow.com/q/52342110
type: Answer
has body: Just apply the standard debugging technique: make the lists smaller and smaller, while making sure the output is still unexpected. It is possible to reproduce this unexpected behavior with lists of size 2. Compare [2,1] with [2,3]. Also, run your algorithm manually, using pen and paper. Be sure that you follow the algorithm exactly. And if you want to do something different, find out why and in which situations.
has comment: http://stackoverflow.com/comment/91630808

http://stackoverflow.com/q/52419070
has answer: http://stackoverflow.com/a/52419886
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/91781879
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91781906
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52419886
downvote count: 2
upvote count: 1
type: Question
tagged with: opencv
possible better answer: http://stackoverflow.com/a/52419722
has comment: http://stackoverflow.com/comment/91781852
has answer: http://stackoverflow.com/a/52419722
score: -1
has body: When I was trying to load a image from path using cv2.imread, it shows 'none'. I created the UI to upload the image using flask. Here's what I've done: UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg']) app = Flask(__name__) #app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/') def uploadfile(): return render_template('home.html') @app.route('/uploader', methods=['GET', 'POST']) def upload_file(): target = os.path.join(UPLOAD_FOLDER, 'static/') upload = os.path.join(target, 'uploads/') if not os.path.isdir(target): os.mkdir(target) os.mkdir(upload) if request.method == 'POST': file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(upload, filename)) image=cv2.imread('/home/user/image/static/uploads/filename') print("image",image) My image isn't loaded to the 'image'. The result of print is image,None ,
has title: load image using cv2.imread
has comment: http://stackoverflow.com/comment/91781777
answer count: 2

http://stackoverflow.com/q/52284234
has answer: http://stackoverflow.com/a/52284404
tagged with: python
has comment: http://stackoverflow.com/comment/91544408
has comment: http://stackoverflow.com/comment/91544614
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91516686
has body: It appears that when I run &gt;conda list, I have two versions of pandas installed. pandas 0.23.4 py36h830ac7b_0 pandas 0.22.0 &lt;pip&gt; I cannot run import pandas or import pandas as pd in my console (Anaconda - Spyder/Jupyter Notebook) to check the version, but I am getting errors thrown in a script related to pandas: Traceback (most recent call last) ... from pandas.errors import AbstractMethodError ImportError: cannot import name 'AbstractMethodError' I was going to do &gt;conda update pandas but it said that my numpy would be downgraded. That doesn't sound right! How do I fix this?
tagged with: conda
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/52284404
has comment: http://stackoverflow.com/comment/91519416
answer count: 1
has title: Two versions of Pandas causing problems
score: 0
tagged with: pandas
tagged with: version
has comment: http://stackoverflow.com/comment/91520875

http://stackoverflow.com/a/57134641
type: Answer
has comment: http://stackoverflow.com/comment/124592176
has body: Following a clean install of Ubuntu 18.04 (via Vagrant), the following was installed successfully without any issues: sudo apt-get update sudo apt-get install -y python3-pip Note that the Ubuntu 18.04 download today shipped with Python 3.6.8 installed. This may vary by the time of your reading this post.
score: 42
upvote count: 42
downvote count: 0
answers question: http://stackoverflow.com/q/52394543

http://stackoverflow.com/a/52319726
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52319664
answers question: http://stackoverflow.com/q/52319664
has body: Since the ids are unique, you can store the items in a dictionary to achieve O(1) lookup. lookup = {ele['id']: ele for ele in data} then you can do user_info = lookup[user_id] to retrieve it
upvote count: 2

http://stackoverflow.com/a/52415355
answers question: http://stackoverflow.com/q/52400853
type: Answer
score: 0
has body: based on the description here It should be like this, but not tested. import mock def mock_jwt_required(realm): return @mock.patch('flask_jwt.jwt_required', side_effect=mock_jwt_required) def test_get(jwt_required_fn): a_obj = A() a_obj.get("address123", 'xyz')

http://stackoverflow.com/comment/91771549
type: AnswerComment
has text: this is not going to work because it will bring all the divs we need one that just looks for div with a certain class "media-story"
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52413459

http://stackoverflow.com/comment/91640032
comment on: http://stackoverflow.com/a/52347199
type: Comment
score: 1
has text: Iteration should be preferred in Python over recursion. Function call overhead is much larger than the overhead of a for-loop.
type: AnswerComment

http://stackoverflow.com/q/52409631
type: AnsweredQuestion
downvote count: 1
type: Question
has title: Using python to access JAVA API?
has answer: http://stackoverflow.com/a/52409738
upvote count: 0
has comment: http://stackoverflow.com/comment/91763123
answer count: 1
has body: I have written a python scripts which get data from various sources(Quandl, webscraping etc) at the moment. I want to switch to a more stable information feed, order placement system. The broker provides an API: https://www.sharekhan.com/active-trader/oalert/new-to-oalert After looking through the docs and the scant information available it seems I can only use it with java. I am new-ish to python and have never tried java. Can someone point me in the direction of where to begin learning more about how to use the API in my python program/script? From the FAQ TradeTiger API has a Transmission Control Protocol (TCP)-based architecture. So, it can work in any programming language that can communicate using the TCP protocol. Some programming languages that are compatible with the API are C#.net, VB.Net, Java, Python, C++ and VB. Thanks
has comment: http://stackoverflow.com/comment/91763072
favorite count: 0
accepted answer: http://stackoverflow.com/a/52409738
has comment: http://stackoverflow.com/comment/91763521
tagged with: python
has comment: http://stackoverflow.com/comment/91763611
score: -1

django-authentication
tags question: http://stackoverflow.com/q/52425647
tag name: django-authentication
type: Tag
tags question: http://stackoverflow.com/q/52407131

http://stackoverflow.com/comment/91574687
comment on: http://stackoverflow.com/a/52312431
type: Comment
has text: You should break from both loops once you set a 1, not continue checking.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91492915
type: QuestionComment
has text: I want to make that result data as global data for all celery workers.
score: 0
comment on: http://stackoverflow.com/q/52271999
type: Comment

http://stackoverflow.com/a/52429680
upvote count: 2
answers question: http://stackoverflow.com/q/52428916
downvote count: 0
has body: Instead of just dumping all your locations into the Cluster, you could loop over them and create a Marker for each of them - that way you can set the Marker's color. After creation, you can add the Marker to the desired MarkerCluster. for com_location, com_popup in zip(com_locations, com_popups): folium.Marker(com_location, popup=com_popup icon=folium.Icon(color='red', icon='info-sign') ).add_to(cluster) A different approach would be to modify the style function, as shown here (In[4] and In[5]).
type: Answer
has comment: http://stackoverflow.com/comment/91804646
score: 2

http://stackoverflow.com/q/52382522
has answer: http://stackoverflow.com/a/52383374
type: UnansweredQuestion
has title: Correct way to represent 3Dimentional data for Keras CNN model?
tagged with: scipy
type: Question
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/91710495
tagged with: pandas
answer count: 1
has body: I am new to numpy. I have a dataset of 1000 3D structures and every structure has x,y,z coordinates. I am trying to use a CNN model but not able to prepare the correct dataset format for the architecture. Here is my pandas data frame dataset: row_id, xlist, ylist, zlist, target 1, [1,2,3,3], [5,2,6,7], [1,0,4,5], 1 2, [-1,6,4,6], [7,-1,4,1], [2,5,3,5], 1 3, [6,4,-2,-2], [2,-6,6,2], [3,0,7,2], 0 ... n, [5,3,1], [5,3,7], [3,5,3], 1 I tried this but it is not what I want np.array([dataset['xlist'],dataset['ylist'],dataset['zlist']]) I want to obtain a 3D structure with x * y * z dimentions. How can I create a 3D matrix with dimentions 4 * 4 * 4 (for x, y, and z)
tagged with: python
has comment: http://stackoverflow.com/comment/91709877

http://stackoverflow.com/q/52383664
possible better answer: http://stackoverflow.com/a/52384069
has title: Why does numpy not allow assignment of a doubly indexed numpy array?
has answer: http://stackoverflow.com/a/52384069
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52384944
has answer: http://stackoverflow.com/a/52384421
has comment: http://stackoverflow.com/comment/91711812
has comment: http://stackoverflow.com/comment/91712954
has comment: http://stackoverflow.com/comment/91711904
linked to: http://stackoverflow.com/q/52323524
downvote count: 0
has answer: http://stackoverflow.com/a/52383863
has body: I would like to assign values of an array arr_2 to a different array arr_1. However, I want to do this based on 2 selection criteria. As a working example, I define my selection criteria as such import numpy as np # An array of -1 values of shape(10,): [-1 -1 -1 -1 -1 -1 -1 -1 -1 -1] arr_1 = np.zeros(10, dtype=int) - 1 # An array of 0-9 values of shape(10,): [0 1 2 3 4 5 6 7 8 9] arr_2 = np.arange(10) # Create an initial selection of values we want to change # In this example: even indices: [ T F T F T F T F T F] selection_a = np.arange(10) % 2 == 0 # Create a second selection based on selection_a: [F F F T T] selection_b = arr_2[selection_a] &gt; 5 Based on these two selection criteria I would like to assign the values of arr_2 where both conditions hold to the array arr_1. I.e. equivalent to [F F F F F F T F T F]. arr_1[selection_a][selection_b] = arr_2[selection_a][selection_b] If I inspect both sides of the equation before the assignment, they yield the values that I expect: print(arr_1[selection_a][selection_b]) # yields [-1 -1] print(arr_2[selection_a][selection_b]) # yields [ 6, 8] However, the assignment itself does not assign the values, i.e. arr_1 remains unchanged. My question is, why is this the case? NB: I know that in most (and maybe even all cases) this can be circumvented by creating a single criterion, however I want to know why using 2 separate criteria won't work. If anything is unclear, please let me know and I'll try to clarify. Edit I investigated this a bit further and the problem seems to be in the left hand side of the equation as something like arr_1[selection_a][selection_b] = 5 does not work either.
answer count: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/91739275
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91711806
has comment: http://stackoverflow.com/comment/91739375
score: 1
accepted answer: http://stackoverflow.com/a/52383863

http://stackoverflow.com/a/52308917
answers question: http://stackoverflow.com/q/52308493
type: AcceptedAnswer
has body: If you dont want to use list comprehension: my_list=[] for i in range(5): n=int(input("Enter and integer number:")) my_list.append(n) print(my_list) for index, i in enumerate(my_list): if i%5==0: my_list[index] = i + 5 print (my_list)
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91565606
accepted answer of: http://stackoverflow.com/q/52308493

http://stackoverflow.com/q/52417206
has title: python string format without {}
type: Question
tagged with: format
has answer: http://stackoverflow.com/a/52417326
downvote count: 4
upvote count: 0
accepted answer: http://stackoverflow.com/a/52417326
answer count: 1
has body: Case 1: '{} is good'.format('This') Output: This is good. Case 2: 'is good'.format('This') Output: is good Can I use Case 2 ? string does not contain {} . but I use format() The reason I ask is I want to assign value only for the thing containing {} m = ["{} is good", "{} is bad", "all are normal"] for loop m m[index].format("AA") Anyway I found it worked . But I have to know it is right way.
tagged with: string
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: -4

http://stackoverflow.com/q/52420831
tagged with: python
has comment: http://stackoverflow.com/comment/91786162
has comment: http://stackoverflow.com/comment/91784893
has comment: http://stackoverflow.com/comment/91785051
has comment: http://stackoverflow.com/comment/91784933
has comment: http://stackoverflow.com/comment/91784803
upvote count: 2
has body: import pyspark.sql.functions as f df_categories4 = df_categories3.select("alias", "title", f.when(df_categories.parents == 0).otherwise(df_categories3.parents[0])).show() It shows an error of when() missing 1 required positional argument: 'value'. But if i place a value after the '0', it says that there is an error that can't be resolve. How would I approach this problem? Thanks. Original Error: TypeError: when() missing 1 required positional argument: 'value' Error After Entering Value after 0: AnalysisException: "cannot resolve '(`parents` = 0)' due to data type mismatch: differing types in '(`parents` = 0)' (array&lt;string&gt; and int).;;\n'Project [alias#226, title#230, CASE WHEN (parents#229 = 0) THEN 1 ELSE parents#229[0] END AS CASE WHEN (parents = 0) THEN 1 ELSE parents[0] END#1079]\n+- AnalysisBarrier\n +- Filter ((array_contains(country_whitelist#228, US) || array_contains(country_whitelist#228, CA)) || isnull(country_whitelist#228))\n +- Filter (NOT (array_contains(country_blacklist#227, US) &amp;&amp; array_contains(country_blacklist#227, CA)) || isnull(country_blacklist#227))\n +- Relation[alias#226,country_blacklist#227,country_whitelist#228,parents#229,title#230] json\n"
type: UnansweredQuestion
tagged with: bigdata
has comment: http://stackoverflow.com/comment/91785135
downvote count: 1
has comment: http://stackoverflow.com/comment/91785253
has title: Positional argument error when using 'when' in pyspark
type: Question
has comment: http://stackoverflow.com/comment/91785070
has comment: http://stackoverflow.com/comment/91785046
has answer: http://stackoverflow.com/a/52421459
tagged with: pyspark
tagged with: database
has comment: http://stackoverflow.com/comment/91785473
has comment: http://stackoverflow.com/comment/91784909
answer count: 1
score: 1
has comment: http://stackoverflow.com/comment/91784752
favorite count: 0
has comment: http://stackoverflow.com/comment/91785569
has comment: http://stackoverflow.com/comment/91784850
tagged with: apache-spark

http://stackoverflow.com/comment/91768787
comment on: http://stackoverflow.com/a/52412271
type: AnswerComment
score: 0
type: Comment
has text: @justengel the while still stinking, an improvement would be the following: `slider = QtWidgets.QSlider(QtCore.Qt.WA_DeleteOnClose) slider.show() loop = QtCore.QEvenLoop() slider.destroyed.connect(loop.quit) loop.exec_()`

http://stackoverflow.com/comment/91694966
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52374941
has text: I don't get what relation to PHP is here. Can you reduce the problem? Or can you at least extend the question with a [mcve]?
type: Comment

http://stackoverflow.com/a/52407091
answers question: http://stackoverflow.com/q/52405276
has comment: http://stackoverflow.com/comment/91784030
accepted answer of: http://stackoverflow.com/q/52405276
has comment: http://stackoverflow.com/comment/91821289
score: 0
type: AcceptedAnswer
has body: There is no use in using a ReLu activation function before applying softmax_cross_entropy. Change the activation function in the last fully connected layer to None and you'll get good accuracy. from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf from tensorflow.contrib.layers import fully_connected x = tf.placeholder(dtype=tf.float32,shape=[None,784]) y = tf.placeholder(dtype=tf.float32,shape=[None,10]) test_x = tf.placeholder(dtype=tf.float32,shape=[None,784]) test_y = tf.placeholder(dtype=tf.float32,shape=[None,10]) mnist = input_data.read_data_sets("/home/xuenzhu/mnist_data", one_hot=True) hidden1 = fully_connected(x,100,activation_fn=tf.nn.relu,weights_initializer=tf.random_normal_initializer()) hidden2 = fully_connected(hidden1,100,activation_fn=tf.nn.relu,weights_initializer=tf.random_normal_initializer()) outputs = fully_connected(hidden2,10,activation_fn=None,weights_initializer=tf.random_normal_initializer()) loss = tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=outputs) reduce_mean_loss = tf.reduce_mean(loss) equal_result = tf.equal(tf.argmax(outputs,1),tf.argmax(y,1)) cast_result = tf.cast(equal_result,dtype=tf.float32) accuracy = tf.reduce_mean(cast_result) train_op = tf.train.AdamOptimizer(0.001).minimize(reduce_mean_loss) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})) for i in range(10000): xs,ys = mnist.train.next_batch(128) sess.run(train_op,feed_dict={x:xs,y:ys}) if i%1000==0: print(sess.run(equal_result,feed_dict={x:mnist.test.images,y:mnist.test.labels})) print(sess.run(reduce_mean_loss,feed_dict={x:mnist.test.images,y:mnist.test.labels})) print(sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}))
type: Answer

http://stackoverflow.com/comment/91759172
score: 0
type: Comment
has text: I've tried to run Ridge and Linear regressions on the data you provided and there is a flat minimum of the r^2 score for values of alpha around 300,000. Also, the coefficient of determination you are looking at can be negative and returns 0 when you output the mean of your outputs. Moreover, most of your binary values have similar distribution within the groups formed by the output values (0 and 1). This can be a coincidence but the 9-th row has only values values equal to .
type: QuestionComment
comment on: http://stackoverflow.com/q/52339693

http://stackoverflow.com/comment/91670337
score: 0
type: Comment
has text: I get an error stating" while Guess2 == ((Estimate+Guess)/2): UnboundLocalError: local variable 'Guess2' referenced before assignment" Im assuming because i havn't closed my loop it hasnt defined guess2 yet?
type: AnswerComment
comment on: http://stackoverflow.com/a/52362828

http://stackoverflow.com/q/52410113
type: Question
has answer: http://stackoverflow.com/a/52410514
score: 0
answer count: 1
tagged with: amazon-web-services
favorite count: 0
upvote count: 3
tagged with: python
downvote count: 3
tagged with: django
accepted answer: http://stackoverflow.com/a/52410514
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91764536
has title: after deploy django code to aws, datas in django admin are gone
has body: I am new in Django, python , and AWS. I register a user, and I can see the user in my Django admin deployed to AWS. After I write a new feature and 'eb deploy' to AWS. I can see the new feature, but the user I registered before disappear. Can any one help?

http://stackoverflow.com/a/52399769
type: AcceptedAnswer
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/91743574
has body: You can use factorize: print (df.dtypes) INSTRUMENT_TYPE_CD object RISK_START_DT datetime64[ns] FIN_POS_IND int64 PL_FINAL_IND object dtype: object #select only object columns (obviously strings) #cols = df.select_dtypes('object').columns #select columns by names cols = ['INSTRUMENT_TYPE_CD','PL_FINAL_IND'] for c in cols: df[c] = pd.factorize(df[c])[0] print (df) INSTRUMENT_TYPE_CD RISK_START_DT FIN_POS_IND PL_FINAL_IND 0 0 01-03-2017 00:00 0 0 1 1 01-09-2018 00:00 0 0 2 0 01-09-2017 00:00 0 0 3 0 01-12-2016 00:00 0 0 4 1 01-02-2018 00:00 0 0
accepted answer of: http://stackoverflow.com/q/52399725
score: 1
answers question: http://stackoverflow.com/q/52399725
upvote count: 1

http://stackoverflow.com/q/52334940
has comment: http://stackoverflow.com/comment/91617440
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52335243
has title: Not able to scrape links in python with beautifulsoup
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91617363
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: web-scraping
type: Question
has comment: http://stackoverflow.com/comment/91617733
has body: I want to scrape all the links on a webpage which is tag and class="author track". There are multiple URLs like this on a web page but when i run the program, my list is empty Example of one HTML:- Nileshkikuuchise My code:- discover_page = BeautifulSoup(r.text, 'html.parser') finding_accounts = discover_page.find_all("a", "[class~=author track]") print(finding_accounts) and output is none How do i get the href value to the list?. I can do the for loop later but need to get the basics correct first

http://stackoverflow.com/q/52360073
score: 3
has body: I'm building SIP 4.19.12 and PyQt 5.11.2 on Windows 10 with Visual Studio 2017. I'm planning to do that for Python x86 2.7.15. I downloaded the versions above and extracted them, installed enum34 with pip, the configured SIP with python configure.py --sip-module PyQt5.sip --no-tools This is SIP 4.19.12 for Python 2.7.15 on win32. The PyQt5.sip module will be installed in C:\Users\FiFo\AppData\Local\Programs\Python\Python27\Lib\site-packages\PyQt5. The sip.pyi stub file will be installed in C:\Users\FiFo\AppData\Local\Programs\Python\Python27\Lib\site-packages\PyQt5. The default directory to install .sip files in is C:\Users\FiFo\AppData\Local\Programs\Python\Python27\sip. Creating sipconfig.py... Creating top level Makefile... Creating sip code generator Makefile... Creating sip module Makefile... Setup the x86 building environment with "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x86 Followed by nmake: Microsoft (R) Program Maintenance Utility Version 14.15.26729.0 Copyright (C) Microsoft Corporation. All rights reserved. cd siplib C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\bin\HostX86\x86\nmake.exe Microsoft (R) Program Maintenance Utility Version 14.15.26729.0 Copyright (C) Microsoft Corporation. All rights reserved. cl -c -nologo -Zm200 -Zc:wchar_t- -O2 -MD -W3 -DNDEBUG -DUNICODE -DWIN32 -DQT_LARGEFILE_SUPPORT -DSIP_MODULE_NAME=\"PyQt5.sip\" -I. -IC:\Users\FiFo\AppData\Local\Programs\Python\Python27\include -Fo @C:\Users\FiFo\AppData\Local\Temp\nm8C0F.tmp siplib.c apiversions.c descriptors.c qtlib.c threads.c objmap.c voidptr.c array.c int_convertors.c Generating Code... cl -c -nologo -Zm200 -Zc:wchar_t- -O2 -MD -W3 -w34100 -w34189 -DNDEBUG -DUNICODE -DWIN32 -DQT_LARGEFILE_SUPPORT -DSIP_MODULE_NAME=\"PyQt5.sip\" -I. -IC:\Users\FiFo\AppData\Local\Programs\Python\Python27\include -Fo @C:\Users\FiFo\AppData\Local\Temp\nm9111.tmp bool.cpp link /NOLOGO /DYNAMICBASE /NXC…
type: Question
has answer: http://stackoverflow.com/a/52372235
accepted answer: http://stackoverflow.com/a/52372235
downvote count: 0
tagged with: python-sip
has title: PyQt5's PyQt5.sip File is Not Generated by the SIP Library
upvote count: 3
answer count: 1
tagged with: python
favorite count: 0
tagged with: pyqt5
type: AnsweredQuestion

http://stackoverflow.com/a/52298638
downvote count: 1
score: 2
answers question: http://stackoverflow.com/q/52298586
has body: Assuming you dict name as d pd.Series(d).to_frame().T Out[55]: key1 key2 key3 0 1 42 foo #pd.Series(d).to_frame().T.to_csv()
upvote count: 3
type: Answer

http://stackoverflow.com/comment/91512574
comment on: http://stackoverflow.com/q/52282066
type: Comment
type: QuestionComment
has text: If you're entering code golf competitions. For production code, less so.
score: 0

http://stackoverflow.com/comment/91776524
comment on: http://stackoverflow.com/a/52396490
score: 0
type: Comment
has text: Thank you for the information. I knew about .set() and thought of using it but wanted something more challenging. I have done word[::-1], but my intentions where to find the space, reverse it, then add the space to show the user that it is in fact a Paldrome. Again, thank you for the hint.
type: AnswerComment

http://stackoverflow.com/q/52362047
type: AnsweredQuestion
score: 0
tagged with: matplotlib
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52362671
has body: I want the Y-axis in the Graph with the Range in the Sum column. total_by_year.plot(kind='bar' ,x='year',y='sum',rot=0, legend=False) plt.show() DataFrame output: year sum 0 2010 42843534.38 1 2011 45349314.40 2 2012 35445927.76 3 2013 0.00 below is the Graph i am getting:
has comment: http://stackoverflow.com/comment/91673031
answer count: 2
has comment: http://stackoverflow.com/comment/91668420
linked to: http://stackoverflow.com/q/29188757
has answer: http://stackoverflow.com/a/52362399
favorite count: 0
has comment: http://stackoverflow.com/comment/91668649
possible better answer: http://stackoverflow.com/a/52362399
linked to: http://stackoverflow.com/q/52362124
upvote count: 1
tagged with: python
has title: Axis values is not showing as in the DataFrame in python
has answer: http://stackoverflow.com/a/52362671

http://stackoverflow.com/q/52335276
possible better answer: http://stackoverflow.com/a/52335622
accepted answer: http://stackoverflow.com/a/52335297
has answer: http://stackoverflow.com/a/52335622
score: 2
type: AnsweredQuestion
downvote count: 0
favorite count: 0
tagged with: python-3.x
has title: How to index list when there is 2 of the same char
has body: I have been trying to make the even letters in a string become upper-cased and the odd letters to become lower-cased with a function, like so: def myfunc('apple'): #OUTPUTS: 'ApPlE' This is what I made: def myfunc(mystring): stringList = [letter for letter in mystring] for letter in stringList[1::2]: stringList[stringList.index(letter)] = letter.lower() for letter in stringList[::2]: stringList[stringList.index(letter)] = letter.upper() return ''.join(stringList) I believe that, when I use words like 'apple' where there is two identical letters, the index() function can only manage to give me the index of the first 'p', if my word is apple. It returns: 'APplE' How could I fix this?
type: Question
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52335297
upvote count: 2

http://stackoverflow.com/comment/140216548
type: Comment
has text: There is quite plausibly a simple answer for this use-case - see my answer using zeroguess library.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52375410

http://stackoverflow.com/comment/91592669
type: QuestionComment
type: Comment
score: 1
has text: define `list1=[]` in your function and unindent the `return` function to the same level as `for i in range (a,c)`
comment on: http://stackoverflow.com/q/52322523

http://stackoverflow.com/a/52374473
type: Answer
accepted answer of: http://stackoverflow.com/q/52351116
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
has body: Question: ... do this to only show relevent time values? The following implements your own class Timedelta: class Timedelta(object): def __init__(self, td): self._td = td def _calc(s, f): _s = int(s % f) return _s, int(s / f) s, self.hours = _calc(self._td.seconds, (60 * 60)) self.seconds, self.minutes = _calc(s, 60) def __str__(self): r = "" for v in [('Days', self._td.days), ('Hours', self.hours), ('Minutes', self.minutes), ('Seconds', self.seconds)]: if v[1] != 0: lingua = v[0] if v[1] == 1: lingua = v[0][:-1] r += "{} {} ".format(v[1], lingua) return r def __repr__(self): return "({}) Days:{} Hours:{} Minutes:{} Seconds:{}"\ .format((self._td.seconds), self._td.days, self.hours, self.minutes, self.seconds) Usage: date1 = dt.datetime(2018, 9, 17, hour=18, minute=23, second=0) date2 = dt.datetime(2018, 9, 17, hour=22, minute=23, second=10) dtt = date2 - date1 print("dtt:{}".format(dtt)) tdelta = Timedelta(date2 - date1) print("Timedelta::\__repr\__: {}".format(tdelta.__repr__())) print("Timedelta::\__str\__: {}".format(tdelta)) Output: dtt:4:00:10 Timedelta::__repr__: (14410) Days:0 Hours:4 Minutes:0 Seconds:10 Timedelta:__str__: 4 Hours 10 Seconds Tested with Python:3.4.2
answers question: http://stackoverflow.com/q/52351116

http://stackoverflow.com/q/52297210
has comment: http://stackoverflow.com/comment/91543698
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/52298053
has comment: http://stackoverflow.com/comment/91542621
tagged with: python
has title: Why does my code, reading a CSV file, print a dictionary, and not a list?
has comment: http://stackoverflow.com/comment/91542316
type: AnsweredQuestion
has body: import unicodecsv def read_csv(filename): with open(filename, 'rb') as f: reader = unicodecsv.DictReader(f) return list(reader) enrollments = read_csv('enrollments.csv') daily_engagement = read_csv('daily-engagement.csv') project_submissions = read_csv('project-submissions.csv') In the previous lesson I was learning how to read a CSV file and convert it to an editable format. The code works great but when I was trying to understand the code, and I don't understand why, when I print enrollments[0], that the result is a dictionary. The first part of the function uses with open(filename, 'rb') as f: I understand that it is used to open the file. The next part is reader = unicodecsv.DictReader(f), I understand that it is used for mapping the information read, into a dictionary. The third part is where I'm having difficulties understanding, the return list(reader) line. Doesn't this line mean that the reader variable is returned as a list()? So why it is returning a dictionary when I use print? print enrollments[0] {u'account_key': u'448', u'cancel_date': u'2015-01-14', u'days_to_cancel': u'65', u'is_canceled': u'True', u'is_udacity': u'True', u'join_date': u'2014-11-10', u'status': u'canceled'}
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91542293
accepted answer: http://stackoverflow.com/a/52298053
has comment: http://stackoverflow.com/comment/91544183
has comment: http://stackoverflow.com/comment/91542641
possible better answer: http://stackoverflow.com/a/52297287
tagged with: python-2.7
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52297287

http://stackoverflow.com/a/52293325
score: 1
answers question: http://stackoverflow.com/q/52293232
downvote count: 0
type: Answer
has body: There are several ways, but here's one without an explicit loop or specifying a format: L = [0, 1] datetime = pd.to_datetime('2017-11-13') + pd.to_timedelta(L, unit='h') Result: DatetimeIndex(['2017-11-13 00:00:00', '2017-11-13 01:00:00'], type='datetime64[ns]', freq=None) Your solution won't work because str does not work in a vectorised way.
upvote count: 1

http://stackoverflow.com/a/52394522
has body: Perl to the rescue! perl -pe 's/Vec2\(\K([0-9]+)/$1-1/ge' -- file \K makes the regex engine "forget" the preceding characters, so only the substring matching the following regex is replaced /e evaluates the replacement as code
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/52394269
downvote count: 0

http://stackoverflow.com/q/52355145
has answer: http://stackoverflow.com/a/52355513
favorite count: 0
type: Question
tagged with: gradient-descent
tagged with: python
upvote count: 2
answer count: 2
has body: This network contains an input layer and an output layer, with no nonlinearities. The output is just a linear combination of the input.I am using a regression loss to train the network. I generated some random 1D test data according to a simple linear function, with Gaussian noise added. The problem is that the loss function doesn't converge to zero. import numpy as np import matplotlib.pyplot as plt n = 100 alp = 1e-4 a0 = np.random.randn(100,1) # Also x y = 7*a0+3+np.random.normal(0,1,(100,1)) w = np.random.randn(100,100)*0.01 b = np.random.randn(100,1) def compute_loss(a1,y,w,b): return np.sum(np.power(y-w*a1-b,2))/2/n def gradient_step(w,b,a1,y): w -= (alp/n)*np.dot((a1-y),a1.transpose()) b -= (alp/n)*(a1-y) return w,b loss_vec = [] num_iterations = 10000 for i in range(num_iterations): a1 = np.dot(w,a0)+b loss_vec.append(compute_loss(a1,y,w,b)) w,b = gradient_step(w,b,a1,y) plt.plot(loss_vec)
tagged with: neural-network
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52355403
score: 2
downvote count: 0
has title: Neural network - loss not converging
tagged with: convergence

http://stackoverflow.com/q/52335081
tagged with: elasticsearch
tagged with: python
tagged with: web-services
score: 1
has title: How can I build a web interface on top of hundreds of excel reports
has answer: http://stackoverflow.com/a/52335321
upvote count: 1
type: Question
downvote count: 0
answer count: 1
favorite count: 0
has body: I have a large document collection on Excel financial reports. These reports are sitting on a shared drive and not all users have access to the drive. I would like to build some form of basic web interface with search capabilities so user can see the data. I have jupyter notebook running on my machine that can connect to the files. My questions are: 1. How can I build a web interface where the user can search for a customer that will trigger a function in the jupyter notebook. The function will bring back customer data and display on the browser. Since the purpose is to mostly do search and not any calculations, should I forget about python completely and look at elastic search? How can I get started with a basic elastic search query? Or is something like Cassandra better? I need the search to go across multiple excel files and bring back all results. So if we search for customer 'ABC', it will get me monthly stats for the last 12 months (each month is stored in a separate excel file).
tagged with: rest
type: UnansweredQuestion

http://stackoverflow.com/a/52290468
answers question: http://stackoverflow.com/q/52289736
has comment: http://stackoverflow.com/comment/91570791
accepted answer of: http://stackoverflow.com/q/52289736
type: AcceptedAnswer
downvote count: 0
has body: First of all, you can use the following code to check the list of all checkpoints in the ckpt file you saved. from tensorflow.python.tools import inspect_checkpoint as chkp chkp.print_tensors_in_checkpoint_file(file_name="file.ckpt", tensor_name="xxx", all_tensors=False, all_tensor_names=True) Remember when you restore a checkpoint file, it will restore all variables in the checkpoint file. If you have to save and restore specific variables, you can do so as follows: Make a list of all variables you want to save from tf.trainable_variables() var = [v for v in tf.trainable_variables() if "net_1_kernel" in v.name] saverAndRestore = tf.train.Saver(var) Now you can easily save or restore all the variables in var list as follows: saverAndRestore.save(sess_1,"net_1.ckpt") This will only save variables in the list var to net_1.ckpt. saverAndRestore.restore(sess_1,"net_1.ckpt") This will only restore variables in the list var from net_1.ckpt. Apart from above, all you have to do is name/scope your variables such that you can easily do step 1 above.
has comment: http://stackoverflow.com/comment/91531017
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/91597365
type: Comment
comment on: http://stackoverflow.com/a/52325210
score: 0
type: AnswerComment
has text: You tried this code but in your csv the format is different?? Are you sure you commented your apply/lambda-command away for this test...?

http://stackoverflow.com/a/52322458
downvote count: 0
answers question: http://stackoverflow.com/q/52322364
score: 1
has body: You can use combinations from itertools to select all unique pair of columns. from itertools import combinations np.random.seed(0) arr = np.array(np.random.randn(2, 3)) &gt;&gt;&gt; arr array([[ 1.76405235, 0.40015721, 0.97873798], [ 2.2408932 , 1.86755799, -0.97727788]]) &gt;&gt;&gt; np.array([arr[:, [i, j]] for i, j in combinations(range(arr.shape[1]), 2)]) array([[[ 1.76405235, 0.40015721], # First and second column. [ 2.2408932 , 1.86755799]], [[ 1.76405235, 0.97873798], # First and third column. [ 2.2408932 , -0.97727788]], [[ 0.40015721, 0.97873798], # Second and third column. [ 1.86755799, -0.97727788]]])
has comment: http://stackoverflow.com/comment/91593048
upvote count: 1
has comment: http://stackoverflow.com/comment/117571472
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52322364

http://stackoverflow.com/a/52309617
answers question: http://stackoverflow.com/q/52304079
type: Answer
score: 2
downvote count: 0
has body: As @bdbd mentioned in comments, you can do it by specifying by required=False. For example, if you want to age field to be optional, add it explicitly as from django import forms class CheckinPatientMetaForm(ModelForm): age = forms.IntegerField(required=False) class Meta: model = customer exclude = [ 'gender', 'maritalstatus', 'occupation', 'bloodgroup' ]
upvote count: 2

http://stackoverflow.com/q/52384798
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
type: Question
has body: This is an example of code, import PyPDF2 import numpy as np # creating a pdf file object pdfFileObj = open('original.pdf' , 'rb') pdfFileObj_1 = open('tutorial.pdf', 'rb') # creating a pdf reader object pdfReader = PyPDF2.PdfFileReader(pdfFileObj) pdfReader_1 = PyPDF2.PdfFileReader(pdfFileObj_1) # creating a pdf writer object for new pdf pdfWriter = PyPDF2.PdfFileWriter() for i in range(100): page= pdfReader.getPage(i) page_1= pdfReader_1.getPage(i) pdfWriter.addPage(page) pdfWriter.addPage(page_1) #print(pdfWriter.getNumPages()) # new pdf file object newFile = open('replaced_pdf_1.pdf', 'wb') pdfWriter.write(newFile) # closing the original pdf file object pdfFileObj.close() pdfFileObj_1.close() # closing the new pdf file object newFile.close() And the error i got, PdfReadWarning: Object 321 0 not defined. [pdf.py:1629] Traceback (most recent call last): File "test.py", line 22, in pdfWriter.write(newFile) File "/home/ubuntu/Ritesh/working/lib/python3.5/site-packages/PyPDF2/pdf.py", line 482, in write self._sweepIndirectReferences(externalReferenceMap, self._root) File "/home/ubuntu/Ritesh/working/lib/python3.5/site-packages/PyPDF2/pdf.py", line 571, in _sweepIndirectReferences self._sweepIndirectReferences(externMap, realdata) File "/home/ubuntu/Ritesh/working/lib/python3.5/site-packages/PyPDF2/pdf.py", line 547, in _sweepIndirectReferences value = self._sweepIndirectReferences(externMap, value) File "/home/ubuntu/Ritesh/working/lib/python3.5/site-packages/PyPDF2/pdf.py", line 571, in _sweepIndirectReferences self._sweepIndirectReferences(externMap, realdata) File "/home/ubuntu/Ritesh/working/lib/python3.5/site-packages/PyPDF2/pdf.py", line 547, in _sweepIndirectReferences value = self._sweepIndirectReferences(externMap, value) File "/home/ubuntu/Ritesh/working/lib/python3.5/site-packages/PyPDF2/pdf.py", line 556, in _sweepIndirectReferences value = self._sweepIndirectReferences(externMap, data[i]) File "/home/ubuntu/Ritesh/working/lib/python3.5/site-packages/PyPD…
accepted answer: http://stackoverflow.com/a/52393712
has title: Replace pages at-least 100 in PDF from another PDF
tagged with: http://stackoverflow.com/tag/pdf
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52393712

http://stackoverflow.com/a/52429583
has body: We could fiddle around with the code in the question, but still it would be an O(n^2) algorithm. To truly improve the performance is not a matter of making the implementation more or less pythonic, but to use a different approach with a helper data structure. Here's an outline for an O(n log n) solution: implement a self-balancing BST (AVL or red-black are good options), and additionally store in each node an attribute with the size of the subtree rooted in it. Now traverse the list from right to left and insert all its elements in the tree as new nodes. We also need an extra output list of the same size of the input list to keep track of the answer. For every node we insert in the tree, we compare its key with the root. If it's greater than the value in the root, it means that it's greater than all the nodes in the left subtree, hence we need to add the size of the left subtree to the answer list at the position of the element we're trying to insert. We keep doing this recursively and updating the size attribute in each node we visit, until we find the right place to insert the new node, and proceed to the next element in the input list. In the end the output list will contain the answer.
has comment: http://stackoverflow.com/comment/91806476
type: Answer
answers question: http://stackoverflow.com/q/52429260
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/91806530
downvote count: 0

http://stackoverflow.com/q/52299833
linked to: http://stackoverflow.com/q/46671348
score: 1
tagged with: image-processing
duplicate of: http://stackoverflow.com/q/46671348
type: Question
answer count: 1
has title: Displaying two images alternatively in one window repeatedly
favorite count: 0
has answer: http://stackoverflow.com/a/52300452
has comment: http://stackoverflow.com/comment/91548798
tagged with: python
upvote count: 2
has comment: http://stackoverflow.com/comment/91556001
accepted answer: http://stackoverflow.com/a/52300452
downvote count: 1
tagged with: opencv
type: AnsweredQuestion
has body: I have two images. I want to show them alternatively in the same window in opencv2 again and again after 1 second(python based) img = cv2.imread('LENNA.jpg',0) img2 = cv2.imread('CAMERAMAN.jpg',0) while TRUE: cv2.imshow("window",img) time.sleep(3) # 3 second delay cv2.imsow("window",img2) window freezes and becomes grey when I execute this.

http://stackoverflow.com/q/52340125
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/52340355
tagged with: multiprocessing
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/52340355
tagged with: asynchronous
has title: Multiprocessing pool map_async for one function then block before the next (python 3)
tagged with: multithreading
has body: please be warned that this demonstration code generates a few GB data. I have been using versions of the code below for multiprocessing for some time. It works well when the run time of each process in the pool is similar but if one process takes much longer I end up with many blocked processes waiting on the one, so I'm trying to make it run asynchronously - just for one function at a time. For example, if I have 70 cores and need to run a function 2000 times I want that to run asynchronously then wait for the last process before calling the next function. Currently it just submits processes in batches of how ever many cores I give it and each batch has to wait for the longest process. As you can see I've tried using map_async but this is clearly the wrong syntax. Can anyone help me out? import os p='PATH/test/' def f1(tup): x,y=tup to_write = x*(y**5) with open(p+x+str(y)+'.txt','w') as fout: fout.write(to_write) def f2(tup): x,y=tup print (os.path.exists(p+x+str(y)+'.txt')) def call_func(f,nos,threads,call): print (call) for i in range(0, len(nos), threads): print (i) chunk = nos[i:i + threads] tmp = [('args', no) for no in chunk] pool.map(f, tmp) #pool.map_async(f, tmp) nos=[i for i in range(55)] threads=8 if __name__ == '__main__': with Pool(processes=threads) as pool: call_func(f1,nos,threads,'f1') call_func(f2,nos,threads,'f2')
tagged with: python

http://stackoverflow.com/q/52428484
type: Question
has body: I'm new to tensorflow. I installed python and tensorflow. I'm getting below error after running my sample code. I have installed tensorflow by below command. I saw that the below command seems for mac, but I have used this command only to install tensorflow, it is successfully installed. I did not get link for windows, that is why I used below link. If anyone knows actual windows installation link for tensorflow, please share and provide solution for the below issue. pip3 install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.5.0-py3-none-any.whl Python 3.7.0, pip 18.0, tenserflow 1.5.0, windows 10 installation_test.py import tensorflow as tf sess = tf.Session() hello = tf.constant("Hellow") print(sess.run(hello)) a = tf.constant(20) b = tf.constant(22) print('a + b = {0}'.format(sess.run(a+b))) PS F:\tensorflow> python .\installation_test.py PS F:\tensorflow&gt; python .\installation_test.py Traceback (most recent call last): File "C:\Users\thava\AppData\Local\Programs\Python\Python37-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 18, in swig_import_helper fp, pathname, description = imp.find_module('_pywrap_tensorflow', [dirname(__file__)]) File "C:\Users\thava\AppData\Local\Programs\Python\Python37-32\lib\imp.py", line 297, in find_module raise ImportError(_ERR_MSG.format(name), name=name) ImportError: No module named '_pywrap_tensorflow' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\thava\AppData\Local\Programs\Python\Python37-32\lib\site-packages\tensorflow\python\__init__.py", line 66, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "C:\Users\thava\AppData\Local\Programs\Python\Python37-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 28, in &lt;module&gt; _pywrap_tensorflow = swig_import_helper() File "C:\Users\thava\AppData\Local\Programs\Python\Python37-32\lib\site-packages\tensorflow\python\pywrap_te…
has title: Tensorflow is not running in windows 10
score: 0
answer count: 1
tagged with: artificial-intelligence
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52440302
tagged with: python
linked to: http://stackoverflow.com/q/51780304
duplicate of: http://stackoverflow.com/q/51780304
tagged with: tensorflow

http://stackoverflow.com/q/52305341
favorite count: 0
accepted answer: http://stackoverflow.com/a/52305564
tagged with: django
tagged with: python
has body: I'm working a Django 2.0 website, and trying to build out a django form: forms.py: class NewMemberstatusform(forms.Form): rank = forms.ModelChoiceField(queryset=models.Rank.objects.all(), widget=forms.ModelChoiceField( attrs={ 'class':'form-control' } )) unit = forms.ModelChoiceField(queryset=models.Unit.objects.all(), widget=forms.ModelChoiceField( attrs={ 'class':'form-control' } )) activate = forms.ChoiceField(choices=YesNo.YESNO_CHOICES, label="Enable Member to see their information", widget=forms.ChoiceField( attrs={ 'class':'form-control' } )) My problem is that it does not compile correctly. I receive this error saying I'm missing the queryset in the rank field, but as you can see, it's clearly in the class. What am I missing? Thanks class NewMemberstatusform(forms.Form): File "/Users/sinistersparrow/PycharmProjects/ifthqcom/app_svcrecord/forms.py", line 126, in NewMemberstatusform 'class':'form-control' TypeError: __init__() missing 1 required positional argument: 'queryset'
has title: how to troubleshoot queryset requirement in django form
type: AnsweredQuestion
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/52305424
type: Question
has answer: http://stackoverflow.com/a/52305564
has answer: http://stackoverflow.com/a/52305424
downvote count: 0
answer count: 2

http://stackoverflow.com/q/52313325
tagged with: setuptools
has body: I'm trying to create an entry point when installing my package. Here is my package: . ├── foo │ ├── example.py │ └── __init__.py └── setup.py My setup.py is: import sys from setuptools import setup, find_packages console_scripts = \ ['foo.py = foo.example:main'] setup(name='foo', version='1.1.1', author='me', author_email='me', url='', entry_points={'console_scripts': console_scripts}, include_package_data=True, packages=find_packages(), zip_safe=False) And this is example.py: def main(): print "hello world" I'm installing like so: python setup.py sdist pip install dist/foo-1.1.1.tar.gz It works fine. But when I try to use the entry point /usr/bin/foo.py I get this traceback: Traceback (most recent call last): File "/usr/bin/foo.py", line 11, in &lt;module&gt; load_entry_point('foo==1.1.1', 'console_scripts', 'foo.py')() File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 570, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2751, in load_entry_point return ep.load() File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2405, in load return self.resolve() File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2411, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) ImportError: No module named example importing the foo module in python shell works fine as well.
type: Question
tagged with: entry-point
answer count: 1
tagged with: python-2.7
has answer: http://stackoverflow.com/a/52317190
tagged with: python
tagged with: setup.py
score: 0
type: UnansweredQuestion
has title: setuptools: ImportError on load_entry_point

http://stackoverflow.com/comment/91569898
has text: Can any Linux tkinter user can advice me if Method 2 works on your system or point out the mistake in my script? Greatly appreciate.
comment on: http://stackoverflow.com/q/52300878
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52330265
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91638779
tagged with: python
has comment: http://stackoverflow.com/comment/91618365
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/91607327
has title: Nested argparse parsers and help message
has comment: http://stackoverflow.com/comment/91667269
has comment: http://stackoverflow.com/comment/91607531
type: Question
has body: The situation One module (let's call it A) implements a "primary" argparse parser, that parses known arguments common for all children classes (using parser.parse_known_args(argv)). Then, it passes remaining arguments to another object that it's calling. Let's assume it may be either object of class B or C. Both B and C have their own argparse parsers which parse remaining arguments (using parser.parse_args(argv)). They take different arguments, specific to class B or C. Example snippet from class A: parser = argparse.ArgumentParser( description="Parent parser", formatter_class=argparse.RawTextHelpFormatter, allow_abbrev=False ) parser.add_argument('--argument_A', action="append", default=None, help="Help of first argument of parser A") known, remaining_args = parser.parse_known_args(argv) my_obj = self.create_obj(b_or_c, remaining_args) Example snippet from class B: parser = argparse.ArgumentParser( description="Class B parser", formatter_class=argparse.RawTextHelpFormatter, allow_abbrev=False ) parser.add_argument('--argument_B', action="append", default=None, help="Help of first argument of parser B") B_arguments_parsed = parser.parse_args(argv) Example snippet from class C: parser = argparse.ArgumentParser( description="Class C parser", formatter_class=argparse.RawTextHelpFormatter, allow_abbrev=False ) parser.add_argument('--argument_C', action="append", default=None, help="Help of first argument of parser C") C_arguments_parsed = parser.parse_args(argv) While implementing passing the arguments and parsing them in the right places was easy, I didn't find a simple solution to print proper help. The question How do I implement help message so that my parent parser (from class A) prints it's own help and help from parser B or C? I would like to see help message from parser A and, depending on which object was selected, parser B or C.
has comment: http://stackoverflow.com/comment/91618511
linked to: http://stackoverflow.com/q/32581439
tagged with: argparse
tagged with: arguments
downvote count: 0
favorite count: 0
upvote count: 2

http://stackoverflow.com/a/52288027
has comment: http://stackoverflow.com/comment/91524762
downvote count: 0
has comment: http://stackoverflow.com/comment/91525657
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91525579
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52287899
answers question: http://stackoverflow.com/q/52287899
type: Answer
has body: sort_index() before slicing would work: df = df.sort_index() df['2018-09-05':'2018-09-11'] or df = df.sort_index() df.loc['2018-09-05':'2018-09-11'] FYI: If you want to make sure that index is DatetimeIndex before making 'timestamp' as index: df.timestamp = pd.to_datetime(df.timestamp) df = df.set_index('timestamp') or after the fact: df.index = pd.to_datetime(df.index)
has comment: http://stackoverflow.com/comment/91525127
has comment: http://stackoverflow.com/comment/91524746
has comment: http://stackoverflow.com/comment/91524670
score: 3

http://stackoverflow.com/comment/91571574
type: QuestionComment
comment on: http://stackoverflow.com/q/52311755
has text: @Jonas Thanks for taking the time to respond. `p` is an integer (i.e the number of columns of I), `qs = np.random.randint(3, size = p)` just an array of length p with random integers. What I expect to have is a matrix `I` of dimension `q x p` full of zeros and ones depending on the conditional
score: 0
type: Comment

http://stackoverflow.com/q/52299927
has comment: http://stackoverflow.com/comment/91550984
favorite count: 0
tagged with: dask
has answer: http://stackoverflow.com/a/52303929
tagged with: python
has comment: http://stackoverflow.com/comment/91550961
score: 4
type: AnsweredQuestion
tagged with: netcdf
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/52303929
downvote count: 0
answer count: 1
has title: Efficient way to stack Dask Arrays generated from Xarray
has body: So I am trying to read a large amount of relatively large netCDF files containing hydrologic data. The NetCDF files all look like this: &lt;xarray.Dataset&gt; Dimensions: (feature_id: 2729077, reference_time: 1, time: 1) Coordinates: * time (time) datetime64[ns] 1993-01-11T21:00:00 * reference_time (reference_time) datetime64[ns] 1993-01-01 * feature_id (feature_id) int32 101 179 181 183 185 843 845 847 849 ... Data variables: streamflow (feature_id) float64 dask.array&lt;shape=(2729077,), chunksize=(50000,)&gt; q_lateral (feature_id) float64 dask.array&lt;shape=(2729077,), chunksize=(50000,)&gt; velocity (feature_id) float64 dask.array&lt;shape=(2729077,), chunksize=(50000,)&gt; qSfcLatRunoff (feature_id) float64 dask.array&lt;shape=(2729077,), chunksize=(50000,)&gt; qBucket (feature_id) float64 dask.array&lt;shape=(2729077,), chunksize=(50000,)&gt; qBtmVertRunoff (feature_id) float64 dask.array&lt;shape=(2729077,), chunksize=(50000,)&gt; Attributes: featureType: timeSeries proj4: +proj=longlat +datum=NAD83 +no_defs model_initialization_time: 1993-01-01_00:00:00 station_dimension: feature_id model_output_valid_time: 1993-01-11_21:00:00 stream_order_output: 1 cdm_datatype: Station esri_pe_string: GEOGCS[GCS_North_American_1983,DATUM[D_North_... Conventions: CF-1.6 model_version: NWM 1.2 dev_OVRTSWCRT: 1 dev_NOAH_TIMESTEP: 3600 dev_channel_only: 0 dev_channelBucket_only: 0 dev: dev_ prefix indicates development/internal me... I have 25 years worth of this data, and it is recorded hourly. So there is about 4 TB of data total. Right now I am just trying to get seasonal averages (Daily and Monthly) of the streamflow values. So I created the following script. import xarray as xr import dask.array as da from dask.distributed import Client import os workdir = '/path/to/directory/of/files' files = [os.path.join(workdir, i) for i in os.listdir(workdir)] client = Client(processes=False, threads_per_worker=4, n_workers=4, memory_limit='750MB') big_array = [] for i, file in enu…
tagged with: python-xarray

http://stackoverflow.com/comment/91759926
has text: Can you confirm that the root lttng-sessiond process is indeed killed by the pkill command? You can check that using `ps aux | grep lttng-sessiond`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52390566
type: Comment

http://stackoverflow.com/comment/91732485
type: Comment
comment on: http://stackoverflow.com/a/52393521
has text: @Mike Remeber, almost ANY website can be scraped but some websites are trickier than others. You can use selemium as shown there, or just any other scraping lib could do the job (IE : beautifulsoup). Using selenium, you can also run some javascript in the browser, if you need to.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52376090
has comment: http://stackoverflow.com/comment/91701225
tagged with: numpy
downvote count: 0
favorite count: 0
has body: I am new to this forum and Python so don't be to hard on me. I'm trying to create a new column, based on the shift between several values. Take this dataframe as an example: df = pd.DataFrame({'Durchfluss': {60: 4.273504273504258, 61: 3.66300366300365, 62: 3.0525030525030417, 63: 2.4420024420024333, 64: 2.4420024420024333, 65: 7.020757020756996, 66: 14.041514041514047, 67: 27.77777777777779, 68: 52.808302808302784, 69: 94.32234432234432, 70: 121.79487179487181, 71: 139.1941391941392, 72: 134.00488400488402, 73: 130.03663003663002, 74: 123.32112332112332, 75: 119.04761904761907, 76: 111.72161172161171, 77: 103.17460317460319, 78: 97.06959706959705, 79: 91.26984126984128, 80: 86.99633699633702, 81: 81.50183150183149, 82: 81.19658119658119, 83: 80.28083028083027, 84: 75.3968253968254, 85: 72.95482295482297, 86: 69.90231990231987, 87: 67.15506715506714, 88: 65.01831501831501, 89: 64.4078144078144, 90: 61.05006105006105, 91: 60.13431013431014, 92: 57.3870573870574, 93: 56.47130647130649, 94: 54.334554334554305, 95: 53.7240537240537, 96: 53.11355311355309, 97: 52.50305250305248, 98: 50.671550671550655, 99: 48.22954822954822, 100: 45.17704517704518, 101: 42.12454212454214, 102: 38.156288156288134, 103: 33.57753357753357, 104: 31.135531135531135, 105: 28.083028083028093, 106: 26.25152625152627, 107: 24.11477411477414, 108: 22.28327228327226, 109: 20.146520146520132, 110: 18.925518925518915, 111: 17.7045177045177, 112: 16.178266178266178, 113: 14.041514041514047, 114: 13.125763125763134, 115: 12.515262515262526, 116: 11.599511599511613, 117: 10.378510378510397, 118: 9.768009768009788, 119: 9.15750915750918, 120: 9.15750915750918, 121: 8.547008547008572, 122: 7.631257631257604, 123: 7.020757020756996, 124: 6.4102564102563875, 125: 5.799755799755779, 126: 5.189255189255171, 127: 4.5787545787545625, 128: 3.968253968253954, 129: 3.968253968253954, 130: 3.357753357753346, 131: 2.7472527472527375, 132: 2.4420024420024333, 133: 5.799755799755779, 134: 11.599511599511613, 135: 23.80…
tagged with: pandas
tagged with: grouping
tagged with: python
answer count: 0
type: UnansweredQuestion
upvote count: 1
has title: Python dataframe select areas of cycle
type: Question
score: 1
tagged with: dataframe

http://stackoverflow.com/a/52385835
type: Answer
upvote count: 1
score: 1
has body: You can do like this, In [11]: for fname,family_name,byear in info: ...: print '{}.{}.{}@python.com'.format(fname[0],family_name[:5],str(byear)[2:]) ...: J.Jense.93@python.com H.Hanse.92@python.com J.Johns.91@python.com A.Ander.90@python.com D.David.89@python.com
answers question: http://stackoverflow.com/q/52385753
downvote count: 0

input
tags question: http://stackoverflow.com/q/52298957
tags question: http://stackoverflow.com/q/52349592
tags question: http://stackoverflow.com/q/52362710
tags question: http://stackoverflow.com/q/52280099
tags question: http://stackoverflow.com/q/52397388
tags question: http://stackoverflow.com/q/52411090
tags question: http://stackoverflow.com/q/52272638
tag name: input
tags question: http://stackoverflow.com/q/52366175
tags question: http://stackoverflow.com/q/52324820
type: Tag

http://stackoverflow.com/q/52423525
has answer: http://stackoverflow.com/a/52423651
linked to: http://stackoverflow.com/q/7961363
has body: I am trying to find a way of remove all the occurences of an item in a list in Python. To do so, imagine that my list is: foo_list = [1,2,3,4,2,3] And let's suppose I am trying to get rid of the item 2. If I use the .remove method, it will just delete the first 2 in my list. foo_list.remove(2) Will have as output [1,3,4,2,3] but I would like to have as output [1,3,4,3]. Of course I can do so using a comprehension list such as: [item for item in foo_list if item !=2] I could also do set(foo_list) but I do want to keep the replicates elements that are not the selected one, 2 in this case. But I am trying to search for a way to do it without the need of a for loop as my real list has more than 100000 items, which it's making this procedure really slow. Is there any method similar to remove that would allow me to delete all the selected items? Any help would be appreciated.
has answer: http://stackoverflow.com/a/52424097
possible better answer: http://stackoverflow.com/a/52423610
answer count: 5
has comment: http://stackoverflow.com/comment/91789888
tagged with: python
accepted answer: http://stackoverflow.com/a/52424097
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/91789995
has comment: http://stackoverflow.com/comment/91789885
type: Question
linked to: http://stackoverflow.com/q/39980323
tagged with: for-loop
has comment: http://stackoverflow.com/comment/91790149
has title: Remove all the repetitions of an item in a list without using loops (Python)
has answer: http://stackoverflow.com/a/52423767
score: 0
has answer: http://stackoverflow.com/a/52423610
has answer: http://stackoverflow.com/a/52423765

http://stackoverflow.com/comment/91802204
type: AnswerComment
has text: I modified this solution slightly and it worked great. Generally, my questions are a much simplified version of the actual problem but using both `master_dictionary[key][k] = n_date` and `master_dictionary[key][k] = [n_date]` seemed to work in my situation. Thanks!
comment on: http://stackoverflow.com/a/52372467
score: 0
type: Comment

http://stackoverflow.com/a/52349641
downvote count: 0
has body: Group by the level=0 for you index and use .mean() df.groupby(df.index.get_level_values(level=0)).mean() release_year 1993 464.484548 1994 504.219173 1995 511.392629 1996 424.185431 1997 543.448686 Name: Net Profit, dtype: float64
type: Answer
answers question: http://stackoverflow.com/q/52349597
score: 2
upvote count: 2

http://stackoverflow.com/q/52294373
has answer: http://stackoverflow.com/a/52294538
score: 2
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-internals
tagged with: cpython
tagged with: python
accepted answer: http://stackoverflow.com/a/52294538
has title: how to find the implementation of [::-1] ( reversing list in python ) in CPython source code
type: AnsweredQuestion
tagged with: list
upvote count: 2
type: Question
has body: I was trying to reverse a list in python. There are many methods out there and [::-1] seems to be a great one! But I'm curious how [::-1] is done? What's the time complexity of it? I searched through CPython repo in github, but I couldn't find any clue. My strategy of searching was that I searched the key word: :: in CPython repo. Since there is :: in the python syntax, i.e. [::-1], there may be :: in the CPython source code so that [::-1] can refer to it and does the reversing. Does this make sense?

http://stackoverflow.com/q/52409296
tagged with: python
has title: Building sequential urls with Beautifulsoup
upvote count: 1
has comment: http://stackoverflow.com/comment/91762547
type: UnansweredQuestion
answer count: 0
downvote count: 0
score: 1
has body: I have a text file that has 1 number in it. i'm trying to have it go to the website with the first number appended to the url, grab the info and then move on to the next url in sequence, pull the info etc. If the number brings up a blank page, it should end the sequence and email out the information it gathered. I'm not getting any errors. It completes it's run, but i'm not getting any back or seeing any changes in the number in the text file. I'm curious if what i've got for this part of the program is correct, or if i'm missing something. Here's what I've got import requests from bs4 import BeautifulSoup as bs #loads LIC# url def get_page(license_number): url = URL_FORMAT.format(license_number) r = requests.get(url) return bs(r.text, 'lxml') #looks for non-existent info for no-license def license_exists(soup): if soup.find('td', class_ = 'style3'): return True else: return False #pulls lic# from text license_number.txt def get_current_license_number(): with open(LICENSE_NUMBER_FILE, 'r') as f: return int(f.read()) #adds lic# to urls def get_new_license_pages(curr_license_num): new_pages = [] more = True curr_license_num +=1 return new_pages
favorite count: 0
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/91763857

http://stackoverflow.com/q/52286480
has answer: http://stackoverflow.com/a/52286500
has comment: http://stackoverflow.com/comment/91521065
upvote count: 2
has comment: http://stackoverflow.com/comment/91521081
has comment: http://stackoverflow.com/comment/91521078
has comment: http://stackoverflow.com/comment/91521084
downvote count: 7
type: AnsweredQuestion
score: -5
possible better answer: http://stackoverflow.com/a/52286531
has comment: http://stackoverflow.com/comment/91521674
has answer: http://stackoverflow.com/a/52286531
accepted answer: http://stackoverflow.com/a/52286500
type: Question
answer count: 2
has title: Calculating leap years
favorite count: 0
has comment: http://stackoverflow.com/comment/91521163
linked to: http://stackoverflow.com/q/11621740
has body: I have an assignment that is supposed to calculate whether a year that the user inputs is in fact a leap year. I cannot figure out the formula for this. Can anyone help? I can figure out the rest of the code but here is what is needed: The month of February normally has 28 days. But if it is a leap year, February has 29 days. Write a program that asks the user to enter a year. The program should then display the number of days in February that year. Use the following criteria to identify leap years: 1. Determine whether the year is divisible by 100. If it is, then it is a leap year if and only if it is also divisible by 400. For example, 2000 is a leap year, but 2100 is not. 2. If the year is not divisible by 100, then it is a leap year if and only if it is divisible by 4. For example, 2008 is a leap year, but 2009 is not.
tagged with: python
duplicate of: http://stackoverflow.com/q/11621740

http://stackoverflow.com/comment/91728191
type: Comment
type: QuestionComment
has text: @liberforce I just look at the memory usage of the process. With "getting garbage collected" I mean that the process stays at roughly the same usage instead of constantly increasing for every created (and destroyed) window.
score: 0
comment on: http://stackoverflow.com/q/52376056

http://stackoverflow.com/comment/91533101
type: Comment
comment on: http://stackoverflow.com/a/52292639
has text: In a single while loop I'm setting indexes[my_choice] to be None, just once. Also, while condition is inside for loop which runs only 5 times
type: AnswerComment
score: 0

http://stackoverflow.com/a/52447617
answers question: http://stackoverflow.com/q/52426203
score: 0
has body: Have you checked that the publishable key and the secret key you're using match? That error usually means that you created the source using one account's publishable key and then tried to make the charge with another account's secret key. Specifically, this can happen really easily if you copy the examples from Stripe' site — these have example keys which work, but they are not your own account's keys so that could be why you get the error. Make sure you're using your publishable key from https://dashboard.stripe.com/account/apikeys .
type: Answer

http://stackoverflow.com/a/52346541
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/52346223
downvote count: 0
type: Answer
has body: Seems you overcomplicated the solution (while correctly selected key cases). It requires only single run through the list. def maxplat(l): if (len(l)==0): return 0, 0 start, leng = 0, 1 maxlen, maxstart = 0, 1 for i in range(1, len(l) + 1): if (i == len(l)) or (l[i] &lt; l[i-1]): if (leng &gt; maxlen): maxlen, maxstart = leng, start elif (l[i] == l[i-1]): leng += 1 else: start, leng = i, 1 return maxlen, maxstart #test cases print(maxplat([])) #empty case print(maxplat([3])) #single element print(maxplat([3,2,4,4,2,5,5,5,3])) #simple case print(maxplat([3,2,4,4,2,5,5,5,6])) #up after long run print(maxplat([3,2,4,4,2,5,5,5])) #run at the end print(maxplat([3,3,3,3,2,4,4,2])) #run at the start &gt;&gt;&gt; (0, 0) (1, 0) (3, 5) (2, 2) (3, 5) (4, 0)

http://stackoverflow.com/q/52424437
has comment: http://stackoverflow.com/comment/91792732
type: Question
has body: I have a rectangular board of MxN dimensions which needs to be cut into square peices of 1x1 size. Each of these squares has some value and the cost of cutting is the sum of the values of all the squares involved in the cut. I want to find the minimum possible cost. Example Say we have 2x3 board and the values of square peices are given in matrix like: 2 7 5 1 9 5 Now if we first make a horizontal cut the cost will be (2+7+5+1+9+5=29), and we will get two smaller reactangular board like: 2 7 5 and 1 9 5 Next we cut 1,9 and 5 (cost=1+9+5=15), then 2,7 and 5 (cost=2+7+5=14). So we have the following boards: 2 7 , 5, 1 9, 5 After this we cut 1 and 9 (cost=1+9=10), then 2 and 7 (cost=2+7=9). And we have the following squares left: 2 , 7, 5, 1, 9, 5 Now we will stop as all the remaining peices are 1x1 only. So the total cost is 77. Now this is just one of the ways which gives the minimum cost. There are other ways to cut the board which may give same or higher cost. So, how can I find the minimum cost? Thanks for help!
tagged with: arrays
has comment: http://stackoverflow.com/comment/91791626
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91792358
has comment: http://stackoverflow.com/comment/91792639
has title: Cutting board algo
has comment: http://stackoverflow.com/comment/91792701
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52426094
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91791662
type: UnansweredQuestion
tagged with: python
score: 1
upvote count: 1

http://stackoverflow.com/q/52338928
linked to: http://stackoverflow.com/q/14951356
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/52338987
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: django
downvote count: 1
has comment: http://stackoverflow.com/comment/91626476
has body: I have a Django app that uses the builtin login system. I'm trying to write a unit test that verifies that the login url redirects to home if the user is already authenticated. Meaning, if an already authenticated user tries to visit the login url, they get redirected to home. This is a built-in feature of Django's LoginView, and I have verified that it is indeed working. However, I'm not sure how to write a unit test for this. Question: How do I verify that this redirect occurs via unit tests? LoginView returns a TemplateResponse, which doesn't have a url parameter. What I have so far is this: from django.test import TestCase from django.urls import reverse home = reverse('home') login = reverse('login') logout = reverse('logout') signup = reverse('signup') USER_CREDS = { some users credentials } class TestLoginView(TestCase): def test_login_redirect(self): self.client.post(signup, USER_CREDS) self.client.get(logout) self.client.post(login, USER_CREDS) response = self.client.get(login) self.assertRedirects(response, home) EDIT: SimpleTestCase.assertRedirects does not work for TemplateResponse objects. TemplateResponse objects do not contain a url parameter, which is required for SimpleTestCase.assertRedirect. The method raises the following error: AttributeError: 'TemplateResponse' object has no attribute 'url' This is not the same as the linked question, because the response object from a LoginView is a TemplateResponse, not an HttpResponse.
has comment: http://stackoverflow.com/comment/91626250
type: Question
answer count: 1
has title: Django - get URL from TemplateResponse

http://stackoverflow.com/q/52370491
has answer: http://stackoverflow.com/a/52372377
has comment: http://stackoverflow.com/comment/91685659
type: UnansweredQuestion
tagged with: python
tagged with: module
has comment: http://stackoverflow.com/comment/91685708
has title: difference between parameter update using tensorflow module and update using manual variables
tagged with: tensorflow
type: Question
has body: I have #using module dense = tf.layers.dense(tf_dataset_l, nn_hidden, activation=tf.tanh) logits_l = tf.layers.dense(dense, num_labels, activation=tf.nn.softmax) loss_l = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=tf_labels_l, logits=logits_l)) optimizer_l = tf.train.GradientDescentOptimizer(0.5).minimize(loss_l) #manual w1 = tf.Variable(tf.truncated_normal([image_size * image_size, nn_hidden])) b1 = tf.Variable(tf.zeros([nn_hidden])) w2 = tf.Variable(tf.truncated_normal([nn_hidden, num_labels])) b2 = tf.Variable(tf.zeros([num_labels])) dense = tf.tanh(tf.matmul(tf_dataset, w1) + b1) logits = tf.matmul(hidden, w2) + b2 loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=tf_labels, logits=logits)) optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss) using mnist image and in same condition, final performance of using module : 92.2% vs final performance of manual : 88.7% I don't use some regularization trick or another. I don't know why there is difference between them. Please let me know
score: 0
answer count: 1

http://stackoverflow.com/q/52376306
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52376353
downvote count: 1
type: Question
has body: I have a pandas dataframe, foo, that looks like the following: a b 0 1 [1, 2] 1 2 [1, 2] 2 3 [10, 11] and I am trying to retrieve all the rows that contain the element [1, 2] in column b. Is there a good way to do this?
answer count: 1
score: 0
has title: Filtering list elements on Pandas
tagged with: pandas
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91679581
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52359797
has text: Alright, I've added the code and the full stack trace

http://stackoverflow.com/comment/91549904
has text: @Goyo However, that would mean anytime I'd seek to call the function, I'd have to refer to all of the parameters of the class, despite the function being in the class. Is there not a better way?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52300994

http://stackoverflow.com/q/52369199
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91682721
has comment: http://stackoverflow.com/comment/91683069
favorite count: 0
has comment: http://stackoverflow.com/comment/91683296
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52369985
type: UnansweredQuestion
tagged with: python
has title: How do i inherit 2 values from method in python
has comment: http://stackoverflow.com/comment/91682822
has comment: http://stackoverflow.com/comment/91683007
type: Question
has comment: http://stackoverflow.com/comment/91682813
score: 0
has body: class a(): def __init__(self): print("hello") def add(self,a,b): print("c = {}".format(self.a+self.b)) class b(a): def __init__(self): a.__init__(self) h = b() h.add(2,3) please tell me my error code not working Error Traceback (most recent call last): File "Inheritance.py", line 10, in h.add(2,3) File "Inheritance.py", line 5, in add print("c = {}".format(self.a+self.b)) AttributeError: 'b' object has no attribute 'a'
upvote count: 1

http://stackoverflow.com/a/52413463
has body: A solution is to bring in status as a global. status = 0 previousStatus = 0 # other code def roomControl(name, demand, thermostat, roomTemp): global status global previousStatus # This will bring in both variables to be edited within the function Good luck!
has comment: http://stackoverflow.com/comment/91770762
has comment: http://stackoverflow.com/comment/91770865
accepted answer of: http://stackoverflow.com/q/52413337
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52413337
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/91770885
upvote count: 1

http://stackoverflow.com/comment/91644018
comment on: http://stackoverflow.com/q/52349325
type: Comment
type: QuestionComment
score: 1
has text: @Kamikaze_goldfish can you post what is being outputted?

http://stackoverflow.com/comment/135386343
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52405696
type: AnswerComment
has text: Is there a similar library that allows execution of built flex templates with Python?

http://stackoverflow.com/q/52420064
has comment: http://stackoverflow.com/comment/91783758
has answer: http://stackoverflow.com/a/52420692
has comment: http://stackoverflow.com/comment/91783376
has body: I want to edit a a big file in specific lines. So it isnt a good Idea to read the whole file before editing, thats why I dont want to use: myfile.readlines() I have to read each line check if there a special content in it and then i have to edit this line. So far Im reading every line: file = open("file.txt","r+") i = 0 for line in file: if line ......: //edit this line //this is where i need help file.close() So the Question is: How can I edit the current line in the If Statement for example: if the current line is "test" I want to replace it with "test2" and then write "test2" back into the file into the line where "test" was before
has comment: http://stackoverflow.com/comment/91783396
has comment: http://stackoverflow.com/comment/91786980
type: Question
has answer: http://stackoverflow.com/a/52420204
has comment: http://stackoverflow.com/comment/91783975
linked to: http://stackoverflow.com/q/11145270
score: 0
answer count: 3
tagged with: python
has title: Edit specific line in a big file
linked to: http://stackoverflow.com/q/23598410
has comment: http://stackoverflow.com/comment/91783254
favorite count: 0
possible better answer: http://stackoverflow.com/a/77733140
has comment: http://stackoverflow.com/comment/91783505
has answer: http://stackoverflow.com/a/77733140
upvote count: 2
has comment: http://stackoverflow.com/comment/91783899
downvote count: 2
accepted answer: http://stackoverflow.com/a/52420204
has comment: http://stackoverflow.com/comment/91783278
has comment: http://stackoverflow.com/comment/91783788
has comment: http://stackoverflow.com/comment/91784447
has comment: http://stackoverflow.com/comment/91783945
type: AnsweredQuestion

http://stackoverflow.com/comment/91626172
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52337870
has text: Are you running python2 or python3, I found similar issues on google but probably you also find them and tried suggestions. A temporary solution is to use matplotlib instead of opencv imshow.

http://stackoverflow.com/a/69688126
score: 0
type: Answer
has body: I had the same problem and couldn't really figure it out. As it was a side project the mistake was infuriating and hilarious at the same time. My folder names had non-english letters. Specifically it had the letter "đ" and the SDK was always invalid because of it. You might say a stupid mistake, it was, but I wasn't really paying attention. Hope this helps somebody.
answers question: http://stackoverflow.com/q/52404529

http://stackoverflow.com/a/52412796
has comment: http://stackoverflow.com/comment/113432886
score: 33
upvote count: 33
has comment: http://stackoverflow.com/comment/93965113
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52412297
downvote count: 0
has comment: http://stackoverflow.com/comment/100560783
has comment: http://stackoverflow.com/comment/98866023
accepted answer of: http://stackoverflow.com/q/52412297
has comment: http://stackoverflow.com/comment/108725044
has comment: http://stackoverflow.com/comment/113421471
type: Answer
has body: PY-yaml library doesn't resolve environment variables by default. You need to define an implicit resolver that will find the regex that defines an environment variable and execute a function to resolve it. You can do it through yaml.add_implicit_resolver and yaml.add_constructor. In the code below, you are defining a resolver that will match on ${ env variable } in the YAML value and calling the function path_constructor to look up the environment variable. import yaml import re import os path_matcher = re.compile(r'\$\{([^}^{]+)\}') def path_constructor(loader, node): ''' Extract the matched value, expand env variable, and replace the match ''' value = node.value match = path_matcher.match(value) env_var = match.group()[2:-1] return os.environ.get(env_var) + value[match.end():] yaml.add_implicit_resolver('!path', path_matcher) yaml.add_constructor('!path', path_constructor) data = &quot;&quot;&quot; env: ${VAR}/file.txt other: file.txt &quot;&quot;&quot; if __name__ == '__main__': p = yaml.load(data, Loader=yaml.FullLoader) print(os.environ.get('VAR')) ## /home/abc print(p['env']) ## /home/abc/file.txt Warning: Do not run this if you are not the one specifying the env variables (or any other untrusted input) as there are remote code execution vulnerabilities with FullLoader as of July 2020.
has comment: http://stackoverflow.com/comment/91772003
has comment: http://stackoverflow.com/comment/108736518

http://stackoverflow.com/a/52391732
answers question: http://stackoverflow.com/q/52391597
score: 0
type: Answer
has body: I'm not sure if there's an elegant way to extract the book title with beautifulsoup. An easy work around though would be to extract the ISBN and then use the replace function to replace the ISBN with an empty string. Then clean up any whitespace with with strip function. titleString.replace(isbnString, "").strip() Replace: https://www.tutorialspoint.com/python/string_replace.htm Strip: https://www.tutorialspoint.com/python/string_strip.htm

yield
tags question: http://stackoverflow.com/q/52329668
tags question: http://stackoverflow.com/q/52362532
type: Tag
tag name: yield

http://stackoverflow.com/comment/91516316
has text: Somewhere the data on HDFS is not matching the schema you define for your DataFrame.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52282544

http://stackoverflow.com/comment/91735609
score: 0
has text: Do you know if there is a way to shorten my run time because I did use `while [year1, month1, day1] != [year2, month2, day2]` awhile back and it ran for over 2 minutes before I force stopped it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52395075

http://stackoverflow.com/comment/91540922
type: QuestionComment
comment on: http://stackoverflow.com/q/52296541
score: 13
has text: Well `iter()` creates a *new* iterable each time
type: Comment

http://stackoverflow.com/a/52355659
score: 2
has body: If you are ok using the standard library, this might help. What you really need is a sliding window over your iterator. You can use this function for that (this was based on grouper from itertools recipes): from itertools import islice def window(iterable, n=2): # window('123', 2) --&gt; '12' '23' args = [islice(iterable, i, None) for i in range(n)] return zip(*args) For the average you can use statistics.mean. The paddig part can be simply achieved by adding the average list with [None] * (n - 1): from statistics import mean def moving_average(prices, n): avgs = [mean(w) for w in window(prices, n)] padding = [None] * (n - 1) return padding + avgs Sample usage: &gt;&gt;&gt; moving_average([2,3,4,5,8,5,4,3,2,1], 3) [None, None, 3, 4, 5.666666666666667, 6, 5.666666666666667, 4, 3, 2] &gt;&gt;&gt; moving_average([1, 2, 3], 3) [None, None, 2] &gt;&gt;&gt; moving_average([1, 2, 3], 1) [1, 2, 3] &gt;&gt;&gt; moving_average([5, 10, 0], 2) [None, 7.5, 5]
answers question: http://stackoverflow.com/q/52355170
downvote count: 0
upvote count: 2
type: Answer

exception
tags question: http://stackoverflow.com/q/52426852
tags question: http://stackoverflow.com/q/52332281
tags question: http://stackoverflow.com/q/52332678
tags question: http://stackoverflow.com/q/52422476
tags question: http://stackoverflow.com/q/52411090
type: Tag
tags question: http://stackoverflow.com/q/52354405
tags question: http://stackoverflow.com/q/52309471
tag name: exception
tags question: http://stackoverflow.com/q/52312606
tags question: http://stackoverflow.com/q/52297143
tags question: http://stackoverflow.com/q/52284566
tags question: http://stackoverflow.com/q/52307055
tags question: http://stackoverflow.com/q/52318123

http://stackoverflow.com/q/52361242
has answer: http://stackoverflow.com/a/52361517
has body: Let's assume I got the following function: def do_something(arg_1, arg_2, arg_3): logger.info('arg_1: {0} arg_2: {1} arg_3: {2}'.format(arg_1, arg_2, arg_3)) print('Doing something..') Is there an elegant way to log all arguments of a function without listing argument names?
accepted answer: http://stackoverflow.com/a/52361332
type: AnsweredQuestion
score: 1
has title: Log all arguments of a function without using argument names
type: Question
answer count: 2
downvote count: 0
tagged with: python
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52361332
possible better answer: http://stackoverflow.com/a/52361517
upvote count: 1

http://stackoverflow.com/comment/91528902
score: 0
type: Comment
type: QuestionComment
has text: @user3927287 you might want to look at https://docs.python.org/3/library/xml.etree.elementtree.html#building-xml-documents - that way you're not working with string formatting and won't have to worry about any escaping/encoding required for any attributes you apply to the the tags/text elements etc...
comment on: http://stackoverflow.com/q/52290160

http://stackoverflow.com/comment/91512428
has text: @pault - My apologies, I should have mentioned, lambdas don't like assignment, so this code doesn't run.
comment on: http://stackoverflow.com/q/52282066
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52368146
score: 1
has answer: http://stackoverflow.com/a/52369137
has title: Numpy matrix multiplication fails ("shapes not aligned") when second element is a vector/array
tagged with: numpy
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/52368287
accepted answer: http://stackoverflow.com/a/52368287
favorite count: 0
possible better answer: http://stackoverflow.com/a/52368668
has comment: http://stackoverflow.com/comment/91680923
has body: When I multiply a NxN numpy matrix by a N elements numpy array I get an error saying that the shapes are not aligned. from numpy import matrix,ones,eye A = matrix(eye(3)) b = ones(3) A*b ValueError: shapes (3,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0) Also trasposing the vector does not solve the issue. A*b.T ValueError: shapes (3,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0) This make sense as numpy does not distinguish between column and row vectors so b.T is equal to b. How can I perform a simple matrix-vector multiplication?
tagged with: python
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/52368668
type: Question
has comment: http://stackoverflow.com/comment/91680735

http://stackoverflow.com/comment/96630884
score: 0
type: Comment
type: AnswerComment
has text: Thanks a lot! After countless hours of searching, this was the good answer. On Windows 10 N, you need to install the media feature pack. Thanks a lot!
comment on: http://stackoverflow.com/a/54321350

http://stackoverflow.com/comment/91755761
type: Comment
comment on: http://stackoverflow.com/a/52403355
has text: @kanayamalakar but there is a problem in the renormalisation for the colors... If after this line 'hist, xedges, yedges = np.histogram2d(x, y, bins=(7,7), range = [[-2,+2],[-2,+2]]) # you can change your bins, and the range on which to take data' you replace hist by an other 7X7 matrix, the colors are not anymore well scale. I don't understand why ! There should a better way to get this color gradiant.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52273673
tagged with: visualization
tagged with: python
has answer: http://stackoverflow.com/a/52274543
type: UnansweredQuestion
type: Question
has title: Bokeh server slow to render lots of NaN values (but fast enough in notebook)
tagged with: bokeh
score: 0
answer count: 1
has body: I am trying to build a dashboard using bokeh, and am currently stuck on a large line plot like this one: Even though this plots fairly quickly in my jupiter notebook (around a second maybe) it takes forever (multiple minutes) in my bokeh server. the network tab in my debug console shows no new data being received during this time, so I would guess it can't be my python code blocking the rendering? I also have a checkboxgroup, and it again takes more than a minute before the callback even reaches the bokeh server. I am plotting 40,000+ line segments connected and interspersed with loads of NaN values in 7 lines. (As I believe plotting large lines is better than plotting many lines in bokeh?). I make my plot like this: f = figure(toolbar_location=None, title='Schade verloop over leeftijd', output_backend="webgl") f.xaxis.axis_label = 'Leeftijd' f.yaxis.axis_label = 'Schade' for i, col, lbl in zip(range(7), colors, labels): r = f.line(x='x_line', y='y_line', line_width=2, source=sources[i], line_color=col, legend=lbl) f.legend.location = "top_left" f.legend.click_policy = "hide" And a small subsection of my data: xs = [np.array([np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]), np.array([np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]), np.array([np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, …

http://stackoverflow.com/q/52352421
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91649916
has comment: http://stackoverflow.com/comment/91650002
type: UnansweredQuestion
has body: I am writing a Python program that maintains a list of contacts, each having 3 fields: Name Phone Number Email Contacts need to be saved in a YAML structured file and the program is supposed to provide the facility of adding new contacts. My Code for this is: class contacts: def add_contact(self,file,contact): if not os.path.exists(file): #Creating for the first time temp = [] temp.append(contact) with open(file, "w") as file_desc: yaml.dump(temp, file_desc, default_flow_style=False) file_desc.close() else: #Second onwards with open(file, "r") as file_desc: loaded = yaml.safe_load(file_desc) loaded.append(contact) with open(file, "w") as file_desc2: yaml.dump(loaded, file_desc2, default_flow_style=False) file_desc2.close() file_desc.close() if __name__ == "__main__": data1 = {'name' :'Abcd', 'phone': 1234, 'email': 'abcd@gmail.com'} data2 = {'name': 'efgh', 'phone': 5678, 'email': 'efgh@gmail.com'} contact = contacts() contact.add_contact("contacts.yaml", data1) contact.add_contact("contacts.yaml",data2) I think this is an inefficient implementation. If we have 1 million contacts, and we want to add a new one, this will first read all of them, append one to the list and write all the 1 Million + 1 contacts again. Is there a way to just add the new contacts without having to write the whole file again. I guess reading is important as I don't want to store duplicate contacts and that would need comparison. Any other efficient approach would also be appreciated.
tagged with: python
has comment: http://stackoverflow.com/comment/91649939
downvote count: 0
has title: PyYAML file efficient management
score: 1
tagged with: pyyaml
type: Question
has comment: http://stackoverflow.com/comment/91650026
linked to: http://stackoverflow.com/q/1112343
has comment: http://stackoverflow.com/comment/91649853
has answer: http://stackoverflow.com/a/52353072
upvote count: 1
tagged with: yaml

http://stackoverflow.com/comment/91508545
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52280027
has text: @KotaMori I have tried that too - is there anything in this? files1 = [re.sub('[-()\"#/@;:<>{}`+=~|.!?,]', '', files1) for y in files1]

http://stackoverflow.com/comment/91585944
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52319222
has text: Step 1: Get a written permission to do so as requiered by their legal notice.
score: 0

http://stackoverflow.com/q/52404081
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91752023
type: UnansweredQuestion
tagged with: django
type: Question
tagged with: django-views
has comment: http://stackoverflow.com/comment/91752293
has title: Django URL, pass parameters in URL
has answer: http://stackoverflow.com/a/52404999
score: 0
answer count: 2
has body: I want to create url like: /api/foodfeeds/?keywords=BURGER,teste&amp;mood=happy&amp;location=2323,7767.323&amp;price=2 urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^api/foodfeed/(?P&lt;keywords&gt;[0-9.a-z, ]+)/(?P&lt;mood&gt;[0-9.a-z, ]+)/(?P&lt;location&gt;[0-9]+)/(?P&lt;price&gt;[0-9]+)/$', backend_views.FoodfeedList.as_view()), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) views.py class FoodfeedList(APIView): # permission_classes = (permissions.IsAuthenticated,) def get(self,request,keywords,mood,location,price): print(request.GET['keywords'])
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/91752099
has answer: http://stackoverflow.com/a/52405829
tagged with: python
has comment: http://stackoverflow.com/comment/91753656

http://stackoverflow.com/q/52322906
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91593361
score: -1
has comment: http://stackoverflow.com/comment/91593321
has body: The function see_inventory() prints the quotation marks in the for loop inside it, how do i make it so the function prints the list without the quotation marks? I am a begginer btw. class Person: equipped_armor = { "head": {"name": "cap", "defense": 1}, "chest": {"name": "mail", "defense": 2}, "legs": {"name": "wooden leggings", "defense": 1}, } gold = 10 stored_armor = {"Stored Armor: ": ["rash leggings"]} weapons = {"Weapons: ": ["wooden_sword", "mythrill_staff"]} potions = {"Potions: ": ["HP potion"]} ui_gold = {"Gold: ": gold} inv = [ stored_armor, weapons, potions, ui_gold ] def __init__(self): self.name = "Cavalex" def see_inventory(self): for element in self.inv: print(element) By running this: player = Person() player.see_inventory() I get this: {'Stored Armor: ': ['rash leggings']} {'Weapons: ': ['wooden sword', 'mythril staff']} {'Potions: ': ['HP potion']} {'Gold: ': 10}
type: Question
has answer: http://stackoverflow.com/a/52323035
has comment: http://stackoverflow.com/comment/91593294
favorite count: 0
tagged with: printing
answer count: 3
has answer: http://stackoverflow.com/a/52323795
has title: Function prints the quotation marks and the curly brackets in this for loop function in python
accepted answer: http://stackoverflow.com/a/52323035
downvote count: 2
possible better answer: http://stackoverflow.com/a/52323024
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52323024
has comment: http://stackoverflow.com/comment/91593330

http://stackoverflow.com/q/52330016
downvote count: 0
score: 7
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/52330093
has answer: http://stackoverflow.com/a/52330093
tagged with: python
has answer: http://stackoverflow.com/a/52330079
has body: I want to take a pandas dataframe, do a count of unique elements by a column and retain 2 of the columns. But I get a multi-index dataframe after groupby which I am unable to (1) flatten (2) select only relevant columns. Here is my code: import pandas as pd df = pd.DataFrame({ 'ID':[1,2,3,4,5,1], 'Ticker':['AA','BB','CC','DD','CC','BB'], 'Amount':[10,20,30,40,50,60], 'Date_1':['1/12/2018','1/14/2018','1/12/2018','1/14/2018','2/1/2018','1/12/2018'], 'Random_data':['ax','','nan','','by','cz'], 'Count':[23,1,4,56,34,53] }) df2 = df.groupby(['Ticker']).agg(['nunique']) df2.reset_index() print(df2) df2 still comes out with two levels of index. And has all the columns: Amount, Count, Date_1, ID, Random_data. How do I reduce it to one level of index? And retain only ID and Random_data columns?
answer count: 2
has comment: http://stackoverflow.com/comment/91606772
upvote count: 7
has comment: http://stackoverflow.com/comment/91608032
has title: pandas reset index after performing groupby and retain selective columns
accepted answer: http://stackoverflow.com/a/52330079
tagged with: pandas
type: AnsweredQuestion

similarity
tags question: http://stackoverflow.com/q/52388291
tags question: http://stackoverflow.com/q/52370113
tag name: similarity
type: Tag

http://stackoverflow.com/comment/91610978
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52332165
type: Comment
has text: Note that f-strings feature was added to Python 3.6, so your solution won't work with earlier versions

http://stackoverflow.com/comment/91553689
has text: This solution is great but my problem is that this command `df['YearMonth'] = df.date.dt.to_period('M')` takes infinite time and I don't know why
comment on: http://stackoverflow.com/a/52302794
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52357271
has body: Something like: parsed = [] array = ['12 1929 8827','8837 139'] for string in array: for component in string.split(' '): parsed.append(int(component)) sum = reduce(lambda a, x: a + x, parsed) Or more simply (as pointed out by @wwii): parsed = [] array = ['12 1929 8827','8837 139'] for string in array: for component in string.split(' '): parsed.append(int(component)) sum = sum(parsed) Or even more simply (also as pointed out by @wwii): accumulated = 0 array = ['12 1929 8827','8837 139'] for string in array: for component in string.split(' '): accumulated += int(component) sum = sum(parsed)
answers question: http://stackoverflow.com/q/52357217
upvote count: 1
has comment: http://stackoverflow.com/comment/91659239
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/91659186
accepted answer of: http://stackoverflow.com/q/52357217

http://stackoverflow.com/comment/91721726
type: Comment
has text: @ShadowRanger yes, I wasn't quite sure how to get the 40 character chunks without having all of the data to begin with, you are more than welcome to add your code as an answer, since it sounds like a good learning experience for anyone who may stumble upon this.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52372561

http://stackoverflow.com/comment/91698872
type: QuestionComment
score: 1
has text: @martineau thanks so much for your help. I'm halfway there trying to solve this problem now. thanks again!
comment on: http://stackoverflow.com/q/52359617
type: Comment

timer
tag name: timer
type: Tag
tags question: http://stackoverflow.com/q/52368428

http://stackoverflow.com/a/52839510
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52392999
has body: I just changed self.connection.recv(1024) to a bigger number, thus accepting more bytes. The problem was, as mentioned by @zwer, that the output of the command of "ipconfig" was bigger than 1024 bytes.
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52392999
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52271619
has answer: http://stackoverflow.com/a/52272738
favorite count: 0
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48727120
score: 1
accepted answer: http://stackoverflow.com/a/52272738
upvote count: 1
has title: Create 2D matrices from several csv files
type: Question
tagged with: numpy
has body: I'm working with Python3 and I would like to load datas from several CSV files. Each CSV (one measurement) has 3 columns (3 different physical quantities). I want to load each quantity on 3 separate variables. For one CSV file this is quite simple, I used : TIME,CH1,CH2 = loadtxt(file_path,usecols=(3,4,5),delimiter=',',skiprows=2,unpack=True) and it worked fine. Now I would like to extend this procedure so I can load several CSV files. Each array would be 2D, each column representing one CSV file. Instead of having several CSV with three variables, I will have 3 2D arrays, which is much more convenient for data analysis. I thought I could try something like this : TIME = matrix(zeros((20480,len(file_path)))) # 20480 length of each column CH1 = matrix(zeros((20480,len(file_path)))) # len(file_path) number of CSV files CH2 = matrix(zeros((20480,len(file_path)))) for k in range(0,len(file_path)): # reading each CSV file TIME[:,k],CH1[:,k],CH2[:,k] = loadtxt(file_path[k],usecols=(3,4,5),delimiter=',',skiprows=2,unpack=True) But it's telling me : ValueError: could not broadcast input array from shape (20480) into shape (20480,1) In the end I would like variables looking like this : TIME = matrix([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.], ..., [0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]) Each column is from one different CSV file. I think this is a quite usual problem, but I don't really get how arrays works in Python. I get this idea from Matlab which is quite straightforward but here I don't know why indexing arrays with TIME[:][:] doesn't work. Have you any idea how I could do this ? Thanks.
tagged with: arrays
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/91742241
type: Comment
type: AnswerComment
has text: `max(ADC * gain + offset, 0)` is what's throwing me. Why do they expect negative results?
score: 0
comment on: http://stackoverflow.com/a/52399158

http://stackoverflow.com/q/52361558
answer count: 0
has title: Segmentation fault when importing numpy and calling Fortran library
score: 0
type: UnansweredQuestion
upvote count: 1
downvote count: 1
type: Question
tagged with: cython
has comment: http://stackoverflow.com/comment/91681612
has body: This is a strange one. I am using Cython to build a Python package (let's call it mypackage) that wraps an external library (externallib). externallib is written in Fortran, but it has an interface library written in C. I use this C interface library to access externallib from Cython. The development has been going very well, up to the point when I imported numpy or any other package dependent on numpy (e.g. pint, matplotlib, pandas, etc.) into the mypackage.core module (a .pyx file). I only import these packages, and do not even use them. This results in a segmentation fault. Current thread 0x00007f02925ee740 (most recent call first): File "build/temp/mypackage/core_test.py", line 191 in _test_runner File "build/temp/mypackage/core_test.py", line 291 in test__str__ File "/home/user/anaconda3/envs/mypackage-build-python3.6.5/lib/python3.6/unittest/case.py", line 605 in run File "/home/user/anaconda3/envs/mypackage-build-python3.6.5/lib/python3.6/unittest/case.py", line 653 in __call__ File "/home/user/anaconda3/envs/mypackage-build-python3.6.5/lib/python3.6/unittest/suite.py", line 122 in run File "/home/user/anaconda3/envs/mypackage-build-python3.6.5/lib/python3.6/unittest/suite.py", line 84 in __call__ File "/home/user/anaconda3/envs/mypackage-build-python3.6.5/lib/python3.6/unittest/suite.py", line 122 in run File "/home/user/anaconda3/envs/mypackage-build-python3.6.5/lib/python3.6/unittest/suite.py", line 84 in __call__ File "/home/user/anaconda3/envs/mypackage-build-python3.6.5/lib/python3.6/unittest/runner.py", line 176 in run File "/home/user/anaconda3/envs/mypackage-build-python3.6.5/lib/python3.6/unittest/main.py", line 256 in runTests File "/home/user/anaconda3/envs/mypackage-build-python3.6.5/lib/python3.6/unittest/main.py", line 95 in __init__ File "build/temp/mypackage/core_test.py", line 311 in &lt;module&gt; ../build/scripts/build-package-linux.sh: line 151: 22796 Segmentation fault (core dumped) python3 build/temp/mypackage/core_test.py The segmentat…
tagged with: numpy
has comment: http://stackoverflow.com/comment/91667433
has comment: http://stackoverflow.com/comment/91681875
has comment: http://stackoverflow.com/comment/92020345
has comment: http://stackoverflow.com/comment/91709079
tagged with: python
has comment: http://stackoverflow.com/comment/92073363
favorite count: 0

http://stackoverflow.com/q/52289488
upvote count: 12
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52289529
tagged with: pandas
has title: Efficient way to add new column to pandas dataframe
favorite count: 0
has comment: http://stackoverflow.com/comment/91526964
score: 12
tagged with: python
type: AnsweredQuestion
has body: I know two ways of adding a new column to pandas dataframe df_new = df.assign(new_column=default_value) and df[new_column] = default_value The first one does not add columns inplace, but the second one does. So, which one is more efficient to use? Apart from these two is there is any all the more efficient method than these?
has comment: http://stackoverflow.com/comment/91526991
linked to: http://stackoverflow.com/q/12555323
has answer: http://stackoverflow.com/a/52289529
type: Question

http://stackoverflow.com/comment/91586126
score: 0
type: AnswerComment
has text: I think you may have changed something else in your Dockerfile. The change I suggested should have no effect on anything to do with Python. If Python was able to open the directory before my change, it should still be able to do so afterwards.
type: Comment
comment on: http://stackoverflow.com/a/52319035

http://stackoverflow.com/a/52376759
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52376665
answers question: http://stackoverflow.com/q/52376665
type: Answer
upvote count: 1
has body: The call to smtplib.SMTP.sendmail() does not take a subject parameter. See the doc for instructions on how to call it. Subject lines, along with all other headers, are included as part of the message in a format called RFC822 format, after the now-obsolete document that originally defined the format. Make your message conform to that format, like so: import smtplib fromx = 'xxx@gmail.com' to = 'xxx@gmail.com' subject = 'subject' #Line that causes trouble msg = 'Subject:{}\n\nexample'.format(subject) server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.ehlo() server.login('xxx@gmail.com', 'xxx') server.sendmail(fromx, to, msg) server.quit() Of course, the easier way to conform your message to all appropriate standards is to use the Python email.message standard library, like so: import smtplib from email.mime.text import MIMEText fromx = 'xxx@gmail.com' to = 'xxx@gmail.com' msg = MIMEText('example') msg['Subject'] = 'subject' msg['From'] = fromx msg['To'] = to server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.ehlo() server.login('xxx@gmail.com', 'xxx') server.sendmail(fromx, to, msg.as_string()) server.quit() Other examples are also available.
score: 1

http://stackoverflow.com/a/52338734
type: Answer
score: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52329504
accepted answer of: http://stackoverflow.com/q/52329504
downvote count: 0
has comment: http://stackoverflow.com/comment/91635462
has body: iter_rows() may be a choice for you. Please find this link for more details. from openpyxl import load_workbook wb = load_workbook('PathToFile') sht = wb['SheetName'] for row in sht.iter_rows('K1:K999'): for cell in row: cell.value = '...' wb.save('PathToFile')
upvote count: 2

http://stackoverflow.com/a/52348189
has body: You can use a really simple pattern: \b-\b \b Word boundary. - Hyphen. \b Word boundary. Regex demo here. Python demo: import re text = "one-hundered-and-three- some text foo-bar some--text" print(re.sub(r'\b-\b', ' ', text)) Prints: one hundered and three- some text foo bar some--text
type: Answer
answers question: http://stackoverflow.com/q/52347891
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/52457924
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52426831
score: 1
type: AcceptedAnswer
downvote count: 0
has body: Question: ... add the "same" data to the right, not top down like the .append method You have to use ws.append(...) anyway. First you need a Workbook Instance: from openpyxl import Workbook wb = Workbook() Don't use n1 = wb.active inside your for ... loop. You have to get the active Worksheet only once. for agreement in agreements: n1 = wb.active ws = wb.active You want to add x Header per Row to the right, so you can't use .append(...). n1.append(['Account Number', 'Account Name', 'Total DKK',]) Before you .append(...) your Row Column Values, you have to create a List with your expected Values. For example: HEADER = ['Account Number', 'Account Name','Total DKK'] listOfColumnValues = [] # Extend listOfColumnValues with HEADER as many times you need for _ in range(3): listOfColumnValues.extend(HEADER) print("{}".format(listOfColumnValues)) ws.append(listOfColumnValues) Output: ['Account Number', 'Account Name', 'Total DKK', 'Account Number', 'Account Name', 'Total DKK', 'Account Number', 'Account Name', 'Total DKK'] Tested with Python:3.4.2 - openpyxl:2.4.1 - LibreOffice:4.3.3.2
type: Answer
answers question: http://stackoverflow.com/q/52426831

http://stackoverflow.com/comment/91516303
type: QuestionComment
score: 0
has text: Did you try the answer provided on the link of MWE you shared?
comment on: http://stackoverflow.com/q/52284040
type: Comment

http://stackoverflow.com/comment/91790595
comment on: http://stackoverflow.com/q/52423873
score: 0
type: QuestionComment
type: Comment
has text: Do you have any way to tell if a date is DD-MM-YYYY or MM-DD-YYYY? Any indicator in the other columns in the Excel file?

http://stackoverflow.com/comment/91738715
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/52396634
has text: Possible duplicate of [How to stop IntelliJ truncating output when I run a build?](https://stackoverflow.com/questions/7836313/how-to-stop-intellij-truncating-output-when-i-run-a-build)

http://stackoverflow.com/comment/91638834
type: Comment
has text: Possible duplicate of [count the frequency that a value occurs in a dataframe column](https://stackoverflow.com/questions/22391433/count-the-frequency-that-a-value-occurs-in-a-dataframe-column)
comment on: http://stackoverflow.com/q/52346617
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91644352
score: 1
type: AnswerComment
has text: Currently, `groupby/first` returns the first non-NaN value for each group. But I'm not sure if we should rely on it, as the head developer seems to [possibly consider this a bug](https://github.com/pandas-dev/pandas/issues/8427).
type: Comment
comment on: http://stackoverflow.com/a/52349533

http://stackoverflow.com/comment/91581483
type: Comment
has text: [This](https://ibb.co/meXUEp) is the output of the script if you pass `cmap='RdYlBu'` to `ax.imshow()` for example, the values closer to zero are now represented in yellow.
comment on: http://stackoverflow.com/a/52313584
type: AnswerComment
score: 0

http://stackoverflow.com/q/52317856
has title: Python - Returning Exception in unittest
accepted answer: http://stackoverflow.com/a/52318293
type: AnsweredQuestion
tagged with: unit-testing
type: Question
possible better answer: http://stackoverflow.com/a/52318037
has answer: http://stackoverflow.com/a/52318037
tagged with: tdd
has answer: http://stackoverflow.com/a/52318293
answer count: 2
score: 0
has body: im starting to learn TDD and got the Bowling Game kata as exercise. I have completed some of the regular score test, but i want to add more just to practice and one idea was to raise an exception if i roll a negative number. The hole code is not relevant because this is a simple validation class BowlingGame(object): def __init__(self): pass def roll(self, pins): if pins &lt; 0: #Want to Return Value Exception class BowlingGameTest(unittest.TestCase): def setUp(self): self._game = BowlingGame() def test_roll_negative(self): self.game.roll(-1) #Want to catch exception here with self.assert or except The problem is that if i return for example 0/0 the exception is raised in the BowlingGame class and not in the BowlingGameTest class (there are in two diferent files). If i do return ValueError (BowlingGame Class) with self.assertRaises(ValueError): (BowlingGameTest Class) i got AssertionError: ValueError not raised Any ideas?
tagged with: python

http://stackoverflow.com/comment/91743568
type: Comment
has text: Here's an example to start (didn't test it): https://gist.github.com/domibarton/df2b7d1135c49dc99622283645f88478 You might want to read the docs, as it has a lot of code snippets / examples. Have a look at templates, static files & file uploads :)
score: 1
comment on: http://stackoverflow.com/a/52399727
type: AnswerComment

http://stackoverflow.com/comment/91780129
has text: i.e. I have a total population of 50 of which it contains 3 sub_pop each normally distributed differently. so wad I want to do is generate random samples from each of these 3 sub_pop and then add the results into the list "group_all"
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52417487
type: Comment

http://stackoverflow.com/q/52309515
downvote count: 1
has answer: http://stackoverflow.com/a/52309955
has body: I have two dictionaries- selected candidates and rejected candidates. the structure is like as shown below- selected={"name":score} #same for rejected I want to show selected candidates in the green and rejected candidates in red. How can I do that? I have tried this way but it is giving me some absurd result: #Husain Shaikh #test 3 matplotlib import matplotlib.pyplot as plt selected={"Husain":92, "Asim":65,"Chirag": 74 } rejected={"Absar":70,"premraj":57} plt.bar(range(len(selected)),list(selected.values()),color="green") plt.xticks(range(len(selected)),list(selected.keys())) plt.bar(range(len(rejected)),list(rejected.values()),color="red") plt.xticks(range(len(rejected)),list(rejected.keys())) plt.xlabel("Candidates") plt.ylabel("Score") plt.plot() plt.show()
tagged with: matplotlib
has title: Change the colour of individual bars in matplotlib?
type: Question
answer count: 2
upvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52311205
tagged with: python
tagged with: dictionary
score: -1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91567516
type: UnansweredQuestion

http://stackoverflow.com/comment/91745109
comment on: http://stackoverflow.com/a/52399247
type: AnswerComment
score: 0
type: Comment
has text: if test_function requires the internet connection check then yes.

http://stackoverflow.com/a/52279846
has comment: http://stackoverflow.com/comment/91510764
has comment: http://stackoverflow.com/comment/91507780
has body: This is the best I've got: if your data is on a pandas.DataFrame called df you can do: df2 = df.unstack() start = pd.Timestamp('01/01/2013') df2 = df2.reset_index() df2['date'] = [start + pd.DateOffset(days = int(x)-1) for x in df2.level_0.values] df2['date'] += pd.to_timedelta(df2.level_1, unit='h') df2.index = df2.date df2 = df2[0] Result date 2013-01-24 00:00:00 0,3818 2013-01-24 01:00:00 0,17802 2013-01-24 02:00:00 0,22356 2013-01-24 03:00:00 0,1771 2013-01-24 04:00:00 0,19389 2013-01-24 05:00:00 0,20401 2013-01-24 06:00:00 0,18354 2013-01-24 07:00:00 0,46184 2013-01-24 08:00:00 0,43838 2013-01-24 09:00:00 0,78292 2013-01-24 10:00:00 1,81792 2013-01-24 11:00:00 2,40833 2013-01-24 12:00:00 1,55746 2013-01-24 13:00:00 1,2075 2013-01-24 14:00:00 2,4196 2013-01-24 15:00:00 0,95979 2013-01-24 16:00:00 0,51681 2013-01-24 17:00:00 0,46529 2013-01-24 18:00:00 0,58328 2013-01-24 19:00:00 1,40185 2013-01-24 20:00:00 0,71484 2013-01-24 21:00:00 0,48576 2013-01-24 22:00:00 0,04278 2013-01-24 23:00:00 0,07291 2013-01-25 00:00:00 0,0713
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52279702
score: 1
answers question: http://stackoverflow.com/q/52279702
has comment: http://stackoverflow.com/comment/91507744
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91543322
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52297395
has text: Or better yet, try running scrapy with python3, e.g. `python3 -m scrapy crawl event -o items_new.csv`
score: 0

http://stackoverflow.com/q/52429410
has comment: http://stackoverflow.com/comment/91804969
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/91804763
has comment: http://stackoverflow.com/comment/91804445
upvote count: 5
has comment: http://stackoverflow.com/comment/91802877
score: 5
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/53717374
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91803277
has body: Made a request on the above Wikipedia page. Specifically I need to scrape "results matrix" from https://en.wikipedia.org/wiki/2017%E2%80%9318_La_Liga#Results selectedSeasonPage = requests.get('https://en.wikipedia.org/wiki/2017–18_La_Liga', features='html5lib') Doing pprint.pprint(selectedSeasonPage.text) and jumping to source code of matrix, it can be seen it's incomplete. Snippet of HTML returned by requests.get() : &lt;table class="wikitable plainrowheaders" style="text-align:center;font-size:100%;"&gt; . . &lt;th scope="row" style="text-align:right;"&gt;&lt;a href="/wiki/Deportivo_Alav%C3%A9s" title="Deportivo Alavés"&gt;Alavés&lt;/a&gt;&lt;/th&gt; &lt;td style="font-weight: normal;background-color:transparent;"&gt;— &lt;/td&gt; &lt;td style="white-space:nowrap;font-weight: normal;background-color:transparent;"&gt;&lt;/td&gt; &lt;td style="white-space:nowrap;font-weight: normal;background-color:transparent;"&gt;&lt;/td&gt; &lt;td style="white-space:nowrap;font-weight: normal;background-color:transparent;"&gt;&lt;/td&gt; &lt;td style="white-space:nowrap;font-weight: normal;background-color:transparent;"&gt;&lt;/td&gt; &lt;td style="white-space:nowrap;font-weight: normal;background-color:transparent;"&gt;&lt;/td&gt; &lt;td style="white-space:nowrap;font-weight: normal;background-color:#BBF3FF;"&gt;2–1&lt;/td&gt; HTML returned by requests.get() viewed through browser and as expected its not complete. Can check this image for reference. Snippet from view-source and the output needed. &lt;table class="wikitable plainrowheaders" style="text-align:center;font-size:100%;"&gt; . . &lt;a href="/wiki/Deportivo_Alav%C3%A9s" title="Deportivo Alavés"&gt;Alavés&lt;/a&gt;&lt;/th&gt; &lt;td style="font-weight: normal;background-color:transparent;"&gt;&amp;#8212;&lt;/td&gt; &lt;td style="white-space:nowrap;font-weight: normal;background-color:#BBF3FF;"&gt;3–1&lt;/td&gt; &lt;td style="white-space:nowrap;font-weight: normal;background-color:#FFBBBB;"&gt;0–1&lt;/td&gt; &lt;td style=…
accepted answer: http://stackoverflow.com/a/53717374
tagged with: python
type: AnsweredQuestion
has title: Python requests.get() returns broken source code instead of expected source code?

http://stackoverflow.com/q/52342217
has answer: http://stackoverflow.com/a/52342260
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52342436
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/52342268
score: 0
has comment: http://stackoverflow.com/comment/91630911
answer count: 3
tagged with: matrix
upvote count: 1
has title: Reverse rows of n*n matrix
downvote count: 1
favorite count: 0
has body: I have a matrix [[1 2 3],[4,5,6],[7,8,9]] How can I reverse it horizontally so it become [[3 2 1],[6,5,4],[9,8,7]]
tagged with: python-3.x

http://stackoverflow.com/comment/91796151
has text: thanks. but it counts 2 tp! there is only one tp. so maybe you should delete the counted records as shown in the question. Also fn should be 2 not 1. thanks
type: AnswerComment
comment on: http://stackoverflow.com/a/52426112
score: 0
type: Comment

http://stackoverflow.com/comment/91559248
has text: Understood. My understanding was incorrect. Is there any functionality which I can use to get the outcome I am looking for?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52305499

http://stackoverflow.com/comment/91668290
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52361128
has text: wait i'll upload an image
score: 0

http://stackoverflow.com/comment/91743426
has text: `'{:04b}'.format(12)` converts `12` to a binary string with leading zeroes up to 4 characters: `'1100'`. you get that part for free...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52399704

http://stackoverflow.com/a/58278394
score: 2
downvote count: 0
has body: Remove the region from the connection information and specify 'account='abc.us-east-1'. The region field is being deprecated and should not be used in connections to Snowflake. https://docs.snowflake.net/manuals/user-guide/nodejs-driver-use.html#establishing-a-connection
upvote count: 2
answers question: http://stackoverflow.com/q/52429553
type: Answer

http://stackoverflow.com/q/52306300
tagged with: flask
favorite count: 0
tagged with: eventlet
tagged with: python
score: 2
upvote count: 2
type: UnansweredQuestion
has title: python Flask SocketIO throwing SSL error with eventlet
tagged with: flask-socketio
has answer: http://stackoverflow.com/a/57918809
type: Question
has body: I am running this python code where I am trying to run a socketio flask application and passing ssl certificate files: from flask import Flask, render_template, request, session, Markup, current_app, jsonify from flask_socketio import emit, SocketIO import eventlet from flask_babel import gettext app = Flask(__name__) app.config['SECRET_KEY'] = '123' app.config['FILEDIR'] = 'static/_files/' socketio = SocketIO(app) if __name__ == '__main__': try: app_host = os.environ.get('APP_HOST') app_port = os.environ.get('APP_PORT') eventlet.wsgi.server(eventlet.wrap_ssl(eventlet.listen((app_host, int(app_port))),certfile ='selfsigned.crt', keyfile = 'selfsigned.key',server_side = True),app) except Exception as e: logger.error(e) When I run this code it throws following SSL error: (21755) wsgi starting up on https://12.34.56.78:5000 (21755) accepted ('12.34.56.79', 50021) Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/eventlet/hubs/hub.py", line 458, in fire_timers timer() File "/usr/local/lib/python3.6/site-packages/eventlet/hubs/timer.py", line 58, in __call__ cb(*args, **kw) File "/usr/local/lib/python3.6/site-packages/eventlet/greenthread.py", line 218, in main result = function(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/eventlet/wsgi.py", line 781, in process_request proto.__init__(conn_state, self) File "/usr/local/lib/python3.6/site-packages/eventlet/wsgi.py", line 335, in __init__ self.handle() File "/usr/local/lib/python3.6/site-packages/eventlet/wsgi.py", line 368, in handle self.handle_one_request() File "/usr/local/lib/python3.6/site-packages/eventlet/wsgi.py", line 397, in handle_one_request self.raw_requestline = self._read_request_line() File "/usr/local/lib/python3.6/site-packages/eventlet/wsgi.py", line 380, in _read_request_line return self.rfile.readline(self.server.url_length_limit) File "/usr/local/lib/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b) File "/usr/local/lib/python3.6…
answer count: 1
downvote count: 0

system-calls
type: Tag
tags question: http://stackoverflow.com/q/52378927
tag name: system-calls

http://stackoverflow.com/comment/92337173
has text: but in the code above, minX and minY were not included in the function below. Based on maxXY = max(maxX, maxY), I think your idea is to get the widest bound. So it is supposed to be maxXY = max(maxX, maxY, minX, minX), where minX and minY need to be absolute.
type: Comment
comment on: http://stackoverflow.com/a/52357822
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91572109
type: AnswerComment
type: Comment
has text: @lightalchemist you are correct. I read the comment above which stated `as myDataInstance.value is a reference to x` whereas in fact, in the example provided, it is not. Updated the answer accordingly.
comment on: http://stackoverflow.com/a/52311527
score: 0

http://stackoverflow.com/a/52399332
score: 1
upvote count: 1
has body: I had a same question and i have tried below code and it worked for me :- import glob import pytesseract import os os.chdir("Set your Tesseract-OCR .exe file path") b = '' for i in glob.glob('Fullpath of your image directory/*.tif'): &lt;-- you can give *.jpg extension in case of jpg image if glob.glob('*.tif'): b = b + (pytesseract.image_to_string(i)) print(b) Happy learning !
answers question: http://stackoverflow.com/q/52350619
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91597408
score: 0
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/180036/discussion-between-mohamed-thasin-ah-and-pes04).
type: AnswerComment
comment on: http://stackoverflow.com/a/52324987

http://stackoverflow.com/comment/91626661
type: QuestionComment
comment on: http://stackoverflow.com/q/52334783
has text: @OzzyWalsh please see my method above, doing it this way is a lot easier than editing my configuration in nginx using pycharm and it auto-reloads for me when I make changes and serves the new scripts. Otherwise I have to restart services by cli which takes some time.
score: 0
type: Comment

http://stackoverflow.com/comment/91723855
score: 0
has text: Try using `request.json()` instead of `request.content`
type: Comment
comment on: http://stackoverflow.com/q/52384096
type: QuestionComment

http://stackoverflow.com/a/52404129
has body: Go to Custom Fields screen. Then go to the Market custom field and click in the Configure option in the right. You will navigate to a screen with this kind of url http://localhost:8080/jira/secure/admin/ConfigureCustomField!default.jspa?customFieldId=10406 The custom field id is in this case customfield_10406.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52385888
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52385888

http://stackoverflow.com/a/52377974
answers question: http://stackoverflow.com/q/52366296
downvote count: 0
has comment: http://stackoverflow.com/comment/91752189
has comment: http://stackoverflow.com/comment/91744472
score: 3
has comment: http://stackoverflow.com/comment/91710221
upvote count: 3
has comment: http://stackoverflow.com/comment/91761534
has body: You have overwrite the list method, so it's not working to work call the filter_queryet method. def list(self, request, *args, **kwargs): """ Method for Post listing. It can be accessed by anyone. """ serializer = PostListSerializer(self.filter_queryset(self.get_queryset()), many=True, context= . {"request": request}) return Response(serializer.data)
type: Answer

http://stackoverflow.com/q/52366158
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: django-views
has title: Django form is not saving image file
has body: In this webapp I have a question model and a question diagram model. Whenever the user uploads an image, it is supposed to be saved in media/question_image folder. It is working fine if I upload from the admin panel, but when I upload the image from webpage it is not getting saved. Fact is, the post request is working and I don't get any kind of error. The image is not getting saved at its desired place. Here is all my codes: model.py class QuestionDiagram(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='questionDiagrams') user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) question_diagram = models.ImageField(upload_to='question_diagram/') question_diagram_text = models.CharField(max_length = 48) date = models.DateTimeField(auto_now_add=True, blank=True, null=True) forms.py class QuestionDiagramForm(forms.ModelForm): question_diagram = forms.CharField(widget = forms.FileInput(attrs={'class':'questionDiagram-questionDiagram'})) question_diagram_text = forms.CharField(widget = forms.Textarea(attrs={'class':'questionDiagram-questionDiagramText', 'placeholder':'Describe', 'maxlength':'48'})) class Meta: model = QuestionDiagram fields = ['question_diagram', 'question_diagram_text'] settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') in project urls.py (added mediaroot and mediaurl) ...... if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py class QuestionDiagramView(View): form_class = QuestionDiagramForm template_name = 'mechinpy/question_diagram.html' def get(self, request, slug): form = self.form_class(None) return render(request, self.template_name, {'form':form}) def post(self, request, slug): question = get_object_or_404(Question, slug=slug) form = self.form_class(request.POST, request.FILES) if form.is_valid(): questiondiagram = form.save(commit=False) questiondiagram.user = self.request.user questiondiagram.quest…
tagged with: django-forms
type: Question
has answer: http://stackoverflow.com/a/52366299
tagged with: django-2.1
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52366299
upvote count: 2
tagged with: django

http://stackoverflow.com/q/52381723
type: AnsweredQuestion
has title: Why does Python pandas read_csv not work when combined with other functions
has body: Python pandas read_csv gives correct output when written individually like this: import pandas as pd def bgp_neighbor_status(): data = pd.read_csv('E:\\Python-Scripts\\bgp-result.txt', delim_whitespace=True, header=None) for index, row in data.iterrows(): if row[9] == 'Down' or row[9] == 'Idle' or row[9] == 'Active': print(f"Neighbor {row[0]} is down") else: pass bgp_neighbor_status() Output which is showing as expected: Neighbor 10.0.11.101 is down However, when I combine the same function with another function like this I am getting the error:- pandas.errors.EmptyDataError: No columns to parse from file from __future__ import print_function from netmiko import ConnectHandler import pandas as pd import sys import time import select import paramiko import re bgp_result_file = open(r'E:\\Python-Scripts\\bgp-result.txt','w') old_stdout = sys.stdout sys.stdout = bgp_result_file platform = 'cisco_ios' username = 'javed' password = 'cisco' ip_add_file = open(r'E:\\Python-Scripts\\IPAddressList.txt', 'r') def check_bgp(ip_add_file): for host in ip_add_file: host = host.rstrip('\n') connect = ConnectHandler(device_type=platform, ip=host, username=username, password=password) output = connect.send_command('terminal length 0') output = connect.send_command('enable') bgp_status = connect.send_command('show ip bgp summary | be N') print (bgp_status) def bgp_neighbor_status(): data = pd.read_csv('E:\\Python-Scripts\\bgp-result.txt', delim_whitespace=True, header=None) for index, row in data.iterrows(): if row[9] == 'Down' or row[9] == 'Idle' or row[9] == 'Active': print(f"Neighbor {row[0]} is down") else: pass check_bgp(ip_add_file) bgp_neighbor_status()
type: Question
answer count: 1
score: 0
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/91707735
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52381770
accepted answer: http://stackoverflow.com/a/52381770

http://stackoverflow.com/comment/91595015
score: 0
type: Comment
type: QuestionComment
has text: Oh, thanks. I fixed it now.
comment on: http://stackoverflow.com/q/52323906

http://stackoverflow.com/comment/91727088
has text: @pault - yeah makes sense the more I read about limit. The documentation is a little light and I didn't think about it till after but... is this because of the lazy execution? So every time I run .count().collect() it goes back and reruns the .limit(2000) and pulls a new dataframe?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52389487
score: 0

http://stackoverflow.com/q/52290482
has title: How can i retrieve the output shown on my command line using python?
type: AnsweredQuestion
score: 2
linked to: http://stackoverflow.com/q/4408377
type: Question
has answer: http://stackoverflow.com/a/52290545
linked to: http://stackoverflow.com/q/4760215
downvote count: 0
answer count: 1
tagged with: python
tagged with: shell
has comment: http://stackoverflow.com/comment/91528803
favorite count: 0
tagged with: python-3.x
has body: Using ubuntu 16.04 what i want is to retrieve the output on terminal using python, i did refer to these 2 links : How can I get terminal output in python? Running shell command from Python and capturing the output but being a starter in python i couldn't make it work, my original code which output i want: for element in my_images: os.system('you-get -o videos ' + element) how my code became : for element in my_images: # value = os.system('you-get -o videos ' + element) output = subprocess.Popen(os.system('you-get -o videos ' + element), stdout=subprocess.PIPE).communicate()[0] print(output) but it didn't work i get this error Traceback (most recent call last): File "main_twitter.py", line 29, in &lt;module&gt; output = subprocess.Popen(os.system('you-get -o videos ' + element), stdout=subprocess.PIPE).communicate()[0] File "/usr/local/lib/python3.6/subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "/usr/local/lib/python3.6/subprocess.py", line 1220, in _execute_child args = list(args) TypeError: 'int' object is not iterable
accepted answer: http://stackoverflow.com/a/52290545
tagged with: subprocess
upvote count: 2

http://stackoverflow.com/q/52273117
type: Question
has answer: http://stackoverflow.com/a/52274879
has body: I'm working on project based on project built at Arduino microcontroller and Raspberry Pi computer: Arduino measures time from the moment when program loop starts. It stops when the user push button. This score is going to be sent via serial port to specially prepared csv file. The same time update() function is going to take out values from this file and plot live graph and histogram. The problem started, when just one function was executed when the script was running. I've checked some options and decided to try the threading: https://docs.python.org/3/library/threading.html https://docs.python.org/2/library/threading.html https://www.tutorialspoint.com/python/python_multithreading.htm However it compiles, but not executes properly. I don't ask for ready code or links - just suggestion or some tip would be really helpfull: import pandas as pd import matplotlib.pyplot as plt import matplotlib.animation as animation import serial import datetime import threading fig, axes = plt.subplots(nrows=2, ncols=1) ax1, ax2 = axes.flatten() scores_to_read = serial.Serial ('/dev/ttyACM0', 9600) file = open ("/home/pi/Desktop/Noc_Naukowcow/score_board.csv", 'r+') def update(i): file_data = pd.read_csv("/home/pi/Desktop/Noc_Naukowcow/score_board.csv", delimiter="\t", parse_dates=[0], header=None, usecols=[0, 1]) ax1.clear() ax2.clear() ax1.plot(file_data[0],file_data[1]) ax2.hist([file_data[1],], bins='auto', histtype='bar') #ax1.set_title('History') ax1.set_xlabel('Measurement time') ax1.set_ylabel('Reaction time [s]') #ax2.set_title('Histogram') ax2.set_xlabel('Reaction time [s]') ax2.set_ylabel('Number of results') ani = animation.FuncAnimation(fig, update, interval=1000) plt.plot() def serial_port(file): file.read() new_score = scores_to_read.readline() print(new_score) score = new_score.decode('utf-8').strip() + "\n" score_time = '{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()) file.write(score_time) file.write('\t') file.write(score) file.flush() thread1 = threading.T…
score: 0
tagged with: raspberry-pi
answer count: 1
tagged with: python
type: AnsweredQuestion
tagged with: multithreading
has title: How to make serial port and matplotlib working in the same Python scrypt
accepted answer: http://stackoverflow.com/a/52274879

http://stackoverflow.com/q/52361198
has comment: http://stackoverflow.com/comment/91686676
has body: I am willing to concatenate two file on line basis, so that every line of each file is merged consecutively in a third file. So I have the following code and the following text files: file1.txt 1 3 5 7 file2.txt 2 4 6 code: from ast import literal_eval def merge_lines(): with open("file1.txt") as f1, open("file2.txt") as f2: with open("file3.txt", "r+") as tfile: f1_lists = (literal_eval(line) for line in f1) f2_lists = (literal_eval(line) for line in f2) for l1, l2 in zip(f1_lists, f2_lists): tfile.write(str(l1)) tfile.write("\n") tfile.write(str(l2)) tfile.write("\n") combine_hands() This works just fine as the output file looks likes: file3.txt 1 2 3 4 5 6 My question is why the last line (number 7) of the file1.txt is not being merged?
possible better answer: http://stackoverflow.com/a/52361305
has answer: http://stackoverflow.com/a/52361305
has answer: http://stackoverflow.com/a/52361233
type: Question
accepted answer: http://stackoverflow.com/a/52361232
has comment: http://stackoverflow.com/comment/91666762
score: 0
tagged with: concatenation
has answer: http://stackoverflow.com/a/52361645
has title: Python concatenation/merging one line from one file at the time
tagged with: python
tagged with: merge
answer count: 4
has answer: http://stackoverflow.com/a/52361232
has comment: http://stackoverflow.com/comment/91666738
type: AnsweredQuestion

http://stackoverflow.com/comment/91729471
has text: Please make sure that the folder and file exist **on the server** and that the account used for automation has access to it.
comment on: http://stackoverflow.com/q/52375050
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91711842
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52383893
has text: It is called boolean indexing : https://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing

http://stackoverflow.com/comment/91737415
has text: I got it the rest of the way, thanks to you.. adding my slight variation to question for others
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52395932
score: 0

http://stackoverflow.com/comment/91770983
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52413581
has text: What is `RET` in your dataframes?

http://stackoverflow.com/q/52345699
tagged with: tensorflow-lite
score: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/55760214
downvote count: 0
has answer: http://stackoverflow.com/a/52444938
accepted answer: http://stackoverflow.com/a/55760214
answer count: 2
tagged with: deep-learning
possible better answer: http://stackoverflow.com/a/52444938
has title: How can you identify Input and Output name in tensorboard graph like this one in the pictures attached to this post?
tagged with: tensorboard
favorite count: 0
upvote count: 1
tagged with: python
has body: I used the MobileNet_v1_1.0_224 tensorflow model for object detection. Now, I have my custom frozen graph (.pb file) that I need to convert to tflite extension so that I can use my model for mobile devices. Can someone help me to identify the input and the output names in this tensorboard graph? I need them to use as input and output parameters to convert my frozen graph (.pb file) to tensorflow lite (.tflite) file graph from tensorboard same graph
type: AnsweredQuestion

http://stackoverflow.com/comment/91714635
type: Comment
comment on: http://stackoverflow.com/a/52371589
has text: It's normal I think. The loop is on 20 000 items but it's on Informix object. I do query on Informix database and I think it takes 47 sec cause of this
type: AnswerComment
score: 0

http://stackoverflow.com/a/52342604
score: 1
has comment: http://stackoverflow.com/comment/91632588
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52342507
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52342507
has body: To select only tr without class try to replace rows = offense_table.tbody.findAll("tr") by rows = offense_table.findAll("tr", attrs={'class': None})

http://stackoverflow.com/a/59462089
accepted answer of: http://stackoverflow.com/q/52360965
type: Answer
answers question: http://stackoverflow.com/q/52360965
score: 2
type: AcceptedAnswer
downvote count: 0
has body: A general solution for this is to use the labelOrient option of the header parameter: df = df[df.date.dt.year &lt; 2014] # make a smaller chart alt.Chart(df).mark_rect().encode( alt.Y('month(date):O', title='day'), alt.X('date(date):O', title='month'), color='temp_max:Q' ).facet( row=alt.Row('year(date):N', header=alt.Header(labelOrient='top')) )
upvote count: 2

http://stackoverflow.com/comment/91669304
type: Comment
score: 1
has text: A couple of things occur to me: find out whether the part of your algorithm taking up the time is the recursive iteration or the regex matching combined with word stem calculation; if it is the latter, then can you pre-calculate canonical forms for your matching words? You also seem to need to invert your dictionary: make the key_list the top key. Pandas can do the equivalent of this (pivot the multidimensional table), but if your industry_data dict is not too large, then can you do it in native Python?
type: QuestionComment
comment on: http://stackoverflow.com/q/52361783

http://stackoverflow.com/a/52397461
score: 4
type: Answer
answers question: http://stackoverflow.com/q/52391451
has body: I think you could add some code like this. import plotly.offline as py import plotly.graph_objs as go labels = ['Alice','Bob','Carl'] vals = [2,5,4] data = [go.Bar(x=vals, y=labels, orientation='h')] layout = dict(yaxis=dict(ticksuffix=" ")) fig = go.Figure(data=data,layout=layout) py.iplot(fig) add a suffix will fix this problem easily. I have checked the reference plotly ref, it also have more suitable key named tickformat, but it hard to use so I didn't use it.
upvote count: 5
downvote count: 1

http://stackoverflow.com/comment/91666040
type: QuestionComment
comment on: http://stackoverflow.com/q/52360438
type: Comment
has text: Which of the Firestore [documented limits](https://firebase.google.com/docs/firestore/quotas) do you think you're running into? Are you suggesting the count is different when you perform the update as opposed to leaving it commented out as you show now?
score: 0

http://stackoverflow.com/a/52345385
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52343245
answers question: http://stackoverflow.com/q/52343245
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/111786367
upvote count: 6
score: 5
has body: The easiest way to do this is with the discord.ext.commands extension. Here we use a converter to get the target user, and a keyword-only argument as an optional message to send them: from discord.ext import commands import discord bot = commands.Bot(command_prefix='!') @bot.command(pass_context=True) async def DM(ctx, user: discord.User, *, message=None): message = message or "This Message is sent via DM" await bot.send_message(user, message) bot.run("TOKEN") For the newer 1.0+ versions of discord.py, you should use send instead of send_message from discord.ext import commands import discord bot = commands.Bot(command_prefix='!') @bot.command() async def DM(ctx, user: discord.User, *, message=None): message = message or "This Message is sent via DM" await user.send(message) bot.run("TOKEN")

http://stackoverflow.com/comment/91738966
comment on: http://stackoverflow.com/q/52397168
score: 0
type: QuestionComment
type: Comment
has text: Perhaps you should not name your function `pow` as it is a built-in function

http://stackoverflow.com/q/52417076
type: Question
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52417360
tagged with: python-3.x
has title: Tables of multiples in Python
type: UnansweredQuestion
tagged with: python
has body: I would like to print a table that print rows*columns in that many rows and columns, with the beginning of each column incrementing by one and that row being multiples of the first number. For example: table(3,4) 1 2 3 4 2 4 6 8 3 6 9 12 Here is my code so far. It's currently going by ones, and I don't know how to make each row be a multiple of the first number. Thank you. def table(rows, columns): for i in range(rows): print(*range(1+i*columns, 1+(i+1)*columns)) for h in range(rows%rows): print(*range(1+h*columns%rows, 1+(h+1)*columns))
score: 1
upvote count: 3
downvote count: 2

http://stackoverflow.com/a/52299186
has comment: http://stackoverflow.com/comment/91571513
has comment: http://stackoverflow.com/comment/91568251
downvote count: 0
has comment: http://stackoverflow.com/comment/91558867
has comment: http://stackoverflow.com/comment/91570916
has comment: http://stackoverflow.com/comment/91571389
has comment: http://stackoverflow.com/comment/91568324
has comment: http://stackoverflow.com/comment/91558815
answers question: http://stackoverflow.com/q/52298676
has comment: http://stackoverflow.com/comment/91575121
has comment: http://stackoverflow.com/comment/91570882
type: Answer
has comment: http://stackoverflow.com/comment/91568311
has body: I'd suggest you use select instead of find in order to make a query more similar to a browser's css selectors. This way you could just get all the inner texts in the same list and work from there. Something similar to this should help: # import libraries import json import urllib2 from bs4 import BeautifulSoup # specify the url quote_page = 'http://www.hujjat.org/' # query the website and return the html to the variable 'page' page = urllib2.urlopen(quote_page) # parse the html using beautiful soap and store in variable 'soup' soup = BeautifulSoup(page, 'html.parser') table = soup.find("div",class_="NamaazTimeName", text="Fajr").find_previous("table") texts = [x.text for x in table.select("td.NamaazTimes div")] only_times = [texts[x+1] for x in range(0, len(texts), 2)] # we'll open the file in a with block, so we don't need to close it with open("foo.txt", "w") as fp: # you'll need to iterate each string for row in only_times: fp.write(row + "\n") EDIT(2): Re-phrased my comments in the code EDIT(3): Did some sode cleanup and changed to only store the times.
score: 1
has comment: http://stackoverflow.com/comment/91571519
has comment: http://stackoverflow.com/comment/91556403
upvote count: 1
has comment: http://stackoverflow.com/comment/91571629
has comment: http://stackoverflow.com/comment/91573422
has comment: http://stackoverflow.com/comment/91570901

http://stackoverflow.com/comment/91637463
type: QuestionComment
comment on: http://stackoverflow.com/q/52345293
type: Comment
has text: @JamesKPolk I will, however try out installing rng-tools as stated in the link... will post an update in a while.
score: 0

http://stackoverflow.com/comment/91639774
has text: What is your index? `emp_id`? In other words, how do you tell which rows to match?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52347052

http://stackoverflow.com/comment/91625618
type: Comment
comment on: http://stackoverflow.com/a/52339035
score: 0
type: AnswerComment
has text: If you have a truth table, use grouping like above to see which values are independent. In most practical cases you shouldn't need a truth table, as ideally the functions should be self explanatory. `a` would be `isCleanData` and `func1()` `CleanData()` so we get `if not isCleanData(): CleanData()` which makes sense without having to produce a truth table if the next step requires clean data.

http://stackoverflow.com/q/52272170
has answer: http://stackoverflow.com/a/52275717
type: Question
has title: Create index with collation
tagged with: alembic
answer count: 1
downvote count: 0
score: 1
has body: I want to create an index in alembic which will be similar to this: CREATE INDEX my_index ON tab(columnA DESC, columnB COLLATE "da_DK" ASC, id DESC); I know that I can do something like: op.create_index('my_index', 'tab', ['columnA', 'columnB']) but I don't know how I can pass collate option.
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 1
tagged with: sqlalchemy

http://stackoverflow.com/q/52423288
has comment: http://stackoverflow.com/comment/91789583
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52423476
type: UnansweredQuestion
has body: I am using following regular expression for matching function. FINDFUNC_RE = re.search('^\s*(?:(?:inline|static)\s+){0,2}(?!else|typedef|return)\w+\s+\*?\s*(\w+)\s*\([^0]+\s*?', Line) It correctly matches if line is like this: static int abc(int a) But it does not matches if the line is like this (contains * after return type): static int* abc(int a) What can I do in the regex so that it should match both strings?
tagged with: python
has comment: http://stackoverflow.com/comment/91789751
tagged with: regex
score: -1
has title: Regular expression for following requirement
downvote count: 1
type: Question

http://stackoverflow.com/comment/91989860
comment on: http://stackoverflow.com/q/52336996
type: Comment
has text: was my answer helpful?
score: 0
type: QuestionComment

http://stackoverflow.com/q/52373527
answer count: 2
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/52373739
has answer: http://stackoverflow.com/a/52374094
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/91691762
tagged with: python
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/52373739
tagged with: web-scraping
type: Question
has title: Scrape values inside span class HTML with beautifulsoup python
accepted answer: http://stackoverflow.com/a/52374094
has body: I am trying to scrape data inside a span class and putting that data inside a DataFrame using Beautifulsoup. So far, I've been successful at getting to the right place of the webpage. But can't seem to be able to scrape the keywords and numbers next to "Happiness", "Sadness". More stats, More stats Would be super helpful if someone could help me figure out to scrape all numbers next to Happiness and Sadness, and have them as columns in a pandas DataFrame. Thanks a lot

http://stackoverflow.com/comment/91544854
type: Comment
has text: Wikipedia is a good starting point, and I did mention the extended euclidean algorithm which you can enter into your favorite search engine and find a wealth of information.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52291007

http://stackoverflow.com/comment/91619289
score: 2
has text: Use a [defaultdict](https://docs.python.org/3.7/library/collections.html)?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52336100

http://stackoverflow.com/q/52392375
upvote count: 1
has comment: http://stackoverflow.com/comment/91731671
answer count: 1
has answer: http://stackoverflow.com/a/52394364
has title: keeping smileys/emoticons while removing special characters using regex python
tagged with: special-characters
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/52394364
tagged with: python
tagged with: regex
has body: I am using the following code for cleaning my text def clean_str(s): """Clean sentence""" s = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", s) s = re.sub(r"\'s", " \'s", s) s = re.sub(r"\'ve", " \'ve", s) s = re.sub(r"n\'t", " n\'t", s) s = re.sub(r"\'re", " \'re", s) s = re.sub(r"\'d", " \'d", s) s = re.sub(r"\'ll", " \'ll", s) s = re.sub(r",", " , ", s) s = re.sub(r"!", " ! ", s) s = re.sub(r"\(", " ", s) s = re.sub(r"\)", " ", s) s = re.sub(r"\?", " ? ", s) s = re.sub(r"\s{2,}", " ", s) s = re.sub(r'\S*(x{2,}|X{2,})\S*',"xxx", s) s = re.sub(r'[^\x00-\x7F]+', "", s) return s.strip() As you can see that I am removing parentheses and other special characters. Now, I want to keep the following patterns intact in my text and not remove them :), :-), :( and :-( Could anyone help me with this please? thanks,
tagged with: text
tagged with: emoticons

http://stackoverflow.com/q/52353860
has answer: http://stackoverflow.com/a/52353896
type: Question
possible better answer: http://stackoverflow.com/a/52353896
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52354200
favorite count: 0
tagged with: python-3.x
tagged with: python
has body: I've been across a problem in python, the input format of the 2d array to be read is 3 # number of rows and columns of a square matrix 1 2 3 # first row 3 4 6 # second row 4 6 3 # third row how do I read 2d array from the console like the above Python Version : 3.6 IDE : Spyder (Python 3.6)
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52354200
has title: How ro read mutli lined input into 2d arrays in python
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/52331258
has comment: http://stackoverflow.com/comment/91609336
type: Answer
has comment: http://stackoverflow.com/comment/91609874
has body: that shouldnt be a big problem if the format in the text file is consistently as stated above. read the file line by line, if the current line is unequal to '\n' (which would correspond to the empty lines) then treat the current line as your key (you might want to strip of the trailing '\n' though) and concatenate the next two lines as the value for your dictionary. then update you dictionary with these and repeat until line == "". That should do it. see a possible solution below. There might be other more elegant solutions though. filename = ".//users.db" users = {} with open(filename,"r") as fin: line = fin.readline() # read until end of file while line != "": # check if you reached an empty line if line != "\n": content = "" next = fin.readline() # to allow for multiline you can use the while loop # just check if the next line is "\n" or "" to get out of the loop while next != "\n" and next != "": # for the value part of the dict just concat the next lines content += next next = fin.readline() # update the dict with 'line' as key and 'content' as value users.update({line.rstrip():content}) # eat, sleep, repeat line = fin.readline() ### line adjusted for correct intendation print(users) my output: {'n Name1 MiddleName1 Surname1': 'multiline\nstring1\n', 'n Name2 MiddleName2 Surname2': 'multiline\nstring2\n', 'n Name3 MiddleName3 Surname3': 'multiline\nstring3'}
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52330853
has comment: http://stackoverflow.com/comment/91610209
answers question: http://stackoverflow.com/q/52330853
has comment: http://stackoverflow.com/comment/91610346
has comment: http://stackoverflow.com/comment/91609401
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91756570
has text: @roganjosh: Note: It will "work", in the sense that the loop will run to completion, because the old value of `x` is effectively cached as part of `for` loop setup. That said, yes, any reference to `x` after the loop has begun will no longer refer to the original iterable, so while it "works", it's almost certainly going to be confusing/error-prone.
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/52406175

http://stackoverflow.com/comment/91719878
has text: I am editing the PyModuleDef_HEAD_INIT. Mistake because of typing instead of copying. "_"
type: Comment
comment on: http://stackoverflow.com/a/52387564
score: 0
type: AnswerComment

http://stackoverflow.com/q/52320850
answer count: 4
has answer: http://stackoverflow.com/a/52321054
has comment: http://stackoverflow.com/comment/91589514
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52321166
score: -1
has comment: http://stackoverflow.com/comment/91589409
has answer: http://stackoverflow.com/a/52321050
has answer: http://stackoverflow.com/a/52321032
upvote count: 0
favorite count: 0
type: UnansweredQuestion
has title: How to calculate the total salary from inside a for loop
has body: I want to calculate the total number of pennies after the user has input a certain number of days and the for loop runs giving the amount of "pennies" after each iteration. I want to sum up all of the right sided column so that it gives a total in the format $xx.xx. numberOfDaysWorked = int(input ("Enter the amount of days worked: \n")) #Asking the user to enter the amount of days they have worked salary = 0.01 #setting the inital amount of pennies total = 0.00 print( "Day\tSalary\n---\t----" ) #printing out the titles for days and salary for currentDay in range(numberOfDaysWorked): salary += 2 * salary # this is adding the amount of pennies earned that day to the total amount of pennies that will be used toward the total print (currentDay + 1, "\t", salary) #printing out the day (+1 to ensure progression from day1 to day2 to day3 etc. and then printing out the amount of pennies earned on that one day) print ("Total Pay: $", totalPay)
tagged with: python

http://stackoverflow.com/q/52414440
tagged with: python
has comment: http://stackoverflow.com/comment/91772718
answer count: 4
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/52414488
upvote count: 2
type: Question
linked to: http://stackoverflow.com/q/14661701
has title: Call multiple Rows in Pandas
possible better answer: http://stackoverflow.com/a/52414531
has answer: http://stackoverflow.com/a/52414469
has answer: http://stackoverflow.com/a/52414531
tagged with: pandas
has answer: http://stackoverflow.com/a/52414500
has body: I am trying to drop multiple rows from my data. I can drop rows using: dt=dt.drop([40,41,42,43,44,45]) But I was wondering if there is a simpler way. I tried: dt=dt.drop([40:45]) But sadly it did not work.
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52414488
has comment: http://stackoverflow.com/comment/91772871

http://stackoverflow.com/a/52335026
has body: You could try something like this: from itertools import combinations lst = [[1, 2, 3, 5], [1, 2, 9], [5, 6], [9]] lst_set = [set(e) for e in lst] print([[x, y] for x, y in combinations(range(len(lst)), 2) if not lst_set[x].isdisjoint(lst_set[y])]) Output [[0, 1], [0, 2], [1, 3]]
type: Answer
score: 1
answers question: http://stackoverflow.com/q/52334593
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52334593
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91608258
comment on: http://stackoverflow.com/q/52330667
score: 0
type: Comment
type: QuestionComment
has text: @SembeiNorimaki yep, this particular dupe is pretty circular. I just go for one that I think is a decent starting point in the loop. IIRC I did find the bottom of the spiral and it wasn't particularly great, better to start somewhere higher up and the OP can work their way through

sqlite
tags question: http://stackoverflow.com/q/52395405
tags question: http://stackoverflow.com/q/52322201
tags question: http://stackoverflow.com/q/52332258
tags question: http://stackoverflow.com/q/52311278
tags question: http://stackoverflow.com/q/52307130
type: Tag
tags question: http://stackoverflow.com/q/52342780
tags question: http://stackoverflow.com/q/52305911
tags question: http://stackoverflow.com/q/52276142
tags question: http://stackoverflow.com/q/52274852
tags question: http://stackoverflow.com/q/52368510
tags question: http://stackoverflow.com/q/52352319
tags question: http://stackoverflow.com/q/52350352
tags question: http://stackoverflow.com/q/52403943
tags question: http://stackoverflow.com/q/52317084
tags question: http://stackoverflow.com/q/52283157
tags question: http://stackoverflow.com/q/52382517
tags question: http://stackoverflow.com/q/52416482
tags question: http://stackoverflow.com/q/52319954
tags question: http://stackoverflow.com/q/52333800
tags question: http://stackoverflow.com/q/52327678
tags question: http://stackoverflow.com/q/52400294
tags question: http://stackoverflow.com/q/52421332
tag name: sqlite
tags question: http://stackoverflow.com/q/52355627
tags question: http://stackoverflow.com/q/52398273

http://stackoverflow.com/comment/91675824
has text: @TommyF words are everything between commas and spaces and sub-words are the words between '__'.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52365750

http://stackoverflow.com/a/52323376
answers question: http://stackoverflow.com/q/52323208
score: 0
upvote count: 1
downvote count: 1
type: Answer
has body: Here is a handy one-liner using itertools and list comprehension with if and else in it. First it makes a nested list (to have the ability to repeat items on a certain position) and then it will simply flatten it at the end using .chain()-method: from itertools import chain array_a = [1, 2, 1, 2, 1, 1, 2] list(chain.from_iterable([[item, item] if item == 2 else [item] for item in array_a])) [1, 2, 2, 1, 2, 2, 1, 1, 2, 2] # output The specific value to double is inside the if-statement. Using multipliers (instead of [item, item]) and a variable (instead of 2) would make this easily more generic, see this for example: from itertools import chain def repeat_certain_value(array, val, n): return list(chain.from_iterable(([i] * n if i == val else [i] for i in array))) repeat_certain_value([1, 2, 1, 2, 1, 1, 2], 2, 2) [1, 2, 2, 1, 2, 2, 1, 1, 2, 2] # output repeat_certain_value([0, -3, 1], -3, 5) [0, -3, -3, -3, -3, -3, 1] # output While this approach is a handy one-liner using builtin libraries, the approach from coldspeed is faster: %timeit for x in range(1000): repeat_certain_value([1, 1, 1, 2, 2, 2, 3, 3, 3] * 100, 2, 2) 10 loops, best of 3: 165 ms per loop %timeit for x in range(1000): coldspeeds_solution([1, 1, 1, 2, 2, 2, 3, 3, 3] * 100, 2, 2) 10 loops, best of 3: 100 ms per loop

http://stackoverflow.com/comment/91640625
has text: Because I am a student and have not learned about list yet, the exercise in my class strictly forbid us to use anything else other than for loop, ifelse and functions and strings
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52347603
score: 0

http://stackoverflow.com/a/52279667
answers question: http://stackoverflow.com/q/52279470
score: 0
has body: You don't need the for loop as part of your recursive call. The call to sier is what makes the function loop. And you have your recursive termination case with the n==0 check to end the loop. Example &gt;&gt;&gt; def sier(n, length): ... if(n==0): ... return ... print("n:" + str(n) + ", length: " + str(length)) ... sier(n-1, length/2) ... &gt;&gt;&gt; sier(10,100) n:10, length: 100 n:9, length: 50.0 n:8, length: 25.0 n:7, length: 12.5 n:6, length: 6.25 n:5, length: 3.125 n:4, length: 1.5625 n:3, length: 0.78125 n:2, length: 0.390625 n:1, length: 0.1953125 &gt;&gt;&gt; sier(3,100) n:3, length: 100 n:2, length: 50.0 n:1, length: 25.0
has comment: http://stackoverflow.com/comment/91507964
type: Answer

http://stackoverflow.com/comment/91791400
comment on: http://stackoverflow.com/q/52422327
has text: I believe this is currently only possible using tensorflow directly.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91717315
type: Comment
type: QuestionComment
has text: I don't think there is a way to answer your question - maybe `if settings.MIXPANEL_ID` should be checked before calling a method, and the method called only if the state allows it?
comment on: http://stackoverflow.com/q/52386370
score: 1

http://stackoverflow.com/comment/91616012
type: AnswerComment
has text: It is a chat bot for ESPN fantasy football league updates that works with GroupMe, slack, or discord.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52300424

http://stackoverflow.com/comment/132681578
comment on: http://stackoverflow.com/a/52388645
score: 0
type: AnswerComment
type: Comment
has text: The situation is actually a bit different. I take data from a (locally stored) database. This database holds unicode, which will be (simplified speaking) imported by my app after JSON encoding. I can change the database manually towards correct encoding, but had quite some struggle without success. E.g. `\\u00c4\\u00b0zmir` (database) decodes to isolatin1 `Ä°zmir`, which makes `İzmir` in UTF8. That's using your code! I didn't find any tool or online converter which makes out of `\\u00c4\\u00b0` -> `İ`. So I decided to leave the unicode untouched and do the conversion using your snippet.

http://stackoverflow.com/comment/91621095
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52335343
has text: Got `TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'`. But this one worked: `cities, country_codes = zip(*[(d['city'], d['country_code']) for d in df['billing_address'] if not pd.isnull(d)])`

http://stackoverflow.com/comment/91678722
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52366874
has text: This can easily be crashed if the user enters a string for example
score: 0

http://stackoverflow.com/comment/91795936
comment on: http://stackoverflow.com/q/52423873
type: Comment
type: QuestionComment
has text: Yes rdimaio , in excel , we can see the date display format of cell , But i am looking for a way to find it via python ,that python can tell me that the date dispaly format of cell is dd-mm-yyyy or mm-dd-yyy
score: 0

http://stackoverflow.com/comment/91555618
score: 1
comment on: http://stackoverflow.com/q/52303977
type: Comment
type: QuestionComment
has text: You don't need a list. Just add another number `biggest = -sys.maxsize` (initialize it at the beginning, together with the others), and every time you read `num` do `if num > buggest: biggest = num`. You will also need `import sys`.

http://stackoverflow.com/q/52408701
tagged with: python
has comment: http://stackoverflow.com/comment/91762379
score: 14
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91761807
downvote count: 0
has comment: http://stackoverflow.com/comment/91762436
has answer: http://stackoverflow.com/a/52414887
accepted answer: http://stackoverflow.com/a/52414887
has body: So I am trying to scrape the following webpage https://www.scoreboard.com/uk/football/england/premier-league/, Specifically the scheduled and finished results. Thus I am trying to look for the elements with class = "stage-finished" or "stage-scheduled". However when I scrape the webpage and print out what page_soup contains, it doesn't contain these elements. I found another SO question with an answer saying that this is because it is loaded via AJAX and I need to look at the XHR under the network tab on chrome dev tools to find the file thats loading the necessary data, however it doesn't seem to be there? import bs4 import requests from bs4 import BeautifulSoup as soup import csv import datetime myurl = "https://www.scoreboard.com/uk/football/england/premier-league/" headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'} page = requests.get(myurl, headers=headers) page_soup = soup(page.content, "html.parser") scheduled = page_soup.select(".stage-scheduled") finished = page_soup.select(".stage-finished") live = page_soup.select(".stage-live") print(page_soup) print(scheduled[0]) The above code throws an error of course as there is no content in the scheduled array. My question is, how do I go about getting the data I'm looking for? I copied the contents of the XHR files to a notepad and searched for stage-finished and other tags and found nothing. Am I missing something easy here?
has comment: http://stackoverflow.com/comment/91762186
type: Question
has title: BeautifulSoup can't find class that exists on webpage?
has comment: http://stackoverflow.com/comment/91762872
answer count: 1
has comment: http://stackoverflow.com/comment/91762021
upvote count: 14
has comment: http://stackoverflow.com/comment/91762703
has comment: http://stackoverflow.com/comment/91761873
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/91761434

http://stackoverflow.com/a/52309955
answers question: http://stackoverflow.com/q/52309515
score: 0
has comment: http://stackoverflow.com/comment/91567152
type: Answer
has body: you can try something like this import matplotlib.pyplot as plt selected={"Husain":92, "Asim":65,"Chirag": 74 } rejected={"Absar":70,"premraj":57} selected_candidates_number = len(selected) rejected_candidates_number = len(rejected) plt.bar(range(selected_candidates_number ),list(selected.values()),color="green") plt.bar(range(selected_candidates_number,selected_candidates_number +rejected_candidates_number ),list(rejected.values()),color="red") plt.xticks(range(selected_candidates_number +rejected_candidates_number), list(selected.keys()) + list(rejected.keys())) plt.xlabel("Candidates") plt.ylabel("Score") plt.plot() plt.show()

http://stackoverflow.com/comment/91658262
score: 0
type: Comment
type: QuestionComment
has text: Can you clarify what your question is? You say you "couldn't get the answer", but you don't actually say anywhere what does happen. Are you getting an exception? The wrong output? No output? What do you expect the output to be like?
comment on: http://stackoverflow.com/q/52356369

http://stackoverflow.com/q/52427132
tagged with: tkinter
score: 1
upvote count: 1
type: Question
has title: How to "live" update matplotlib figure plot using trace
tagged with: matplotlib
has body: There are few anchor points to notice in the code. The update_observation() function is updated every time a drop downs value changes. I want the graph to change as well whenever a dropdown list value is changed. I would like only one instance of the graph window at any point. I want to update the information inside the graph window. I tried using animation but I believe there could be an alternative to that using the trace method. The button is simply to open and close the window. And it solves no other purpose. It binds until the same window is not closed. How do I use the value of artifact_graph_window in my update_observation() function. def tab_two_load(self,tab1_open_observations): def update_observation(a,b,c): proj_name,mod_name = observation_project_value.get().split(" -- ") observations_fr_project = db.query_findings_by_project(proj_name,mod_name) ##CONFIG fig = Figure(figsize=(6,6)) a = fig.add_subplot(111) ## DATA x_cat = [x[1] for x in db.query_artifact()] x_cat = x_cat[:-2] y_count = {} for i in x_cat: y_count[i] = 0 for i in observations_fr_project: y_count[i[2]] = y_count[i[2]] + 1 print(y_count) x = y_count.keys() y = y_count.values() ## PLOT a.bar(x,y,color='blue') ## SHOW a.set_title ("Artifact Breakdown", fontsize=16) a.set_ylabel("Breakdown", fontsize=14) a.set_xlabel("Artifact Type", fontsize=14) a.yaxis.set_major_locator(MaxNLocator(integer=True)) ####################################### ''' GRAPH END ''' ####################################### canvas = FigureCanvasTkAgg(fig, master=artifact_graph_window) canvas.get_tk_widget().pack() canvas.draw() def artifact_graph(): artifact_graph_window = Toplevel(self) artifact_graph_window.title('Artifact Graph') button_graph_1.config(state='disable') proj_name,mod_name = observation_project_value.get().split(" -- ") observations_fr_project = db.query_findings_by_project(proj_name,mod_name) def quit_win(): artifact_graph_window.destroy() button_graph_1.config(state='normal') quit_artifact_graph = Button(…
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52429360
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/52429360
type: AnsweredQuestion

http://stackoverflow.com/comment/91999492
score: 1
has text: https://i.sstatic.net/aEXNi.png Am running the python script file as child process through npm package...it will open the .exe file and provide inputs on the first page..While clicking submit button the dialog will appear,the script fails in handling the dialog .. i need to close or click OK Button in dialog NOTE:While checking line by line script via python terminal its perfectly working (ie) am able to handle dialog box .. @Vasily Ryabov
comment on: http://stackoverflow.com/a/52406874
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52408473
has body: Given: foo = [['7.0352220e-01 5.3130367e-06 1.5167372e-05 1.0797821e-06'], ['1.3130367e-06 2.4584832e-01 2.2375602e-05 7.3299240e-06'], ['7.2646574e-06 7.1252006e-06 3.0184277e-01 1.0048618e-05']] Try this to split each string foo = [row[i].split() for row in foo for i in range(len(foo[0]))] This for changing type to floats. foo = [[float(row[i]) for i in range(len(foo[0]))] for row in foo] print(type(foo[0][1])) &gt;&gt; float Then turn it into a numpy array: foo = np.array(foo) print(type(foo[0][1])) &gt;&gt; numpy.float64
downvote count: 0
answers question: http://stackoverflow.com/q/52407819
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/91763914

http://stackoverflow.com/q/52277962
has comment: http://stackoverflow.com/comment/91504014
has title: How do I convert a Simple Integer to a time's Minutes
tagged with: python
has body: I have this integers here i = 33 and o = 156, what i want to do is to convert these integers into minutes in a time format to become these results: i =&gt; 00:33:00 o =&gt; 02:36:00 i tried this: from datetime import datetime, timedelta i = 33 o = 156 itime = datetime.timedelta(minutes=i) itime = datetime.timedelta(minutes=o) and it gives me this error AttributeError: type object 'datetime.datetime' has no attribute 'timedelta' which is solved by adding import datetime but in my code it breaks some parts of it like datetime.strptime() when i add it like this import datetime from datetime import datetime, timedelta also i tried without the from datetime import datetime, timedelta like this datetime.timedelta(minutes=33) but the result was datetime.timedelta(0, 1980) but i want it to be by minutes and not seconds like this datetime.time(0, 33)
has comment: http://stackoverflow.com/comment/91503902
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/52278269
possible better answer: http://stackoverflow.com/a/52278044
has answer: http://stackoverflow.com/a/52278242
has answer: http://stackoverflow.com/a/52278044
type: Question
answer count: 3
tagged with: datetime
has answer: http://stackoverflow.com/a/52278269

http://stackoverflow.com/comment/91729692
type: Comment
has text: What makes `0` more concise than `bytes()` or `b''`? I am less familiar with this topic.
type: AnswerComment
comment on: http://stackoverflow.com/a/52391715
score: 0

http://stackoverflow.com/q/52417128
answer count: 1
has answer: http://stackoverflow.com/a/52417147
score: 0
has body: Say that I have a 2D numpy array that looks like this x = np.array( [[ 3 , 4, 2 ,4, 7, 9, 7, 5, 2, 1, 7 ], [ 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] ]) print(x) &gt;[[ 3 4 2 4 7 9 7 5 2 1 7] &gt; [11 10 9 8 7 6 5 4 3 2 1]] I want to delete duplicate numbers in the first row, and delete the corresponding number in the 2nd row. The number that does Not get deleted is the biggest one (from the 2nd row). Here's what I want the output to look like. &gt;[[ 3 4 2 7 9 5 1 ] &gt; [11 10 9 7 6 4 2 ]] All duplicates from row 1 have been deleted, as well as the corresponding value in row 2. The value that remains is always the biggest value in row 2. If it helps, we can assume row 2 is always sorted in descending order like it is above.
has title: How do I delete duplicate values in one row of a 2D Numpy array, and also delete the corresponding value in the other row as well?
tagged with: python
has comment: http://stackoverflow.com/comment/91777468
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52417147
has comment: http://stackoverflow.com/comment/91777546
type: Question
tagged with: numpy

http://stackoverflow.com/a/52375159
type: AcceptedAnswer
upvote count: 16
score: 15
accepted answer of: http://stackoverflow.com/q/52375078
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52375078
has body: Straight from the docs: Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to assertRaises(). The test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception. So, your code should look like assertRaises((RuntimeError, IndexError), "error message")

http://stackoverflow.com/a/52357253
has comment: http://stackoverflow.com/comment/91659061
upvote count: 1
answers question: http://stackoverflow.com/q/52357217
has body: Use the str.split() method to split by space: total = sum(sum(int(n) for n in i.split()) for i in sume) # ^^ that's your starting list This takes each string on numbers in the list and splits it by space, returning the sum of it. Then each of these 'sums' are fed into the outer sum call to get their total. This would look like the following when expanded: total = 0 for i in sume: i = i.split() for n in i: total += int(n) Remember that split() returns a list of strings, so you still need to cast each item to int before summing it.
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/52357560
has comment: http://stackoverflow.com/comment/91659885
has comment: http://stackoverflow.com/comment/91659849
accepted answer: http://stackoverflow.com/a/52357843
has comment: http://stackoverflow.com/comment/91659825
score: 59
has comment: http://stackoverflow.com/comment/91659853
answer count: 1
has comment: http://stackoverflow.com/comment/91659869
has title: How come regex match objects aren't iterable even though they implement __getitem__?
favorite count: 0
tagged with: iterable
has comment: http://stackoverflow.com/comment/91659927
upvote count: 61
has comment: http://stackoverflow.com/comment/91659863
has answer: http://stackoverflow.com/a/52357843
has comment: http://stackoverflow.com/comment/91659844
has body: As you may know, implementing a __getitem__ method makes a class iterable: class IterableDemo: def __getitem__(self, index): if index &gt; 3: raise IndexError return index demo = IterableDemo() print(demo[2]) # 2 print(list(demo)) # [0, 1, 2, 3] print(hasattr(demo, '__iter__')) # False However, this doesn't hold true for regex match objects: &gt;&gt;&gt; import re &gt;&gt;&gt; match = re.match('(ab)c', 'abc') &gt;&gt;&gt; match[0] 'abc' &gt;&gt;&gt; match[1] 'ab' &gt;&gt;&gt; list(match) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: '_sre.SRE_Match' object is not iterable It's worth noting that this exception isn't thrown in the __iter__ method, because that method isn't even implemented: &gt;&gt;&gt; hasattr(match, '__iter__') False So, how is it possible to implement __getitem__ without making the class iterable?
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/22313702
downvote count: 2
linked to: http://stackoverflow.com/q/926574
type: Question

http://stackoverflow.com/q/52281909
has comment: http://stackoverflow.com/comment/91511899
has comment: http://stackoverflow.com/comment/91519930
has body: I have a utf-8 list variable lines like this: [u' ASUS-ASUS-131:66 BF-24-XX-XX-BF--More-- \x08\x08\x08\x08\x08\x08\x08\x08\x08 \x08\x08\x08\x08\x08\x08\x08\x08\x08-A0,'u' ASUS-ASUS-084:R0 AX-24-AX-AC-AX-10] If I do print lines it will print same as above with backspace \x08 but if I print line by line for i in lines print i It will print ASUS-ASUS-131:66 BF-24-XX-XX-BF-A0 ASUS-ASUS-084:R0 AX-24-AX-AC-AX-10 I know the print function was actually performing backspace but is there way to assign the print value to a variable to get rid of backspace? I already tried str_var = str(i) but it does not work Here is a example &gt;&gt;&gt; test=' --More-- \x08\x08\x08\x08\x08\x08\x08\x08\x08 \x08\x08\x08\x08\x08\x08\x08\x08\x08' &gt;&gt;&gt; print test &gt;&gt;&gt; repr(test) "' --More-- \\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08 \\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08'" I don't understand why it shows like this and I want to assign the print output which is empty to a variable
tagged with: python
has answer: http://stackoverflow.com/a/52281948
has comment: http://stackoverflow.com/comment/91516183
has comment: http://stackoverflow.com/comment/91511875
has comment: http://stackoverflow.com/comment/91512234
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91516783
accepted answer: http://stackoverflow.com/a/52282003
type: Question
upvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/91516774
has comment: http://stackoverflow.com/comment/91511903
score: 4
has comment: http://stackoverflow.com/comment/91552036
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91512423
downvote count: 0
has title: How to apply backspace \x08 to a string?
favorite count: 0
has answer: http://stackoverflow.com/a/52282003
possible better answer: http://stackoverflow.com/a/52281948

http://stackoverflow.com/q/52420291
has answer: http://stackoverflow.com/a/52420362
favorite count: 0
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
has body: Any help would be appreciated I have a dictionary containing cards names and their corresponding statistics, for example: {'Bob': [1, 3, 6, 5], 'Dave': [1, 8, 5, 5], 'Steve': [1, 3, 9, 7], 'John': [6, 7, 9, 5], 'Bill': [7, 3, 9, 1], 'Rodger': [4, 5, 2, 8]} player = dict() computer = dict() But I am unsure on how to randomly assign cards into two different variables, such that both variables contain the same number of cards, each card is used once and none of the cards are in both variables. Anyone know how to help?
downvote count: 2
upvote count: 1
has title: Python Top trumps
score: -1
type: Question
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91783802
answer count: 1

http://stackoverflow.com/q/52324812
upvote count: 0
score: -2
has answer: http://stackoverflow.com/a/52324976
tagged with: python
favorite count: 0
type: UnansweredQuestion
downvote count: 2
has body: Write a function named "distance" that takes two floating point numbers as parameters representing the (x, y) coordinates of a point in a 2d space. Define your distance method to return the Euclidean distance between the input point and the point (14.9, 16.2) import math def distance(x, y): return (((x - 14.9) ** 2) + ((y - 16.2) ** 2))** 1/2
has title: Trouble with Euclidean distance statement
has answer: http://stackoverflow.com/a/52324930
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91596872

http://stackoverflow.com/a/52316540
type: Answer
score: 0
has body: Should use continue like so: li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] for i in range(0,len(li)): if i in range(3, li[9]): continue print(i)
answers question: http://stackoverflow.com/q/52316409

mongodb
tags question: http://stackoverflow.com/q/52289516
tags question: http://stackoverflow.com/q/52406141
tags question: http://stackoverflow.com/q/52313900
tag name: mongodb
tags question: http://stackoverflow.com/q/52397507
tags question: http://stackoverflow.com/q/52315572
tags question: http://stackoverflow.com/q/52387322
tags question: http://stackoverflow.com/q/52371412
tags question: http://stackoverflow.com/q/52274472
tags question: http://stackoverflow.com/q/52360924
type: Tag
tags question: http://stackoverflow.com/q/52358406
tags question: http://stackoverflow.com/q/52369977
tags question: http://stackoverflow.com/q/52418721
tags question: http://stackoverflow.com/q/52309654
tags question: http://stackoverflow.com/q/52349227
tags question: http://stackoverflow.com/q/52429644
tags question: http://stackoverflow.com/q/52423426
tags question: http://stackoverflow.com/q/52349991
tags question: http://stackoverflow.com/q/52304949

http://stackoverflow.com/comment/91604175
comment on: http://stackoverflow.com/q/52327134
type: Comment
type: QuestionComment
has text: Checking for balanced parentheses where your string contains *only* parentheses is a pretty useless practical problem. It's good for teaching/learning, but in practice you'll more likely have expressions which contains parentheses *and other stuff*, so your `% 2` check would be pointless there anyway…
score: 1

http://stackoverflow.com/a/52316134
has body: Once I also had that problem so I modified the library, first activate the flags: QtCore.Qt.Dialog | QtCore.Qt.FramelessWindowHint, and the other change must be done in updatePosition() method: def updatePosition(self): if self.parentWidget() and self._centerOnParent: parentRect = QtCore.QRect(self.parentWidget().mapToGlobal(QtCore.QPoint(0, 0)), self.parentWidget().size()) self.move(QtWidgets.QStyle.alignedRect(QtCore.Qt.LeftToRight, QtCore.Qt.AlignCenter, self.size(), parentRect).topLeft()) The result is as follows: waitingspinnerwidget.py import math from PyQt5 import QtCore, QtGui, QtWidgets class QtWaitingSpinner(QtWidgets.QWidget): def __init__(self, parent=None, centerOnParent=True, disableParentWhenSpinning=False, modality=QtCore.Qt.NonModal): super().__init__(parent, flags=QtCore.Qt.Dialog | QtCore.Qt.FramelessWindowHint) self._centerOnParent = centerOnParent self._disableParentWhenSpinning = disableParentWhenSpinning # WAS IN initialize() self._color = QtGui.QColor(QtCore.Qt.black) self._roundness = 100.0 self._minimumTrailOpacity = 3.14159265358979323846 self._trailFadePercentage = 80.0 self._revolutionsPerSecond = 1.57079632679489661923 self._numberOfLines = 20 self._lineLength = 10 self._lineWidth = 2 self._innerRadius = 10 self._currentCounter = 0 self._isSpinning = False self._timer = QtCore.QTimer(self) self._timer.timeout.connect(self.rotate) self.updateSize() self.updateTimer() self.hide() # END initialize() self.setWindowModality(modality) self.setAttribute(QtCore.Qt.WA_TranslucentBackground) def paintEvent(self, QPaintEvent): self.updatePosition() painter = QtGui.QPainter(self) painter.fillRect(self.rect(), QtCore.Qt.transparent) painter.setRenderHint(QtGui.QPainter.Antialiasing, True) if self._currentCounter &gt;= self._numberOfLines: self._currentCounter = 0 painter.setPen(QtCore.Qt.NoPen) for i in range(0, self._numberOfLines): painter.save() painter.translate(self._innerRadius + self._lineLength, self._innerRadius + self._lineLength) rotateAn…
has comment: http://stackoverflow.com/comment/91587029
type: Answer
has comment: http://stackoverflow.com/comment/135867133
has comment: http://stackoverflow.com/comment/91752053
upvote count: 4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52313073
score: 4
accepted answer of: http://stackoverflow.com/q/52313073

http://stackoverflow.com/q/52322216
has comment: http://stackoverflow.com/comment/91604230
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91611663
type: Question
tagged with: apache-spark-sql
tagged with: pyspark
has comment: http://stackoverflow.com/comment/91604853
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91605215
tagged with: apache-spark
linked to: http://stackoverflow.com/q/47761758
has title: How to use partitionBy and orderBy together in Pyspark
has comment: http://stackoverflow.com/comment/91604943
has comment: http://stackoverflow.com/comment/91601747
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52329316
has comment: http://stackoverflow.com/comment/91604735
has comment: http://stackoverflow.com/comment/91593682
has comment: http://stackoverflow.com/comment/91604081
tagged with: python
has body: I'm trying to split sessions from lastfm dataset, following the answer from https://www.arundhaj.com/blog/calculate-difference-with-previous-row-in-pyspark.html from pyspark.sql import SparkSession from pyspark.sql.functions import countDistinct, count, lag, to_timestamp from pyspark.sql.window import Window spark = SparkSession \ .builder \ .appName("SampleAPP") \ .config("spark.executor.memory", "4g") \ .getOrCreate() fname = "inputFile.tsv" df = spark.read.format('com.databricks.spark.csv').options(header='false', delimiter='\t').load(fname) df = df.selectExpr("_c0 as userid", "_c1 as timestamp", "_c2 as artid", "_c3 as artname", "_c4 as traid", "_c5 as traname") df = df.withColumn('new_ts', df.timestamp.astype('Timestamp').cast("long")) my_window = Window.partitionBy("userid").orderBy("new_ts") df = df.withColumn("prev_value", lag(df.new_ts).over(my_window)) df.show() but getting the following error: py4j.protocol.Py4JJavaError: An error occurred while calling o56.showString, the dataset looks like this, +-----------+--------------------+--------------------+---------------+--------------------+--------------------+----------+ | userid| timestamp| artid| artname| traid| traname| new_ts| +-----------+--------------------+--------------------+---------------+--------------------+--------------------+----------+ |user_000001|2009-05-04T23:08:57Z|f1b1cf71-bd35-4e9...| Deep Dish| null|Fuck Me Im Famous...|1241478537| |user_000001|2009-05-04T13:54:10Z|a7f7df4a-77d8-4f1...| 坂本龍一| null|Composition 0919 ...|1241445250| |user_000001|2009-05-04T13:52:04Z|a7f7df4a-77d8-4f1...| 坂本龍一| null|Mc2 (Live_2009_4_15)|1241445124| |user_000001|2009-05-04T13:42:52Z|a7f7df4a-77d8-4f1...| 坂本龍一| null|Hibari (Live_2009...|1241444572| +-----------+--------------------+--------------------+---------------+--------------------+--------------------+----------+ any help on how to solve would be really appreciated. Full Traceback Traceback (most recent call last): File "code.py", line 42, in &lt…
has answer: http://stackoverflow.com/a/52327420
has comment: http://stackoverflow.com/comment/91604429
has comment: http://stackoverflow.com/comment/91604754

syntax-error
tags question: http://stackoverflow.com/q/52289216
type: Tag
tags question: http://stackoverflow.com/q/52354164
tags question: http://stackoverflow.com/q/52419790
tag name: syntax-error
tags question: http://stackoverflow.com/q/52402513

http://stackoverflow.com/comment/91864381
type: Comment
comment on: http://stackoverflow.com/a/52460744
has text: Happy it helped! `app.` is necessary because `get_url` is a method of the `Bottle` class. https://bottlepy.org/docs/dev/api.html#bottle.Bottle.get_url
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91763554
comment on: http://stackoverflow.com/q/52408841
type: Comment
type: QuestionComment
has text: @CharlesDuffy, agreed, will give due consideration going fwd
score: 0

http://stackoverflow.com/comment/91545419
type: Comment
comment on: http://stackoverflow.com/a/52297694
type: AnswerComment
has text: I think that a Dense layer in the bottleneck would not help (you would still have the same problem, because there isn't any integer `x` such that `x*8=150`). I think that cropping in the decoder is not a big deal (the network would figure out by itself that the discarded neurons are useless). I added another possible solution, in case it looks more appealing to you. If you are not satisfied with any of them, I believe you should necessarily change the architecture.
score: 0

http://stackoverflow.com/comment/91522695
comment on: http://stackoverflow.com/a/52287293
has text: I updated the code to allow passing keys in a dictionary. Now it should properly handle only deleting elements from the correct subdictionary.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91758920
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52407555
has text: I will edit now.
score: 0

http://stackoverflow.com/q/52325109
tagged with: pandas-groupby
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/52325473
type: Question
has body: I have a Dataframe that looks like the following: enter image description here The dataframe counts the number of question according to their state: question_count_data.columns = ['date', 'curriculum_name_en', 'concept', 'language', 'concept_name_en', 'concept_name_tc', 'state', 'question_count'] question_count_data['state'] = question_count_data['state']\ .map({10: 'DRAFT', 20: 'REVIEW', 30: 'PUBLISHED', 40: 'ERROR', 50: 'DISABLED'}) I have used the following method to create this dataframe: question_count_data = df_question.groupby(['date', 'concept__curriculum__name_en', 'concept', 'language', 'concept_name_en', 'concept_name_tc', 'state', ], as_index=False)['question_count'].sum() I want to now create separate columns for each state DRAFT, REVIEW, PUBLISHED, etc and provide the question count in rows , that has to look like the following : enter image description here Whats the best possible way to do this using my question_count_data Dataframe? I dont want to change the groupby method already implemented because thats what providing me the question count. I do not think having another groupby method would be possible solution because what i ultimately want to do is getting the row value of the column State and getting them to separate columns like Draft, Review, Published, etc and then provide the count for each date. A detailed explanation would be helpful please.
has answer: http://stackoverflow.com/a/52325473
has title: Pandas DataFrame grouping

http://stackoverflow.com/q/52299946
has body: I am new to tensor flow. I have just started using Keras with the tensor flow at the backend. I am using a laptop with i7 16 GB memory and GeForce GT 750M. Tensorflow version 1.10, Cuddatoolkit 9.1, cudnn 7.14 I have used following code to train the pre-train VGG16 model. my training set has 300 images. I checked the following code with batch size 8 it works fine .however when I change the batch size to 16, the kernel in spyder failed to reload after training, giving the following error: tensorflow/stream_executor/cuda/cuda_driver.cc:1078] failed to synchronize the stop event: CUDA_ERROR_LAUNCH_FAILED tensorflow/stream_executor/cuda/cuda_timer.cc:55] Internal: error destroying CUDA event in context 0000023F82C1E010: CUDA_ERROR_LAUNCH_FAILED tensorflow/stream_executor/cuda/cuda_timer.cc:60] Internal: error destroying CUDA event in context 0000023F82C1E010: CUDA_ERROR_LAUNCH_FAILED tensorflow/stream_executor/cuda/cuda_dnn.cc:211] Check failed: status == CUDNN_STATUS_SUCCESS (7 vs. 0)Failed to set cuDNN stream. I have used the following code: import sys import glob import argparse import matplotlib.pyplot as plt import tensorflow as tf from keras import __version__ from keras.applications import vgg16 from keras.applications.vgg16 import preprocess_input from keras.models import Model from keras.layers import Dense, GlobalAveragePooling2D from keras.preprocessing.image import ImageDataGenerator from keras.optimizers import SGD from keras import backend as K IM_WIDTH, IM_HEIGHT = 299, 299 NB_EPOCHS = 2 BAT_SIZE = 16 #32 FC_SIZE = 256 def get_nb_files(directory): """Get number of files by searching directory recursively""" if not os.path.exists(directory): return 0 cnt = 0 for r, dirs, files in os.walk(directory): for dr in dirs: cnt += len(glob.glob(os.path.join(r, dr + "/*"))) return cnt #******************************************************** def add_new_last_layer(base_model, nb_classes): """Add last layer to the convnet Args: base_model: keras model excluding top n…
type: Question
answer count: 1
tagged with: keras
score: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52302134
has title: kernel restarting failed after training using Tensor flow and keras
tagged with: tensorflow

http://stackoverflow.com/comment/93398886
has text: @David I used [ArviZ](https://arviz-devs.github.io/arviz/examples/index.html) for those plots.
type: AnswerComment
comment on: http://stackoverflow.com/a/52434726
score: 0
type: Comment

http://stackoverflow.com/a/52319982
has comment: http://stackoverflow.com/comment/91587614
answers question: http://stackoverflow.com/q/52319836
type: Answer
score: 2
downvote count: 0
has body: The main point here is knowing where cleaned_data comes from. I am guessing here that it is an instance attribute, so replacing it with self.cleaned_data should work.
upvote count: 2

http://stackoverflow.com/comment/91781879
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52419070
score: 0
has text: yes............

http://stackoverflow.com/a/52371386
type: Answer
answers question: http://stackoverflow.com/q/52349669
upvote count: 3
has comment: http://stackoverflow.com/comment/91690014
has body: Can you try uninstalling opencv and installing it using a wheel file instead? Here is a website that has many versions of OpenCV compiled for windows, search for the one you need and simply install it with pip command. So if you have Python 3.6 (64 Bit) and wish to install OpenCV 3.4.3 then download the wheel file: opencv_python‑3.4.3‑cp36‑cp36m‑win_amd64.whl
score: 3
downvote count: 0

http://stackoverflow.com/q/52340527
has body: I have a touchscreen laptop that folds back enough to become like a tablet. If I put it down on the table, I don't want to be hitting keys accidentally, so I'm working on a script to disable the keyboard when I hit Ctrl-F10 and then re-enable it when I do that again. I'm using xlib from PyPI, and I've gotten this so far: from Xlib.display import Display from Xlib.ext import xinput class Handler: def __init__(self, display): self.enabled = True self.display = display def handle(self, event): if event.data['detail'] == 76 and event.data['mods']['base_mods'] == 4: if self.enabled: self.display.grab_server() else: self.display.ungrab_server() self.enabled = not self.enabled try: display = Display() handler = Handler(display) screen = display.screen() screen.root.xinput_select_events([ (xinput.AllDevices, xinput.KeyPressMask), ]) while True: event = display.next_event() handler.handle(event) finally: display.close() It does disable the keyboard on Ctrl-F10, but as soon as I re-enable, all the keys I pressed when it was disabled are activated all at once. Is there a way to clear the queue before re-enabling, or a better way to disable the keyboard?
tagged with: python
has title: Disable keyboard but keep getting events
downvote count: 0
type: Question
tagged with: xlib
answer count: 1
score: 4
upvote count: 4
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52362524

http://stackoverflow.com/q/52371705
has body: For a given date string such as 2009-01-01T12:00:00+0100 I want the UTC datetime object. from datetime import datetime datetime.strptime("2013-03-21T14:19:42+0100", "%Y-%m-%dT%H:%M:%S%z") returns datetime.datetime(2013, 3, 21, 14, 19, 42, tzinfo=datetime.timezone(datetime.timedelta(0, 3600))) I cannot believe there is no method in datetime or pandas for applying the timezone-related offset to the datetime and returning plain UTC datetime. How can I apply the tzinfo offset/delta, so that the resulting timezone is plain UTC (tzinfo=None)?
score: 4
favorite count: 0
tagged with: pandas
tagged with: datetime
has title: Apply timezone offset to datetime in Python
tagged with: timezone-offset
tagged with: python
upvote count: 4
downvote count: 0
tagged with: timezone
has answer: http://stackoverflow.com/a/52372737
has answer: http://stackoverflow.com/a/60001875
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/70011659
accepted answer: http://stackoverflow.com/a/70011659
type: Question
answer count: 3
possible better answer: http://stackoverflow.com/a/52372737

http://stackoverflow.com/q/52321150
has title: Python Django url reverse in unittest returns a 404
tagged with: unit-testing
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52321586
has comment: http://stackoverflow.com/comment/91590697
has comment: http://stackoverflow.com/comment/91590749
score: 0
has answer: http://stackoverflow.com/a/52321468
has body: url: path('some/path_to/&lt;int:special_id&gt;/', some_views.someAPI.as_view(), name="someAPI") Normally when accessing the API with https://some_domain/some/path_to/1, I can get the data with special_id=1. No issue here. However, when I run a test which contains the reverse() function, the special_id doesn't seem to be loaded. I'm doing url = reverse('someAPI', kwargs={'special_id': 1}) request = self.factory.get(url) force_authenticate(request, user=self.user) response = someAPI.as_view()(request, special_id=1) it gave me a 404: Not found when I expect a 200 I checked the path, and it seems to be correct. I'm wondering why I'm receiving a 404. This is running through django unittest. EDIT: Turns out I didn't save the object in the test db. Make sure you call save() when creating object.....
tagged with: django
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52321468
accepted answer: http://stackoverflow.com/a/52321586

http://stackoverflow.com/q/52429607
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52450699
tagged with: linux
has comment: http://stackoverflow.com/comment/91947825
has comment: http://stackoverflow.com/comment/91804953
tagged with: python
tagged with: ruby
has comment: http://stackoverflow.com/comment/91843305
upvote count: 2
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/91804750
tagged with: ncurses
has comment: http://stackoverflow.com/comment/91955793
has comment: http://stackoverflow.com/comment/91835254
has comment: http://stackoverflow.com/comment/91844592
has comment: http://stackoverflow.com/comment/91821436
has body: I work on a game in Ruby. It uses ncurses to draw window contents and refresh the screen. This all works fine on macOS, where I develop the stuff. But on Linux, I cannot get anything besides plain ASCII to print when interfacing with ncurses either from Ruby or plain C. For example, I get this output: Hello, world! M-b~U~TM-b~U~PM-b~U~WM-b~U~QM-b~U~QM-b~U~ZM-b~U~PM-b~U~]M-b~U~_M-b~T~@M-b~UM-" Instead of what I put into the source: Hello, world! ╔═╗║║╚═╝╟─╢ File encoding is UTF-8, env or locale output reports LANG and LC_* variables to be en_US or en_US.UTF-8 where appropriate. The terminal can print these characters just fine, so it's not the font or terminal emulator setting. Python 3 works fine, too. Ruby and C don't. (Tested on a fresh Linux Mint 19 setup with libncurses5-dev installed.) So, Am I missing some setting or is the Python binding somewhat special and I'm out of luck? What it looks like It should look like this (macOS): But does look like this instead: Python Code This code works just fine: #!/usr/bin/python # -*- coding: utf-8 -*- import locale import curses locale.setlocale(locale.LC_ALL, '') stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.addstr(0, 0, "╔═╗║║╚═╝╟─╢") # dont even need .encode('UTF-8') stdscr.refresh() stdscr.getkey() curses.endwin() The docs for the curses module state that you have to do this since ncurses 5: https://docs.python.org/3/library/curses.html Since version 5.4, the ncurses library decides how to interpret non-ASCII data using the nl_langinfo function. That means that you have to call locale.setlocale() in the application and encode Unicode strings using one of the system’s available encodings. Ruby Code # coding: utf-8 require "curses" Curses.init_screen Curses.start_color Curses.stdscr.keypad(true) # enable arrow keys Curses.cbreak # no line buffering / immediate key input Curses.ESCDELAY = 0 Curses.curs_set(0) # Invisible cursor Curses.noecho # Do not print keyboard input Curses.stdscr.addstr(STYLES[:si…
has comment: http://stackoverflow.com/comment/91898425
has comment: http://stackoverflow.com/comment/91908495
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/91844298
has title: Unicode Box Drawing characters not printed in Ruby
type: Question
score: 0

http://stackoverflow.com/q/52354209
answer count: 3
downvote count: 1
has answer: http://stackoverflow.com/a/52354233
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91653025
has comment: http://stackoverflow.com/comment/91741105
score: 2
has comment: http://stackoverflow.com/comment/91653179
has comment: http://stackoverflow.com/comment/91739048
favorite count: 0
has answer: http://stackoverflow.com/a/52354296
has answer: http://stackoverflow.com/a/52354314
type: Question
tagged with: python
has title: Split lines in .txt file in Python
has body: I have a .txt file: My name is Richard And I want to get something like ['My', 'name is', 'Richard']. I tried file = open("Text.txt") strings = file.read() strings = strings.split() print(strings) But it gives me ['My', 'name', 'is', 'Richard']. So how can I get it line by line?
upvote count: 3

http://stackoverflow.com/comment/91600611
type: Comment
has text: I just checked everything, and realized that I globalized "files". There were some identical "files" words inside the big block of code, which I changed to "filess" or something. Thanks!
comment on: http://stackoverflow.com/a/52326368
score: 0
type: AnswerComment

http://stackoverflow.com/a/52344935
answers question: http://stackoverflow.com/q/52344910
type: AcceptedAnswer
has body: You can use findall: import re print([match for match in re.findall('[^rgb]+?[rgb]', '1b24g55r44r')]) Output ['1b', '24g', '55r', '44r'] The regex match: [^rgb]+? everything that is not rgb one or more times followed by one of [rgb]. If you need the result to be singleton lists you can do it like this: print([[match] for match in re.findall('[^rgb]+?[rgb]', '1b24g55r44r')]) Output [['1b'], ['24g'], ['55r'], ['44r']] Also if the string is only composed of digits and rgb you can do it like this: import re print([[match] for match in re.findall('\d+?[rgb]', '1b24g55r44r')]) The only change in the above regex is \d+?, that means match one or more digits. Output [['1b'], ['24g'], ['55r'], ['44r']]
upvote count: 7
type: Answer
downvote count: 0
score: 7
accepted answer of: http://stackoverflow.com/q/52344910

http://stackoverflow.com/q/52418270
type: Question
answer count: 2
downvote count: 2
has body: My string looks like this: bo_1 bo_1 bo_2 bo_2 bo_3 bo_3 bo_4 bo_4 bo_5 bo_5 bo_6 bo_6 bo_7 bo_7 bo_8 bo_8 bo_9 bo_9 bo_10 bo_10 I want to match the first instance of each digit and ignore the next duplicate line. My regex is as follows: (bo_\d)(?![\s\S]*\1) which returns the following: 'bo_2' 'bo_3' 'bo_4' 'bo_5' 'bo_6' 'bo_7' 'bo_8' 'bo_9' 'bo_1' How would I modify the regex to return a result like this instead (to include 'bo_1' at the start and 'bo_10' at the end): 'bo_1' 'bo_2' 'bo_3' 'bo_4' 'bo_5' 'bo_6' 'bo_7' 'bo_8' 'bo_9' 'bo_10'
upvote count: 3
has title: Python - Regex to avoid matching duplicates
favorite count: 0
has answer: http://stackoverflow.com/a/52418403
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52418321
tagged with: python
tagged with: regex
score: 1

http://stackoverflow.com/a/52429292
accepted answer of: http://stackoverflow.com/q/52428769
type: Answer
has comment: http://stackoverflow.com/comment/91806946
has comment: http://stackoverflow.com/comment/91806667
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91807446
has body: Use the pytz module from pytz import timezone current_timezone_time = ctx.message.author.joined_at new_timezone_time = current_timezone_time.astimezone(timezone('US/Pacific')) #do whatever In this example, I've converted it into US/Pacific but you can do whichever one you want.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52428769
downvote count: 0

http://stackoverflow.com/comment/91644237
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52348753
has text: @vash_the_stampede, you supported someone in writeing from one .py file to another instead of dumping a json. Hope OP has other sources to learn than us.
score: 0

kivy
tags question: http://stackoverflow.com/q/52424126
type: Tag
tags question: http://stackoverflow.com/q/52397887
tags question: http://stackoverflow.com/q/52283319
tags question: http://stackoverflow.com/q/52301798
tags question: http://stackoverflow.com/q/52314086
tags question: http://stackoverflow.com/q/52393623
tags question: http://stackoverflow.com/q/52286558
tag name: kivy
tags question: http://stackoverflow.com/q/52286908
tags question: http://stackoverflow.com/q/52344871
tags question: http://stackoverflow.com/q/52362590
tags question: http://stackoverflow.com/q/52302599
tags question: http://stackoverflow.com/q/52311003
tags question: http://stackoverflow.com/q/52304263
tags question: http://stackoverflow.com/q/52317725
tags question: http://stackoverflow.com/q/52348109
tags question: http://stackoverflow.com/q/52411630

http://stackoverflow.com/comment/92060824
comment on: http://stackoverflow.com/a/52406874
type: AnswerComment
has text: Cool! Seems the problem is resolved. Please mark the answer as accepted (gray check box under voting buttons at the left side should work for you).
score: 0
type: Comment

http://stackoverflow.com/a/60621783
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/127020458
has comment: http://stackoverflow.com/comment/138127952
answers question: http://stackoverflow.com/q/52285104
downvote count: 0
has body: There is no color palette specification for fig 2 but it looks like it is the Paired qualitative colormap from matplotlib (from here). So you need to specify that in your code for the 3D plot with the cmap argument and with the palette option in your pairplot. The legend is harder. You can make one from legend_elements. Better explained here. So your code would look like this (I got rid of the unused imports): import seaborn as sns, numpy as np, pandas as pd, random import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D sns.set_style("whitegrid", {'axes.grid' : False}) fig = plt.figure(figsize=(6,6)) ax = Axes3D(fig) x = np.random.uniform(1,20,size=20) y = np.random.uniform(1,100,size=20) z = np.random.uniform(1,100,size=20) g = ax.scatter(x, y, z, c=x, marker='o', depthshade=False, cmap='Paired') ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') # produce a legend with the unique colors from the scatter legend = ax.legend(*g.legend_elements(), loc="lower center", title="X Values", borderaxespad=-10, ncol=4) ax.add_artist(legend) plt.show()
type: Answer

http://stackoverflow.com/a/52540644
has body: The additional linker options should be added to: the Caffe2_DEPENDENCY_LIBS variable in pytorch/caffe2/CMakeLists.txt with the command: list(APPEND Caffe2_DEPENDENCY_LIBS &lt;linker_options&gt;) the C10D_LIBS variable in pytorch/torch/lib/c10d/CMakeLists.txt with the command: list(APPEND C10D_LIBS &lt;linker_options&gt;) The additional libraries should have Position Independent Code (they must be compiled with the -fPIC flag).
accepted answer of: http://stackoverflow.com/q/52384628
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52384628
type: Answer

http://stackoverflow.com/q/52424772
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/52425626
upvote count: 1
answer count: 1
tagged with: http://stackoverflow.com/tag/json
has title: Python: Error while reading and replacing String(with special characters) from file
tagged with: replace
linked to: http://stackoverflow.com/q/2081640
has comment: http://stackoverflow.com/comment/91792755
has body: a.json file: { "a": "b", "key": "graph: \"color\" = 'black' AND \"api\" = 'demo-application-v1' nodes", "c": "d" } following code I tried: string_to_be_replace = "abcd" string_to = "graph: \"color\" = 'black' AND \"api\" = 'demo-application-v1' nodes" string_to_be_identified = "\"color\" = \'black\' AND \"api\" = \'demo-application-v1\'" string_to_be_identified1 = '"color" = \'black\' AND "api" = \'demo-application-v1\'' print string_to_be_identified print string_to_be_identified1 print string_to.replace(string_to_be_identified1,string_to_be_replace) print string.replace(string_to, string_to_be_identified,string_to_be_replace) output: "color" = 'black' AND "api" = 'demo-application-v1' "color" = 'black' AND "api" = 'demo-application-v1' graph: abcd nodes graph: abcd nodes This is working fine and replacing string as expected but it is not when I tried the following approaches Approach 1: Open file in a read mode, get line by line and replace string with open(path + '/a.json', 'r') as file: read_lines = file.readlines() for line in read_lines: print line.replace(string_to_be_identified,string_to_be_replace) file.close() output: { "a": "b", "key": "graph: \"color\" = 'black' AND \"api\" ='demo-application-v1' node", "c": "d" } Approach 2: Open file in reading mode, Since the file a.json has JSON data, get JSON file loaded, convert JSON object to JSON-string and then replace it. Code: with open(path + '/a.json', 'r') as file: loadedJson = json.load(file) print "z: " + str(loadedJson).replace(string_to_be_identified, string_to_be_replace) file.close() output: z: {u'a': u'b', u'c': u'd', u'key': u'graph: "color" = 'black' AND "api" = 'demo-application-v1' node'} Approach 3: I assume Unicode character in JSON string might be creating a problem so converted Unicode string to normal string and then tried to replace string code: def byteify(input): if isinstance(input, dict): return {byteify(key): byteify(value) for key, value in input.iteritems()} elif isinstance(input, lis…
downvote count: 0
has answer: http://stackoverflow.com/a/52425626
score: 1
tagged with: string
tagged with: rawstring
type: AnsweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91792957

http://stackoverflow.com/comment/91509028
type: Comment
type: QuestionComment
has text: You seem to be assuming that `canvas.coords(img)` returns more than it actually does.
score: 0
comment on: http://stackoverflow.com/q/52280437

http://stackoverflow.com/q/52394985
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91736158
tagged with: wav
has title: Numpy: Wav to list and then back again creates garbage
score: 0
accepted answer: http://stackoverflow.com/a/52402780
answer count: 1
has comment: http://stackoverflow.com/comment/91735970
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52402780
has body: I'm using Python 3.7 and am currently developing a solution that requires me to convert a WAV file to a Numpy Array, then to a List, then back to an Array, and finally written again as a WAV file. Earlier today, it was able to convert and then reconvert with no issues. However, it is currently returning a WAV file that is listenable but is entirely static. import numpy as np import scipy.io.wavfile as wavfile ... rate, data = wavfile.read(os.path.join(F_IN_FOLDER, f)) work = data.tolist() out = np.array(work, dtype=np.float32) wavfile.write(os.path.join(F_IN_FOLDER, f), rate, out) The purpose of this code is so that, as a list, I can silence portions of the WAV file and then write over the original file. I am inexperienced with WAV files as well as the Numpy library, and if there is a more efficient way to this this, I'm interested in learning it.
has comment: http://stackoverflow.com/comment/91747010
tagged with: python
has comment: http://stackoverflow.com/comment/91736057
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91735187

http://stackoverflow.com/comment/91494460
comment on: http://stackoverflow.com/a/52273058
type: Comment
has text: your problem is that DISABLED and ENABLED are defined in tkinter itself.
score: 0
type: AnswerComment

http://stackoverflow.com/a/52369137
answers question: http://stackoverflow.com/q/52368146
score: 0
has body: Because A is a matrix, Python calls A's __mul__ method to compute A*b, with b as its argument. That is, it calls A.__mul__(b). A numpy matrix insists on making everything a 2-d matrix, so it converts b to a matrix before performing the matrix multiplication. When b is converted to a numpy matrix, the result has shape (1, 3): In [248]: b Out[248]: array([1., 1., 1.]) In [249]: np.matrix(b).shape Out[249]: (1, 3) Then __mul__ complains that the shapes are not aligned, because A has shape (3, 3) and the converted b has shape (1, 3). One way to fix this is to ensure that b is 2-d with shape (3, 1) before doing the multiplication: In [250]: b = ones((3, 1)) In [251]: A * b Out[251]: matrix([[1.], [1.], [1.]]) In the long term, though, it would be better to modify your code to not use matrix at all, as mentioned by @w-m.
type: Answer

http://stackoverflow.com/comment/91697380
comment on: http://stackoverflow.com/a/52376251
type: AnswerComment
type: Comment
has text: As mentioned maybe try a new question with your data and what you want to accomplish I'm sure we will be able to find a solution :)
score: 0

http://stackoverflow.com/q/52308096
accepted answer: http://stackoverflow.com/a/52330119
answer count: 2
has body: I initially started a small python project (Python, Tkinter amd PonyORM) and became larger that is why I decided to divide the code (used to be single file only) to several modules (e.g. main, form1, entity, database). Main acting as the main controller, form1 as an example can contain a tkinter Frame which can be used as an interface where the user can input data, entity contains the db.Enttiy mappings and database for the pony.Database instance along with its connection details. I think problem is that during import, I'm getting this error "pony.orm.core.ERDiagramError: Cannot define entity 'EmpInfo': database mapping has already been generated". Can you point me to any existing code how should be done.
downvote count: 0
possible better answer: http://stackoverflow.com/a/52416542
upvote count: 2
has answer: http://stackoverflow.com/a/52330119
has title: Sharing PonyORM's db session across different python module
favorite count: 0
has answer: http://stackoverflow.com/a/52416542
tagged with: python
tagged with: ponyorm
type: AnsweredQuestion
score: 2
type: Question

http://stackoverflow.com/a/52408022
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/52407819
score: 3
answers question: http://stackoverflow.com/q/52407819
has body: If you replace the spaces with commas, you can use json.loads to read the string as a list, and pass that to np.asarray: import json import numpy as np foo = "[[7.0352220e-01 5.3130367e-06 1.5167372e-05 1.0797821e-06] \ [1.3130367e-06 2.4584832e-01 2.2375602e-05 7.3299240e-06]]" a = np.asarray(json.loads(foo.replace(" ", ",")), dtype=np.float32) print(a) #array([[7.0352220e-01, 5.3130367e-06, 1.5167372e-05, 1.0797821e-06], # [1.3130367e-06, 2.4584832e-01, 2.2375602e-05, 7.3299240e-06]]) print(a.dtype) #float32 This assumes there is exactly 1 space between values. If that is not the case, you can use re.sub to replace multiple spaces with a comma: import re a = np.asarray(json.loads(re.sub("\s+", ",", foo))) #array([[7.0352221e-01, 5.3130366e-06, 1.5167372e-05, 1.0797821e-06], # [1.3130367e-06, 2.4584831e-01, 2.2375601e-05, 7.3299238e-06]], # dtype=float32)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52295349
type: Question
has answer: http://stackoverflow.com/a/52295977
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/52295450
tagged with: for-loop
downvote count: 0
tagged with: multiple-columns
favorite count: 0
type: UnansweredQuestion
has title: Calculating a new column with numpy using for loop
tagged with: python
score: 1
upvote count: 1
has body: i have a Dataset called np_charge in numpy with a size of (1430, 258). My idea is to create a new column where the first row contains the output of the equation first row: np_charge[-1][1]-np_charge[0][1] second row: np_charge[-1][1]-np_charge[1][1] . . . last row: np_charge[-1][1]-np_charge[1429][1] I tried to find solutions in the internet but couldn't find any. My solution looks like this: e=[] n_rows=np_charge.shape[0]-1 for i in range(n_rows): e[i]=(np_charge[-1][1]-np_charge[i][1]) But I get this error code: --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-988-9463a5cb0618&gt; in &lt;module&gt;() 15 16 for i in range(n_rows): ---&gt; 17 e[i]=np_charge[-1][1]-np_charge[i][1] 18 19 IndexError: list assignment index out of range Thanks, R

http://stackoverflow.com/a/52384772
has body: Question: it is not clear which format should be the privatekey and the publickey Source on GitHub tells: def userauth_publickey_fromfile(self, username not None, privatekey not None, passphrase='', publickey=None): From the Documentation, only for publickey, the types explained. For security reasons, a Private Key should never stored inside a python script. You have to read it from a access restriced file storage. You are right, the Parameters should be explained as in userauth_publickey(...). Documentation userauth_publickey...
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52378910
score: 1
upvote count: 1

http://stackoverflow.com/comment/91775287
has text: Please accept the answer if it has solved your query
type: Comment
comment on: http://stackoverflow.com/a/52415615
type: AnswerComment
score: 0

http://stackoverflow.com/a/52371983
has comment: http://stackoverflow.com/comment/91688957
type: Answer
has comment: http://stackoverflow.com/comment/91688940
accepted answer of: http://stackoverflow.com/q/52371716
has body: Simple approach is to replace ns_list with a dict, then replace ns_list.append(ns) with ns_dict[num, i] = ns. Alternatively, to keep the palindromes as the top level iterable component, you can store all the pairs that produced a particular palindrome in a list, using collections.defaultdict(list) to simplify the code: from collections import defaultdict ns_dict = defaultdict(list) #outside for loop with first 3-digit 'num' and inside loop with second 3-digit 'i' for num in range(100,1000): for i in range(100,1000): n = i*num ns = str(n) if ns[::-1] == ns: ns_dict[ns].append((num, i)) Now when you iterate ns_dict, you can see all the pairs you checked that produced that palindrome: ns_list_with_factors = sorted(ns_dict.items(), key=lambda x: int(x[0]), reverse=True) print(ns_list_with_factors[0]) # Displays both number and the pairs that produced it for ns, pairs in ns_dict.items(): ...
answers question: http://stackoverflow.com/q/52371716
score: 0
has comment: http://stackoverflow.com/comment/91689026
type: AcceptedAnswer

http://stackoverflow.com/comment/91703037
score: 0
has text: Thank you again but if possible, is it alright for you to check my this post and give me some comments about my understanding between feature extraction and word2vec? Thank you. https://stackoverflow.com/questions/52379317/word2vec-is-it-for-word-only-in-a-sentence-or-for-features-as-well
type: AnswerComment
comment on: http://stackoverflow.com/a/52320963
type: Comment

http://stackoverflow.com/comment/91741536
score: 1
comment on: http://stackoverflow.com/q/52398066
type: Comment
type: QuestionComment
has text: From where did you imported `User` in your view ?

http://stackoverflow.com/q/52404529
has answer: http://stackoverflow.com/a/59321026
has answer: http://stackoverflow.com/a/63873647
has comment: http://stackoverflow.com/comment/92227929
has answer: http://stackoverflow.com/a/70275559
answer count: 14
has title: 'Cannot setup a Python SDK' in PyCharm project using virtualenv after OS reinstallation
downvote count: 0
tagged with: virtualenv
has answer: http://stackoverflow.com/a/54619984
has answer: http://stackoverflow.com/a/58384043
favorite count: 0
linked to: http://stackoverflow.com/q/34618858
has answer: http://stackoverflow.com/a/70639439
has answer: http://stackoverflow.com/a/52553043
has answer: http://stackoverflow.com/a/59365742
has comment: http://stackoverflow.com/comment/92044632
has body: I re-installed windows and opened an existing Pycharm project and get the error 'SDK seems invalid' in Settings > Project Interpreter. The project interpreter path is pointing to python in the venv: MyProject\venv\Scripts\python.exe I tried re-adding python.exe: Thats when I get the error: Update: here is an error from idea.log, a lot of other issues for virtual environments seem to be with windows environment variables and system paths: 2018-09-28 19:50:40,275 [ 17601] INFO - hon.packaging.PyPIPackageCache - Loaded 153296 packages from C:\Users\Matt\.PyCharm2018.2\system\python_packages\pypi-cache.json 2018-09-28 19:50:40,816 [ 18142] INFO - rains.python.sdk.PythonSdkType - Fatal Python error: Py_Initialize: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' Current thread 0x00000fa8 (most recent call first): Exit code -1073740791 2018-09-28 19:50:40,816 [ 18142] ERROR - ns.python.sdk.PythonSdkUpdater - Failed to determine Python's sys.path value: STDOUT: STDERR: Fatal Python error: Py_Initialize: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' Current thread 0x00000fa8 (most recent call first): com.jetbrains.python.sdk.InvalidSdkException: Failed to determine Python's sys.path value: STDOUT: STDERR: Fatal Python error: Py_Initialize: unable to load the file system codec ModuleNotFoundError: No module named 'encodings'
has answer: http://stackoverflow.com/a/72094911
tagged with: python
has answer: http://stackoverflow.com/a/71983777
has answer: http://stackoverflow.com/a/62700135
has answer: http://stackoverflow.com/a/75142163
has comment: http://stackoverflow.com/comment/92228861
tagged with: pycharm
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92041433
has answer: http://stackoverflow.com/a/69688126
linked to: http://stackoverflow.com/q/31840195
type: Question
has answer: http://stackoverflow.com/a/72293570
score: 76
upvote count: 76

http://stackoverflow.com/comment/91707971
score: 0
type: Comment
type: QuestionComment
has text: @ead Cython definitely did improve speed. It made it 4-5 times as fast by just adding types for the variables. But I have issues with deployment with cython (constraint 2). Numba/Numpy doesnt seem to add much value though.
comment on: http://stackoverflow.com/q/52378578

http://stackoverflow.com/comment/91929879
type: Comment
has text: Looking at this a little more, it's not --concurrency that had to be removed from the command line, it was --source. I've changed the message again. Now it will say, "Options affecting multiprocessing must only be specified in a configuration file. Remove --source from the command line."
type: AnswerComment
comment on: http://stackoverflow.com/a/52379777
score: 0

http://stackoverflow.com/q/52351914
has comment: http://stackoverflow.com/comment/91649526
answer count: 1
has title: file handling runtime error - python in pycharm
has answer: http://stackoverflow.com/a/52353735
score: 0
has comment: http://stackoverflow.com/comment/91648873
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91648820
has body: My script program as folows- fname = raw_input('Enter a file name: ') f1 = open(fname) for line in f1: line1 = line.capitalize() print line1 How to solve this error? File " ", line 1, in <module> File "D:\PyCharm Community Edition 2018.2.2\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile pydev_imports.execfile(filename, global_vars, local_vars) # execute the script File "D:/Pycharm Projects/Files/p7.1.py", line 5, in <module> f1 = open(file_name) IOError: [Errno 2] No such file or directory: 'D:/Pycharm Projects/Files/fname\\mbox-short.text'
type: Question

http://stackoverflow.com/comment/91663352
score: 1
type: Comment
comment on: http://stackoverflow.com/a/52359351
has text: @AvivShai, to your EDIT: No one is offended, IMHO, but **"Special cases aren't special enough to break the rules."** See [The Zen of Python](https://www.python.org/dev/peps/pep-0020/) or - alternatively - write `import this` to the Python interactive console.
type: AnswerComment

http://stackoverflow.com/comment/91552340
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52302106
has text: Mutating a dictionary (adding/removing keys) is indeed different from mutating a value mapped to a particular key. It's only the first thing you should avoid while iterating over its keys.

http://stackoverflow.com/comment/91664572
has text: Please update your question with the relevant code.If the link goes 404, it has no value for future users.
score: 3
comment on: http://stackoverflow.com/q/52360088
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52285759
upvote count: 0
tagged with: string
has comment: http://stackoverflow.com/comment/91519986
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52285814
tagged with: datetime
tagged with: python
has title: converting date from string to a required DateTime format in python
downvote count: 1
possible better answer: http://stackoverflow.com/a/52286227
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52286227
has answer: http://stackoverflow.com/a/52285814
score: -1
has body: I have a date in string format. I want to convert it to a required DateTime format(mm-dd-yyyy). Here is the code which I am using: from datetime import datetime demoDate='03-25-17' requiredDate = datetime.strptime(demoDate, '%m-%d-%y').strftime('%m-%d-%Y') print(requiredDate) print(type(requiredDate)) The output which I am getting is: 03-25-2017 &lt;class 'str'&gt; May I know if I can get my required output format but in DateTime format not string?
type: Question
answer count: 2

http://stackoverflow.com/comment/91746725
score: 0
type: Comment
has text: I don't think this answer's the OP's question. As far as I can tell, they're asking why `open` accepts duplicated backslashes like in `r"D:\\users\\xy"`.
comment on: http://stackoverflow.com/a/52401442
type: AnswerComment

http://stackoverflow.com/comment/91627213
comment on: http://stackoverflow.com/a/52339988
has text: @Bazingaa true, but there is... You can run the snippet I posted in my question and you'll see the output of a numpy Polynomial with such domain and coefs passes through (0,0).
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52361941
has comment: http://stackoverflow.com/comment/91668423
has body: I connect local database to app then I want to bring these data into app again to be edited. That is my code import sys import os import time from PyQt5 import QtCore, QtGui, QtWidgets, uic import mysql.connector from mysql.connector import errorcode FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__),"mahmoudtarek.ui")) class Main(QtWidgets.QMainWindow, FORM_CLASS): def __init__(self,parent=None): super(Main,self).__init__(parent) self.setupUi(self) self.InitUI() self.conn = None self.handle_buttons() self.handle_db_connections() def InitUI(self): ## changes in the run time pass def handle_buttons(self): ## all buttons in the app self.pushButton.clicked.connect(self.add_mahmoud_friends) self.pushButton_3.clicked.connect(self.update_mahmoud_friends) self.pushButton_2.clicked.connect(self.delete_mahmoud_friends) self.pushButton_6.clicked.connect(self.search_mahmoud_friends) def handle_db_connections(self): try: self.conn = mysql.connector.connect( host='127.0.0.1', database='mydb', user='root', password='134668691011', use_pure=True) # use_pure is set to true if self.conn.is_connected(): db_Info = self.conn.get_server_info() print("Connected to MySQL database using C extension... MySQL Server version on ", db_Info) except mysql.connector.Error as err: print("Error while connecting to MySQL using C extension", err) def add_mahmoud_friends(self): mth_friends = self.lineEdit.text() mth_search = self.lineEdit_4.text() if self.conn: c = self.conn.cursor() try: c.execute('''INSERT INTO ahmed (mth_friends,mth_search) values (%s,%s)''', (mth_friends,mth_search)) self.conn.commit() self.lineEdit.setText('') self.lineEdit_4.setText('') self.statusBar.showMessage('ok mahmoud') except mysql.connector.Error as err: print("Error: ", err) def update_mahmoud_friends(self): pass def delete_mahmoud_friends(self): pass def search_mahmoud_friends(self): sql = '''SELECT * FROM ahmed WHERE mth_search = %s''' mth_search = self.lineEdit_3.text() self.conn.cursor.execute(sq…
downvote count: 1
has comment: http://stackoverflow.com/comment/91668279
type: UnansweredQuestion
upvote count: 0
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/52362782
has answer: http://stackoverflow.com/a/52363211
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/91668912
tagged with: pycharm
has title: How to import data from SQL Database?
answer count: 3
tagged with: mysql
has answer: http://stackoverflow.com/a/52362387
linked to: http://stackoverflow.com/q/372885

http://stackoverflow.com/q/52356730
type: Question
has comment: http://stackoverflow.com/comment/91659018
tagged with: highcharts
answer count: 1
has comment: http://stackoverflow.com/comment/91658444
score: 0
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/52357293
tagged with: python-3.x
type: UnansweredQuestion
has body: I have this total_of_each_error data frame: month name errors count 0 January ABCD Big 1 1 January ABCD Monitoring 3 2 January WORLD Small 1 3 January Channel Big 2 4 January Channel Small 1 5 January Channel Monitoring 1 6 January AVR Monitoring 1 7 March WORLD Monitoring 2 8 April Migration Big 1 9 April Migration Monitoring 2 10 May P&amp;G Small 1 11 May P&amp;G Monitoring 1 12 May ABCD Monitoring 1 13 May WORLD Improvement 1 14 June P&amp;G Monitoring 1 15 June ABCD Small 1 16 June ABCD Monitoring 1 I have written this function: import pandas as pd from itertools import product def get_chartdata(df): months = df['month'].unique().tolist() no_of_errors = df['errors'].unique().tolist() name = df['name'].unique().tolist() cross_df = pd.DataFrame(list(product(months, name, no_of_errors)), columns=['month','name','errors']) merged_df = pd.merge(total_of_each_error,cross_df,how='outer', left_on=['month','name','errors'], right_on=['month','name','errors']).drop_duplicates().fillna(0) pivot_df = merged_df.pivot_table(columns='month', index=['name','errors'], values='count', fill_value=0).reset_index() data = {} for index, row in pivot_df.iterrows(): if (row['name']) not in data.keys(): data[row['name']] = [] data[row['name']].append({'name':row.values[1:2].tolist() , 'data': row.values[2:].tolist()}) x_axis = {} for i in pivot_df['name'].unique(): df1 = pivot_df[pivot_df['name'] == i] x_axisData = pivot_df.columns[2:].unique() x_axis[i] = {'categories': x_axisData.tolist()} return data, x_axis print(get_chartdata(total_of_each_error)) prints the following: ({'P&amp;G': [{'name': ['Big'], 'data': [0, 0, 0, 0, 0]}, {'name': ['Small'], 'data': [0, 0, 0, 0, 1]}, {'name': ['Monitoring'], 'data': [0, 0, 1, 0, 1]}, {'name': ['Improvement'], 'data': [0, 0, 0, 0, 0]}], 'ABCD': [{'name': ['Big'], 'data': [0, 1, 0, 0, 0]}, {'name': ['Small'], 'data': [0, 0, 1, 0, 0]}, {'name': ['Monitoring'], 'data': [0, 3, 1, 0, 1]}, {'name': ['Improvement'], 'data': [0, 0, 0, 0, 0]}], 'WORLD':…
has title: Writing a Function Using pandas and Returning Data in Required Format

http://stackoverflow.com/q/52337153
type: Question
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0
tagged with: maya
score: 2
type: UnansweredQuestion
tagged with: python
tagged with: plugins
has answer: http://stackoverflow.com/a/52376427
has title: Execute GameFbxExporter Maya with Python
has body: I need to export thousand of files with the GameFbXExporter Plugin from Maya, and I was wondering if there was any way to script those exports, knowing that the parameters are fine in every files. All I need to do is fill the path section and the name of the exported file in FBX, then launching the export itself with the plugin. I'm kind of lost and doesn't know how to do this. Could someone help me understand how to reach that please? Thank you

http://stackoverflow.com/a/52327265
accepted answer of: http://stackoverflow.com/q/52326962
answers question: http://stackoverflow.com/q/52326962
has comment: http://stackoverflow.com/comment/91602351
has body: You can use partial to create a function callable later. For example: funcs = [partial(work, arg1, arg2) for arg1, arg2 in arg_instances] Parallel(...)(delayed(f) for f in funcs)) Partial is a very handy and useful python builtin function, give it a shot! Anyway looking at the library (joblib) you are using, probably this will fix Parallel(...)(delayed(work)(arg1, arg2) for arg1, arg2 in arg_instances)) Actually it is not working because you are calling "work" function with the entire "arg_instances" list as first positional parameter.
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/91602537
score: 2

http://stackoverflow.com/comment/91629464
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52341266
type: AnswerComment
has text: @Austin So far, _all_ answers make this assumption. I doubt it is possible to answer the question as asked without using NLP of some sort. So, a regex solution is not worse than any other.

http://stackoverflow.com/q/52359769
type: Question
tagged with: python
tagged with: visual-studio
score: -1
has title: Problem building python solution with c++ component in Visual Studio 2017
tagged with: c++
has body: I tried to open a project/solution twslink2pt.sln (a Python 3.6 wrapper with c++ component) using the Visual Studio 2017, the following message is displayed. 1&gt;------ Build started: Project: twslink2pt, Configuration: Release Win32 ------ 1&gt;Performing Custom Build Tools 1&gt;In order to function correctly, please ensure the following environment variables are correctly set: 1&gt;PYTHON_INCLUDE: 1&gt;PYTHON_LIB: 1&gt;The system cannot find the path specified. 1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7 \IDE\VC\VCTargets\Microsoft.CppCommon.targets(209,5): error MSB6006: "cmd.exe" exited with code 3. 1&gt;Done building project "twslink2pt.vcxproj" -- FAILED. ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== This project/solution twslink2pt.sln has different installation than mine. My python.exe is installed with Visual Studio 2017 and located in C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64. I am using Window 10. I need to either adjust my python installation to match with what is set in the project or adjust the project to match with my python installation. How do I change the include path in the c++ settings in Visual Studio 2017 to point to the correct library (C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\include)? For the linking I need the python36.lib. The python36.lib is in C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\libs. How do I include the python36.lib in the linking in Visual Studio 2017? Any ideas? Thank you.
downvote count: 1
has answer: http://stackoverflow.com/a/52372039
type: UnansweredQuestion
tagged with: visual-studio-2017
upvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/91528060
comment on: http://stackoverflow.com/a/52284726
has text: @coldspeed: Thank you very much!
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52284965
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91518497
has comment: http://stackoverflow.com/comment/91518377
has comment: http://stackoverflow.com/comment/91518919
has title: numberVarible Not Displaying to the Right of id: in JavaScript / jQuery Code
has comment: http://stackoverflow.com/comment/91518589
has comment: http://stackoverflow.com/comment/91518658
type: Question
has body: There are two parts to this question: Part A: When I run the code below, "numberVariable" is displaying as the text "numberVariable" within the javascript instead of the actual value of 1. How do I get it to display as 1 to the right of id: -- Do I have to pass it in somehow? Also, alert(numberVariable); does print the value of 1 when I run the HTML. There's something I'm not understanding with the code as this is the first time I've tried to build a widget. The code works when I hard code a value of id: "1" into the code, but not when it is id: numberVariable. Part B: How would I then send numberVariable into the Python file without affecting the callback that already works? "https://example.com/cgi-bin/data.py?callback=?"; Thanks for the help. Here is the HTML Code: &lt;script src="https://example.com/widget/externalJSfileContainingTheCodeBelow.js" async&gt;&lt;/script&gt;&lt;div id="widget" dataVar="1"&gt;&lt;/div&gt; Here is the Javascript / jQuery Code (function () { var jQuery; if (window.jQuery === undefined) { var script_tag = document.createElement('script'); script_tag.setAttribute("type", "text/javascript"); script_tag.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"); if (script_tag.readyState) { script_tag.onreadystatechange = function () { if (this.readyState == 'complete' || this.readyState == 'loaded') { scriptLoadHandler(); } }; } else { script_tag.onload = scriptLoadHandler; } (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag); } else { jQuery = window.jQuery; main(); } function scriptLoadHandler() { jQuery = window.jQuery.noConflict(true); main(); } function main() { jQuery(document).ready(function ($) { var element = document.getElementById('widget'); var numberVariable = element.getAttribute('dataVar'); alert(numberVariable); $.ajax({ type: "GET", url: "https://example.com/widget/widget-updater.php", data: { id: numberVariable } }); var css_link = $("&lt;link&gt;",…
has comment: http://stackoverflow.com/comment/91518727
has comment: http://stackoverflow.com/comment/91518962
tagged with: javascript
tagged with: jquery
has comment: http://stackoverflow.com/comment/91518503
has comment: http://stackoverflow.com/comment/91518527
has comment: http://stackoverflow.com/comment/91518625
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91518663

http://stackoverflow.com/a/52295371
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52295283
has body: Instead of setting a random state, you should try shuffling the data before splitting. You can do this by setting the parameter: shuffle=True.

http://stackoverflow.com/comment/91570107
has text: It worked because what you gave input was all numbers for sure. Most probably case is that there's one value in you `x` or `Y` which is either some english character or more likely it's empty. In other words there's one or more values which are empty. Try to find thm by using subsets of `X` and `Y`. To confirm my point, replace any of the `0's` in `feed_dict` with empty string`( ' ')`. It should give the same error.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52309568
type: QuestionComment

http://stackoverflow.com/q/52414542
answer count: 0
tagged with: image-processing
type: Question
tagged with: numpy
tagged with: opencv
tagged with: matplotlib
score: 0
has title: How do we draw a curve between outlines / boundaries in Python?
has comment: http://stackoverflow.com/comment/91775497
has comment: http://stackoverflow.com/comment/91775540
type: UnansweredQuestion
tagged with: python
has body: I want to draw dotted curve between the boundaries. For eg, consider the following image: From the image, I have the dark outline - what I want is the dotted part through code. As of now, I have the following algorithm: For each point say A, find it's two nearest points Form these two points, find it's slope, and then the slope of the line perpendicular to it. The using the perpendicular slope and point A, determine the line and also where it intersects the parallel point, say B Draw a point half way between A and B on this perpendicular line. This method is like Brute force. I think using numpy, opencv or plotting libraries, this might be a trivial thing. Do you have any suggestions? Thank you

http://stackoverflow.com/comment/91655268
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52355311
has text: No, we can't help, because you haven't shown any code.

http://stackoverflow.com/q/52389675
has comment: http://stackoverflow.com/comment/91729396
tagged with: matplotlib
has body: How can I create a custom diverging colormap in matplotlib such that it would use a single color (i.e. the same color on the vmin and vmax ends, and white in the middle)? All of the default ones use 2 different colors: https://matplotlib.org/examples/color/colormaps_reference.html I need to show cases where some value deviates from its mean and it is more important to show the magnitude of the deviation and not the direction (direction will the shown through cell annotations). Thank you for your help!
duplicate of: http://stackoverflow.com/q/16834861
type: Question
tagged with: colormap
has comment: http://stackoverflow.com/comment/91725851
tagged with: customization
score: 0
has comment: http://stackoverflow.com/comment/91729739
tagged with: colors
linked to: http://stackoverflow.com/q/16834861
type: UnansweredQuestion
tagged with: python
has title: Creating MatPlotLib diverging colormap with a single color
answer count: 0

http://stackoverflow.com/comment/91786371
comment on: http://stackoverflow.com/a/52421459
type: AnswerComment
score: 0
has text: I still do not understand. My parents structure remains untouched and it has worked perfectly for other queries. The error is mentioning data type mismatches so I am assuming the strings and number values may be the issue?
type: Comment

http://stackoverflow.com/a/52425456
answers question: http://stackoverflow.com/q/52425137
score: 5
upvote count: 5
accepted answer of: http://stackoverflow.com/q/52425137
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: In YAML, \ is a special character only in doubly-quoted strings. The Python string r'\\\|' is a raw string, so it consists of three backslashes and a pipe. You have the following options to encode this in a YAML document: plain: \\\| # plain scalar. YAML does not process the backslashes. single: '\\\|' # single quoted scalar. YAML also does not process the backslashes. double: "\\\\\\|" # double quoted scalar. YAML does process escape sequences here, so you # need to double the backslashes Single-quoted scalars are kind-of the YAML equivalent of Python's raw strings. You may have other characters in your regexes that may interfere with YAML's syntax. You may want to use block scalars instead, which treat all characters as content and are ended via indentation: block: |- \\\| next block: |- \\\| | starts a literal block scalar, - causes the final linebreak (before the next item) to not be part of the scalar, which is what you want.

http://stackoverflow.com/a/52425509
has body: Seems like in the GDP column there are decimal values from the first column in the .csv file and first digits of the second column. There's either something wrong with the .csv you created, but more probably you need to specify separator in the pandas.read_csv line. Also, add header=None, to make sure you don't lose the first line of the file (i.e. it will get replaced by colnames). Try this: import pandas colnames = ['GDP', 'Unemployment', 'CPI', 'HousePricing'] data = pandas.read_csv('Dane_2.csv', names = colnames, header=None, sep=';') GDP = data.GDP.tolist() print(GDP)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91794079
score: 1
accepted answer of: http://stackoverflow.com/q/52425403
type: Answer
answers question: http://stackoverflow.com/q/52425403
upvote count: 1
has comment: http://stackoverflow.com/comment/91793991

http://stackoverflow.com/a/53353699
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/52424543
downvote count: 0
answers question: http://stackoverflow.com/q/52424543
has body: You can't see from the MemoryError exception, and the exception is raised for any situation where memory allocation failed, including Python internals that do not directly connect to code creating new Python data structures; some modules create locks or other support objects and those operations can fail due to memory having run out. You also can't necessarily know how much memory would be required to have the whole operation succeed. If the library creates several data structures over the course of operation, trying to allocate memory for a string used as a dictionary key could be the last straw, or it could be copying the whole existing data structure for mutation, or anything in between, but this doesn't say anything about how much memory is going to be needed, in addition, for the remainder of the process. That said, Python can give you detailed information on what memory allocations are being made, and when, and where, using the tracemalloc module. Using that module and an experimental approach, you could estimate how much memory your data set would require to complete. The trick is to find data sets for which the process can be completed. You'd want to find data sets of different sizes, and you can then measure how much memory those data structures require. You'd create snapshots before and after with tracemalloc.take_snapshot(), compare differences and statistics between the snapshots for those data sets, and perhaps you can extrapolate from that information how much more memory your larger data set would need. It depends, of course, on the nature of the operation and the datasets, but if there is any kind of pattern tracemalloc is your best shot to discover it.
score: 4
type: AcceptedAnswer

http://stackoverflow.com/a/52367800
accepted answer of: http://stackoverflow.com/q/52367739
has comment: http://stackoverflow.com/comment/91703871
has comment: http://stackoverflow.com/comment/91681308
answers question: http://stackoverflow.com/q/52367739
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91680593
has comment: http://stackoverflow.com/comment/91681412
upvote count: 2
has comment: http://stackoverflow.com/comment/91681068
type: Answer
has body: Multiply (u, v) with a 2D index grid: ind = np.indices((512, 512)) pixels = ind[0, ..., np.newaxis] * u + ind[1, ..., np.newaxis] * v &gt;&gt;&gt; %timeit ind = np.indices((512, 512)); pixels = ind[0, ..., np.newaxis] * u + ind[1, ..., np.newaxis] * v 8.06 ms ± 69.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) Multiply u with a 1D index range, multiply v with a 1D index range, broadcast and combine to 2D: i512 = np.arange(512)[:, np.newaxis] pixels = (i512 * u)[:, np.newaxis, :] + (i512 * v)[np.newaxis, :, :] &gt;&gt;&gt; %timeit i512 = np.arange(512)[:, np.newaxis]; pixels = (i512 * u)[:, np.newaxis, :] + (i512 * v)[np.newaxis, :, :] 4.06 ms ± 58.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
score: 2

http://stackoverflow.com/a/52437895
has body: First, profile. If the profile tells you that it's evaluations if fun, then your best bet is to either numba.jit it, or rewrite it in Cython.
score: 0
answers question: http://stackoverflow.com/q/52349283
type: Answer

http://stackoverflow.com/a/52387572
answers question: http://stackoverflow.com/q/52387466
has body: Just install PyYAML https://pypi.org/project/PyYAML/ Then : import yaml yaml_as_python_dict = yaml.load(yaml_as_string_or_bytes) https://pyyaml.org/wiki/PyYAML
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/92520572
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/91909104
type: Comment
type: QuestionComment
score: 1
has text: Sorry if this is a bit late, but I'm just learning Eve. Maybe this will help. I think that if you remove the "^" from your regex definitions that you may get the result you're looking for.
comment on: http://stackoverflow.com/q/52306826

http://stackoverflow.com/comment/91664237
type: Comment
type: QuestionComment
has text: Can you provide sample output (desired result)?
comment on: http://stackoverflow.com/q/52359897
score: 0

http://stackoverflow.com/comment/91493043
type: Comment
type: QuestionComment
has text: You mean you want to enable that button only after a certain condition is met?
comment on: http://stackoverflow.com/q/52272942
score: 0

http://stackoverflow.com/comment/91813640
type: Comment
has text: Thank you everyone, like you said SignedJwtAssertionCredentials has been deprecated , and now we should be using ServiceAccountCredentials.
comment on: http://stackoverflow.com/a/52414229
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91789163
comment on: http://stackoverflow.com/q/52423013
score: 0
type: QuestionComment
has text: Is it actually `/q=` or `/?q=`?
type: Comment

http://stackoverflow.com/a/52416250
has comment: http://stackoverflow.com/comment/91781650
type: Answer
has body: After trying many possible ways i have found the solution with openCV library. This doesn't throw me any compression error and handled conversion like a charm. import cv2 image = cv2.imread(img) cv2.imwrite(imag_name.replace('.bmp', '.jpg'), image) Thanks for @Mark for his suggestion too. As i have to convert large number of images and openCV seems lite to handle the problem I am going with openCV.
score: 2
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52398468
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52398468

http://stackoverflow.com/a/52395240
has comment: http://stackoverflow.com/comment/91735955
upvote count: 7
has comment: http://stackoverflow.com/comment/91735784
score: 7
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52395179
has body: You can use infer_objects: In [11]: df.infer_objects() Out[11]: sepal-length sepal-width petal-length petal-width class 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa 3 4.7 3.2 1.3 0.2 setosa 4 4.6 3.1 1.5 0.2 setosa 5 5.0 3.6 1.4 0.2 setosa In [12]: df.infer_objects().dtypes Out[12]: sepal-length float64 sepal-width float64 petal-length float64 petal-width float64 class object dtype: object The issue is that whilst the right-hand-side is correct: In [21]: df.iloc[:,:-1].astype(float).dtypes Out[21]: sepal-length float64 sepal-width float64 petal-length float64 petal-width float64 dtype: object The assignment df.iloc[:,:-1] = is updating existing columns and not changing their dtype.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52395179
type: Answer

http://stackoverflow.com/comment/91773961
has text: I just tried the following on my idle `float("10.0").is_integer()` outputs `True` and `float("10.20").is_integer()` which outputs `False`, so maybe you can try store the statement `float(gravity).is_integer()` into a `variable` e.g. `x = float(gravity).is_integer()` and then try `if (not x)`
comment on: http://stackoverflow.com/q/52414962
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52393600
answer count: 2
score: 5
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/75580885
tagged with: python
has answer: http://stackoverflow.com/a/75580885
has answer: http://stackoverflow.com/a/52398779
type: AnsweredQuestion
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52398779
tagged with: eyed3
type: Question
has title: How to remove existing album art image from an Mp3 using eyed3 module
upvote count: 5
has body: I have been attempting to use the eyed3 module for tagging mp3 files, but unfortunately, I find the module documentation difficult to understand and was wondering if someone can help me?.. Documentation can be found at https://eyed3.readthedocs.io I was trying to use it to remove existing album art image using: import eyed3 x = eyed3.load('file_path') x.tag._images.remove() x.tag.save() But when I run this code, it gives me the following error: TypeError: remove() missing 1 required positional argument: 'description' I am not sure where to find the above mentioned description to pass as a parameter. I have also looked at the source python file for eyed3 tagging, but based on investigating the code, I can't seem to find out what to pass for this argument description. I attempted to pass an empty string as the argument, but although the script ran fine without any errors, it did not remove the album art image. Please help.

http://stackoverflow.com/q/52309571
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91567130
tagged with: python
has answer: http://stackoverflow.com/a/52311545
has title: give the same login as password
type: UnansweredQuestion
downvote count: 1
tagged with: odoo
tagged with: odoo-8
score: -1
has body: I want to give a password for a specific user but when I use password '123' as an example he shows me this message You can not create a new user from here To create a new user, please use the control panel how to fix that this is my code py class access_teacher(models.Model): _inherit = 'res.partner' is_teacher = fields.Boolean(string="Is teacher") def create(self, cr, uid, vals, context=None): user_obj = self.pool.get('res.users') vals_user = {'password':'123'} user_obj.create(cr, uid, vals_user, context) result = super(access_teacher, self).create(cr, uid, vals, context=context) #to test if user = is_teacher #vals['password_crypt'] = '123' #self.env['res.users'].write({'password': '123'}) return result
type: Question

http://stackoverflow.com/comment/91893610
has text: Thanks Roman, your answer is very explanatory and addresses many questions I had about TDD in general and with Django.
comment on: http://stackoverflow.com/a/52447763
score: 0
type: AnswerComment
type: Comment

apache-spark-sql
tags question: http://stackoverflow.com/q/52350339
tags question: http://stackoverflow.com/q/52312543
tags question: http://stackoverflow.com/q/52338462
tags question: http://stackoverflow.com/q/52412597
tags question: http://stackoverflow.com/q/52275705
tags question: http://stackoverflow.com/q/52375797
tags question: http://stackoverflow.com/q/52322216
tags question: http://stackoverflow.com/q/52343688
tag name: apache-spark-sql
tags question: http://stackoverflow.com/q/52287553
tags question: http://stackoverflow.com/q/52319958
type: Tag
tags question: http://stackoverflow.com/q/52299443

http://stackoverflow.com/q/52393169
type: Question
tagged with: networkx
accepted answer: http://stackoverflow.com/a/52405145
has title: How to set node names in networkxgraph from 0 to len(G.nodes)
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has body: Hope you can help me with the following, proably very simple but I just can't seem to get it. I want to set nodesnames to my nodes in my graph, so I can use them later for dijkstra's algorithm from the networkx package. The shapefile has nodes based on long lat, as shown below: crossings = list(G.nodes(data = True)) print(crossings) Gives: [((4.8703865, 52.364651), {}), ((4.8719547, 52.3651758), {}), ((4.9264105, 52.3695602), {}), ((4.9289823, 52.3711744), {}), ((4.9259642, 52.3692824), {}), ((4.877608, 52.3752153), {}), ((4.8847629, 52.3765112), {}), ((4.8701251, 52.3757447), {}), ((4.8738594, 52.3804434), {}), ((4.8866343, 52.3574955), {}), ((4.8873865, 52.3602753), {}), ((4.8792688, 52.3649914), {}), ((4.8775365, 52.366768), {}), ((4.879805, 52.3667268), {}), ((4.8824711, 52.3674209), {}), ((4.8790738, 52.3677393), {}), ((4.8771909, 52.3704447), {}) ..... Now I want to set nodenames, as input for the following code: print(nx.dijkstra_path(weighted_G, "1" , "20", weight='cost')) But I can't seem to figure out how to set a name to each node as a number, so node 1 gets name "1", node "2" gets name "2", till node n gets "n". G=nx.read_shp('shapefile.shp', simplify=True) # shapefile from OSM crossings = list(G.nodes(data = True)) weighted_G = nx.Graph() j = 0 for i in crossings: nx.set_node_attributes(weighted_G, values = "none" ,name = j) j = j + 1 print(crossings) But this output gives: [((4.8703865, 52.364651), {}), ((4.8719547, 52.3651758), {}), ((4.9264105, 52.3695602), {}), ((4.9289823, 52.3711744), {}), ((4.9259642, 52.3692824), {}), ((4.877608, 52.3752153),....... As you can see, no number has been added as nodename, does anybody know how to fix this? Thanks in advance EDIT and update-------------------------------------------------------------- So I changed my code last night into: weighted_G=nx.read_shp('shapefile.shp', simplify=True) # shapefile from OSM c = list(weighted_G.nodes(data=True)) j = 0 for i in weighted_G.nodes: weighted_G.node[i]['name']= j j =…
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52405145
upvote count: 1
tagged with: nodes

curl
tags question: http://stackoverflow.com/q/52376998
tags question: http://stackoverflow.com/q/52329613
tags question: http://stackoverflow.com/q/52321323
tags question: http://stackoverflow.com/q/52279054
tag name: curl
tags question: http://stackoverflow.com/q/52406211
type: Tag
tags question: http://stackoverflow.com/q/52329024
tags question: http://stackoverflow.com/q/52299690
tags question: http://stackoverflow.com/q/52341272

http://stackoverflow.com/comment/91735499
has text: Yes, I meant with no changes, but now I know there has been a windows update. It is not in production, it is in development. The command window doesn't close, it remains opened, but ir returns to the command prompt without any message. The runserver just stops and returns to the command prompt. I have found some information in the Windows Event Monitor that says there was an application crash on python.exe. I am sharing it in the body of the question,
comment on: http://stackoverflow.com/q/52390390
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52426851
score: 2
accepted answer of: http://stackoverflow.com/q/52402793
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91796995
has comment: http://stackoverflow.com/comment/91839708
type: Answer
answers question: http://stackoverflow.com/q/52402793
upvote count: 2
has comment: http://stackoverflow.com/comment/91797966
has body: Actually, nothing would prevent you from writting a meta-meta class with the __repr__ for the metaclass itself: In [2]: class MM(type): ...: def __repr__(cls): ...: return f"&lt;metaclass {cls.__name__}" ...: In [3]: class M(type, metaclass=MM): ...: def __repr__(cls): ...: return f"&lt;class {cls.__name__}&gt;" ...: In [4]: class O(metaclass=M): ...: pass ...: In [5]: o = O() In [6]: o Out[6]: &lt;&lt;class O&gt; at 0x7ff7e0089128&gt; In [7]: O Out[7]: &lt;class O&gt; The output of repr(M): In [8]: repr(M) Out[8]: '&lt;metaclass M' (The confusing thing here is that type is also the metaclass for type itself - that is reflected here in that M does not inherit from MM, but rather, have it as its metaclass).

http://stackoverflow.com/a/52426118
type: Answer
has body: Your code is very readable, I would not change it. With a list comprehension you could write something like: for index, row in enumerate([row for row in listSchedule if row[0] == 'Download']): row[3] = myOtherList[index]
upvote count: 4
has comment: http://stackoverflow.com/comment/91795363
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/52425984

http://stackoverflow.com/a/52420204
has body: This will help import fileinput with fileinput.FileInput(filename, inplace=True, backup='.bak') as file: for line in file: print(line.replace(text_to_search, replacement_text), end='')
score: 2
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52420064
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52420064
type: Answer

http://stackoverflow.com/comment/91788383
type: QuestionComment
score: 0
has text: This seems more a problem with your file... if somebody sent you a file that was created in a weird way you'll obtain a weird result. Can you change how the file is created? Maybe it's there that you have to fix something.
comment on: http://stackoverflow.com/q/52421405
type: Comment

http://stackoverflow.com/comment/91714571
has text: After looking [here](https://www.statsmodels.org/dev/gee.html) I can supposed you to specify parameters `cow_struct` and `family`. Some [examples](https://www.statsmodels.org/dev/generated/statsmodels.genmod.generalized_estimating_equations.GEE.html#statsmodels.genmod.generalized_estimating_equations.GEE) from docs here maybe can help you
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52379908

http://stackoverflow.com/q/52361449
duplicate of: http://stackoverflow.com/q/42102674
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91695500
has comment: http://stackoverflow.com/comment/91695505
tagged with: excel
linked to: http://stackoverflow.com/q/42102674
has title: Pandas does NOT read values from Excel cells with such simple formula as =10+10
type: Question
has body: I've got a few Excel sheets with columns with different data types. Some of them consist of formulas as well. Pandas does NOT read values from Excel cells with such simple formula as =10+10 or =250+30+40 Code like this truck_work = pd.read_excel(hauls_monthly_data, sheetname=truck) returns dataframe where column filled from those Excel cells consists data, which type is float and value is nan. But I'm waiting for float with value 10 and 320 The only way I've worked out yet to solve this issue is by manually saving each time an Excel-file before processing data from it. Which is not much Pythonic way of dealing with problems. If I'm using such code as wb = load_workbook(filename = hauls_monthly_data) sheet_names = wb.get_sheet_names() name = sheet_names[1] sheet_ranges = wb[name] truck_work = pd.DataFrame(sheet_ranges.values) then it returns 8 =16+109+108 =6+40+29 None Any help be very appreciated.
has comment: http://stackoverflow.com/comment/91703291
has comment: http://stackoverflow.com/comment/91723880
score: 0
linked to: http://stackoverflow.com/q/22613272
tagged with: pandas
has comment: http://stackoverflow.com/comment/91669870

http://stackoverflow.com/q/52374287
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/52387459
downvote count: 1
has body: I'm running a NN training on my GPU with pytorch. But the GPU usage is strangely "limited" at about 50-60%. That's a waste of computing resources but I can't make it a bit higher. I'm sure that the hardware is fine because running 2 of my process at the same time,or training a simple NN (DCGAN,for instance) can both occupy 95% or more GPU.(which is how it supposed to be) My NN contains several convolution layers and it should use more GPU resources. Besides, I guess that the data from dataset has been feeding fast enough,because I used workers=64 in my dataloader instance and my disk works just fine. I just confused about what is happening. Dev details: GPU : Nvidia GTX 1080 Ti os:Ubuntu 64-bit
tagged with: pytorch
upvote count: 1
has comment: http://stackoverflow.com/comment/91831690
type: Question
has title: Why will GPU usage run low in NN training?
score: 0
has comment: http://stackoverflow.com/comment/91702539
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91697845

http://stackoverflow.com/a/52395312
upvote count: 2
answers question: http://stackoverflow.com/q/52395270
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
has body: Hard to say without seeing how you got your original data, but you can get the result you want by replacing your last line: surveys['%'] = surveys['id'] / surveys.id.sum() With: surveys['%'] = surveys.groupby('cohort')['count'].transform(lambda x: x/sum(x)) For example, starting with your dataframe like: &gt;&gt;&gt; surveys cohort status count 0 2017-01 sad 188 1 2017-01 ok 53 2 2017-01 happy 253 3 2017-02 sad 174 4 2017-02 ok 113 5 2017-02 happy 247 6 2017-03 sad 221 7 2017-03 ok 60 8 2017-03 happy 299 Then: &gt;&gt;&gt; surveys['%'] = surveys.groupby('cohort')['count'].transform(lambda x: x/sum(x)) &gt;&gt;&gt; surveys cohort status count % 0 2017-01 sad 188 0.380567 1 2017-01 ok 53 0.107287 2 2017-01 happy 253 0.512146 3 2017-02 sad 174 0.325843 4 2017-02 ok 113 0.211610 5 2017-02 happy 247 0.462547 6 2017-03 sad 221 0.381034 7 2017-03 ok 60 0.103448 8 2017-03 happy 299 0.515517
accepted answer of: http://stackoverflow.com/q/52395270

http://stackoverflow.com/comment/91749441
has text: Thanks! I'll give it a go.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52389138
type: Comment

http://stackoverflow.com/comment/91792057
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/10792970/python-star-unpacking-for-version-2-7
score: 0
comment on: http://stackoverflow.com/q/52424647

http://stackoverflow.com/comment/91604024
type: QuestionComment
has text: grib2json --names --data --output output.json mygrib.grib
comment on: http://stackoverflow.com/q/52308987
score: 0
type: Comment

http://stackoverflow.com/a/52314215
accepted answer of: http://stackoverflow.com/q/52313601
answers question: http://stackoverflow.com/q/52313601
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/91576789
has comment: http://stackoverflow.com/comment/91576004
has body: What you need to do is setting a proper python environment for development. You can use the virtualenv / pipenv /conda and install the mentioned packages. Please follow the following links. https://www.jetbrains.com/help/pycharm/configuring-python-interpreter.html https://www.jetbrains.com/help/pycharm/creating-virtual-environment.html Then you will be able to install all the packages you want following the instructions in the below link. https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-upgrading-packages.html
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91691737
comment on: http://stackoverflow.com/a/52373383
score: 0
type: AnswerComment
has text: @SuperStew I agree, but I'm not the OP here :) Just providing an answer that works. I'm not in my place to recommend an alternative implementation other than `dicts` without further context from the OP.
type: Comment

http://stackoverflow.com/comment/91657761
has text: What do you mean by index value? The count of values? Or their position in the original text?
comment on: http://stackoverflow.com/q/52356607
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52335184
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52335343
upvote count: 2
possible better answer: http://stackoverflow.com/a/52335232
has answer: http://stackoverflow.com/a/52335232
type: Question
tagged with: dataframe
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/52335343
has title: looking for a more efficient way to create new columns out of a dict in a dataframe column
downvote count: 0
has answer: http://stackoverflow.com/a/52335340
favorite count: 0
has body: I'd like to restructure my data in a dataframe: df = pd.DataFrame({'order_id': ['A', 'B'], 'address': [{'city': "NY", 'latitude': 2.12, 'longitude' : 3.12,'country_code' : "US"}, {'city': "KL", 'latitude': 12.12, 'longitude' : 23.12,'country_code' : "MY"}]}, columns= ['order_id', 'address']) df order_id address 0 A {'city': 'NY', 'latitude': 2.12, 'longitude': 3.12, 'country_code': 'US'} 1 B {'city': 'KL', 'latitude': 12.12, 'longitude': 23.12, 'country_code': 'MY'} What I need is this: order_id address_city address_country_code 0 A NY US 1 B KL MY Here is my working code: new_cols = ['city', 'country_code'] for col in new_cols: df['address_{}'.format(col)] = \ df['address'].map(lambda x: np.nan if pd.isnull(x) else x[col]) df.drop(['address'], axis=1) How can I optimize the code to make it more efficient?
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/comment/91736006
type: QuestionComment
has text: Also note suggested installation is `conda install -c anaconda spyder` ( with channel )
score: 0
comment on: http://stackoverflow.com/q/52394908
type: Comment

http://stackoverflow.com/q/52368201
has comment: http://stackoverflow.com/comment/91681801
accepted answer: http://stackoverflow.com/a/52372468
has comment: http://stackoverflow.com/comment/91680779
has body: I'm trying to extract data from following website :https://www.bigschedules.com/ which works normally when I do it manually. I have developed a script using selenium and Chromedriver in Python, It used to work fine before but now, it shows error "Error during WebSocket handshake: Unexpected response code: 200. The script opens chrome and tries to get data from the website but gets stuck as seen in the picture below: [Click here to see image][1] [1]: https://i.sstatic.net/0JxEi.pngenter code here I'm using chromedriver version 2.42, Selenium version 3.14 def setupChrome(self): # Contains all chrome settings self.logger.info("Setting-up Chrome") self.settings = webdriver.ChromeOptions() #self.settings.add_argument("--incognito") self.settings.add_argument('--ignore-ssl-errors') self.settings.add_argument('--ignore-certificate-errors') self.settings.add_argument('–-disable-web-security') self.settings.add_argument('–-allow-running-insecure-content') def loadBrowser(self): self.setupChrome() try: self.browser = webdriver.Chrome(chrome_options=self.settings, executable_path="D:\\chromedriver.exe") self.browser.maximize_window() &amp; I am getting following errors in console stack: webtrends.js:1 **A parser-blocking**, cross site (i.e. different eTLD+1) script, https://sdc.oocl.com/dcsg6upoljf1zldtivsnov48s_8o7d/wtid.js, is invoked via document.write. The network request for this script MAY be blocked by the browser in this or a future page load due to poor network connectivity. If blocked in this page load, it will be confirmed in a subsequent console message. See https://www.chromestatus.com/feature/5718547946799104 for more details. WebTrends.dcsGetId @ webtrends.js:1 (anonymous) @ VM29:431 6[Intervention] **Slow network is detected**. See &lt;URL&gt; for more details. Fallback font will be used while loading: &lt;URL&gt; application-c962374717.min.js:4 pascalprecht.translate.$translateSanitization: **No sanitization** strategy has been configured. This can have seriou…
has title: Error during WebSocket handshake: Unexpected response code: 200 with ChromeDriver and Selenium
favorite count: 0
has comment: http://stackoverflow.com/comment/91683790
has comment: http://stackoverflow.com/comment/91682446
upvote count: 1
tagged with: python
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52369326
score: 1
has comment: http://stackoverflow.com/comment/91683592
has answer: http://stackoverflow.com/a/52369326
tagged with: selenium
tagged with: webdriver
has answer: http://stackoverflow.com/a/52372468
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91684781
downvote count: 0

http://stackoverflow.com/q/52291756
tagged with: python
tagged with: excel
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91536167
has title: Reverse accumulation to get month by month data in Pandas
has answer: http://stackoverflow.com/a/52293506
tagged with: pandas
downvote count: 0
answer count: 1
has body: I have received data with accumulated numbers. Is there a smart way to reverse the accumulation of the data, so I have it month by month and not stacked on top of each other? Example input: Date SalesRep itemA 01-12-2017 X 1 01-12-2017 Y 0 01-12-2017 Z 0 01-01-2018 X 1 01-01-2018 Y 1 01-01-2018 Z 0 01-02-2018 X 1 01-02-2018 Y 1 01-02-2018 Z 1 Desired output: Date SalesRep itemA 01-12-2017 X 1 01-12-2017 Y 0 01-12-2017 Z 0 01-01-2018 X 0 01-01-2018 Y 1 01-01-2018 Z 0 01-02-2018 X 0 01-02-2018 Y 0 01-02-2018 Z 1 I am using that script which i reused from the forum. import pandas as pd df = pd.read_excel('File.xlsx') df['Date'] = pd.to_datetime(df['Date'], dayfirst=True) df = df.sort_values('Date', ascending=False) # This now sorts in date order cum_columns = ['itemA'] result = df.merge( df.groupby('SalesRep')[cum_columns].diff(), left_index=True, right_index=True, suffixes=['', '_uncum'] ).fillna({'{}_uncum'.format(cum_column): df[cum_column] for cum_column in cum_columns}) print(result) Because for the last month each of the value is 1 then the rest of the months is 0. How can I change the script to work with my case ? EDIT Using JohnE answer i am getting error please take a look: Date SalesRep ItemA itemA_diff 2018-08-01 00:00:00 John 1 1 2018-07-01 00:00:00 John 1 0 2018-06-01 00:00:00 John 0 -1 2018-05-01 00:00:00 John 0 0 2018-04-01 00:00:00 John 0 0 2018-03-01 00:00:00 John 0 0 2018-02-01 00:00:00 John 0 0 2018-01-01 00:00:00 John 0 0 2017-12-01 00:00:00 John 0 0 2017-11-01 00:00:00 John 0 0 2017-10-01 00:00:00 John 0 0 I Should get Date SalesRep ItemA itemA_diff 2018-08-01 00:00:00 John 1 0 2018-07-01 00:00:00 John 1 1 2018-06-01 00:00:00 John 0 0 2018-05-01 00:00:00 John 0 0 2018-04-01 00:00:00 John 0 0 2018-03-01 00:00:00 John 0 0 2018-02-01 00:00:00 John 0 0 2018-01-01 00:00:00 John 0 0 2017-12-01 00:00:00 John 0 0 2017-11-01 00:00:00 John 0 0 2017-10-01 00:00:00 John 0 0 What should be changed?
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91623705
type: QuestionComment
comment on: http://stackoverflow.com/q/52337617
has text: Because now the set contains words only from different files, duplicate words from the same file were removed, the list is still ordered so now I need to make a new list which contains the word only once and also the names of the files that it's been in
score: 0
type: Comment

http://stackoverflow.com/comment/91524514
score: 1
has text: You do not show any results. Just a code dump. How do you know it works? How have you shown to the reader that it works and why it works? Why do you think a *hope* and some code is an answer?
type: AnswerComment
comment on: http://stackoverflow.com/a/52288277
type: Comment

http://stackoverflow.com/comment/91506018
has text: Nope still wrong, it does return something. That something is `None`.
type: Comment
comment on: http://stackoverflow.com/a/52278988
score: 1
type: AnswerComment

http://stackoverflow.com/a/52392808
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52392157
downvote count: 0
has body: You don't need loops for this, just a little bit of algebra. See the comments for details. def change(amount): if not 24 &lt;= amount &lt;= 1000: print("The number is outside the range.") return None # 5*3 - 7*2 = 1, so 5*(3*n) + 7*(-2*n) = n, and therefore # 5*(3*n - 7*k) + 7*(5*k - 2*n) = n for all k # We want to find a small k so that the terms in each bracket are positive k = 3 * amount // 7 x = 3 * amount - 7 * k y = 5 * k - 2 * amount return x, y, [5] * x + [7] * y # Print the sequences for some small amounts for i in range(24, 70): x, y, seq = change(i) print(i, x, y, sum(seq) == i) # Check all values in the range for i in range(24, 1001): x, y, seq = change(i) assert sum(seq) == i print('ok') output 24 2 2 True 25 5 0 True 26 1 3 True 27 4 1 True 28 0 4 True 29 3 2 True 30 6 0 True 31 2 3 True 32 5 1 True 33 1 4 True 34 4 2 True 35 0 5 True 36 3 3 True 37 6 1 True 38 2 4 True 39 5 2 True 40 1 5 True 41 4 3 True 42 0 6 True 43 3 4 True 44 6 2 True 45 2 5 True 46 5 3 True 47 1 6 True 48 4 4 True 49 0 7 True 50 3 5 True 51 6 3 True 52 2 6 True 53 5 4 True 54 1 7 True 55 4 5 True 56 0 8 True 57 3 6 True 58 6 4 True 59 2 7 True 60 5 5 True 61 1 8 True 62 4 6 True 63 0 9 True 64 3 7 True 65 6 5 True 66 2 8 True 67 5 6 True 68 1 9 True 69 4 7 True ok This doesn't necessarily give the shortest sequence for every amount, but it's usually close to the optimum, and it's not too hard to modify this code to get the optimum. But that will be left as an exercise for the reader. ;) To learn more about this technique, please see the Wikipedia article on linear Diophantine equations.

http://stackoverflow.com/comment/91999194
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52425783
type: Comment
has text: Yes. It contains all the text in the pdf document.

http://stackoverflow.com/comment/91564232
comment on: http://stackoverflow.com/q/52308493
type: Comment
type: QuestionComment
has text: I get the numbers in an array list but I am struggling to add 5 to those elements divisible by 5
score: 0

http://stackoverflow.com/comment/91667765
has text: Please edit your answer, as it lacks explanation, and the line `pattern_2(no)` comes out of nowhere. And the final line can't execute properly.
type: Comment
score: 2
comment on: http://stackoverflow.com/a/52361757
type: AnswerComment

http://stackoverflow.com/a/61306747
downvote count: 0
has comment: http://stackoverflow.com/comment/108471033
answers question: http://stackoverflow.com/q/52404483
has body: Here is a shorter Pythonic code, the notebook can be accessed here. Python provides some cleaner way to comprehend our code. In this script, I have used two of such techniques. Technique-1: List comprehension A list comprehension is nothing but looping through an iterable and producing a list as an output. Here we can include computation and conditionals also. The other technique i.e. Technique-2: Dictionary comprehension which is very similar to this, you can read about it here. E.g. Code without list comprehension numbers = [] for i in range(10): numbers.append(i) print(numbers) #Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Code using list comprehension numbers = [i for i in range(10)] print(numbers) #Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Coming to OPs problem, the get_top250_movies() function returns a list of movies with very few details. The exact parameters it returns can be checked like this. As seen in the output the movie details do not contain genres and other details. from imdb import IMDb ia = IMDb() top250Movies = ia.get_top250_movies() top250Movies[0].items() #output: [('rating', 9.2), ('title', 'The Shawshank Redemption'), ('year', 1994), ('votes', 2222548), ('top 250 rank', 1), ('kind', 'movie'), ('canonical title', 'Shawshank Redemption, The'), ('long imdb title', 'The Shawshank Redemption (1994)'), ('long imdb canonical title', 'Shawshank Redemption, The (1994)'), ('smart canonical title', 'Shawshank Redemption, The'), ('smart long imdb canonical title', 'Shawshank Redemption, The (1994)')] However, the get_movie() function returns a lot more information about a movie including the Genres. We combine the two functions to get the genres of the top 20 movies. First we call the get_top250_movies() which returns a list of top 250 movies with fewer details (we are only interested in getting the movieID). Then we call the get_movie() for each movieID from the top movies list and this returns us the Genres. Program: from imdb import IMDb #initialize and get to…
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/108458802

http://stackoverflow.com/q/52297472
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52297594
tagged with: bitwise-and
score: 2
type: AnsweredQuestion
upvote count: 2
possible better answer: http://stackoverflow.com/a/52297594
has body: While working on a matrix equivalency problem, which involves a variety of inverse transformations, I found some unexpected behaviour I wanted to clarify. I've made all the matrices equivalent here, as the actual transformations aren't really relevant to the issue I'm having. a = np.matrix([ 1, 1], [-1, 4]]) x = inv(a) y = inv(a) z = inv(a) (x == y &amp; z).all() Note: x = matrix([ 0.8, -0.2], [ 0.2, 0.2]]) Which returns the following error message: TypeError: ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' Is this error is being raised because &amp; operators can't be used with floating points? The following methods seem to return correct answers, but I would appreciate input on a preferred method for the given problem. (np.equal(x, y) &amp; np.equal(y, z)).all() True np.equal([x,y,z], [y,z,x]).all() True
accepted answer: http://stackoverflow.com/a/52299840
has title: How should I evaluate equivalency of floating point numpy matrices?
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/91544524
tagged with: matrix
downvote count: 0
has answer: http://stackoverflow.com/a/52299840

http://stackoverflow.com/comment/91654332
has text: Yes you're right. I meant punctuation isn't mentioned. Case is definitely present and important
comment on: http://stackoverflow.com/a/52354697
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52359950
downvote count: 1
tagged with: ncurses
type: Question
has answer: http://stackoverflow.com/a/52363234
has body: We've built cli-app with Python. Some part need ncurses, so we use npyscreen. We've successfully tested most part of app using pytest (with the help of mock and other things). But we stuck in 'how to test the part of ncurses code' Take this part of our ncurses code that prompt user to answer: """ Generate text user interface: example : fields = [ {"type": "TitleText", "name": "Name", "key": "name"}, {"type": "TitlePassword", "name": "Password", "key": "password"}, {"type": "TitleSelectOne", "name": "Role", "key": "role", "values": ["admin", "user"]}, ] form = form_generator("Form Foo", fields) print(form["role"].value[0]) print(form["name"].value) """ def form_generator(form_title, fields): def myFunction(*args): form = npyscreen.Form(name=form_title) result = {} for field in fields: t = field["type"] k = field["key"] del field["type"] del field["key"] result[k] = form.add(getattr(npyscreen, t), **field) form.edit() return result return npyscreen.wrapper_basic(myFunction) We have tried many ways, but failed: stringIO to capture the output: failed redirect the output to file: failed hecate: failed I think it's only work if we run whole program pyautogui I think it's only work if we run whole program This is the complete steps of what I have tried So the last thing I use is to use patch. I patch those functions. But the cons is the statements inside those functions are remain untested. Cause it just assert the hard-coded return value. I find npyscreen docs for writing test. But I don't completely understand. There is just one example. Thank you in advance.
answer count: 1
has title: How do you test your ncurses app in Python?
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
upvote count: 3
tagged with: npyscreen
linked to: http://stackoverflow.com/q/90002

http://stackoverflow.com/a/52361076
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91666707
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52361048
has comment: http://stackoverflow.com/comment/91666630
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52361048
has body: Use add of shifted DataFrame with no first column selected by iloc or removed by drop, last filter by list of columns names: cols = ['a','b','d','f','h'] df = df.add(df.iloc[:, 1:].shift(-1,axis=1), fill_value=0)[cols] Alternative: df = df.add(df.drop('a', axis=1).shift(-1,axis=1), fill_value=0)[cols] print (df) a b d f h group A 0.15 0.2 0.3 0.2 0.15 B 0.13 NaN 0.4 0.2 0.19
upvote count: 2

http://stackoverflow.com/comment/91515993
type: Comment
comment on: http://stackoverflow.com/a/52281584
has text: In my CloudTrail, I chose the `Select all S3 buckets in your account ` option. Do I still need to go physically edit the properties section of every bucket to enable logging?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91601357
score: 3
type: QuestionComment
type: Comment
has text: AFAIR for cPython boils it all down to "reading a variable", where some kind of PyObject keeps track of the current length of the sequence. The closest thing I found was https://docs.python.org/3/c-api/object.html But perhaps others could help, filling the gaps ;)
comment on: http://stackoverflow.com/q/52327134

http://stackoverflow.com/comment/91687722
has text: @CristiFati I have been following the information in your link since the beginning. My question also contains that link. According to the link's instructions, all the work will be done if I simply run ` scripts\build_win.cmd`. I did that and I got errors about python's libraries and numpy.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52358784

http://stackoverflow.com/comment/91744923
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52400534
score: 0
has text: Waht kind of error?

http://stackoverflow.com/q/52302605
favorite count: 0
has comment: http://stackoverflow.com/comment/91553321
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52302774
upvote count: 1
downvote count: 1
type: Question
has body: I have a dataframe df like the following: df ID date values 0 0 2017-01-05 55 1 0 2017-01-08 55 2 0 2017-01-09 33 3 1 2017-01-05 27 4 1 2017-01-08 78 5 1 2017-01-09 78 I would like to get the most frequent value for each month and for each ID, so df1 ID YearMonth value 0 0 2017-01 55 1 1 2017-01 78
tagged with: group-by
has answer: http://stackoverflow.com/a/52302794
score: 0
answer count: 2
tagged with: pandas
has title: Pandas: how to get most frequent value in a month for each ID?
has comment: http://stackoverflow.com/comment/91553143

http://stackoverflow.com/q/52410731
has comment: http://stackoverflow.com/comment/120224032
tagged with: pyqt
favorite count: 0
type: UnansweredQuestion
has body: I'm attempting to display QT's graphics objects over the top of AxisItems in pyqtgraph. It took quite a bit of head bashing to figure out how to do this, and I think that perhaps there is a better way that uses the built in pyqtgraph mapToScene / mapToView funtions more efficently. I thought initially that it would be easy and from the documentation (http://www.pyqtgraph.org/documentation/plotting.html#organization-of-plotting-classes) it would just be a case of drawing an object and referencing the pyqtgraph co-ordinates within PlotItem(GraphicsItem) with a higher Z value should make the objects float on top of the AxisItems. However, they disappear behind the Axis when I try this no matter how high I set the Z value or whatever object(viewbox/plotitem/plotwidget) I select as the parent. As a workaround I reference the QTGraphicsScene instead and it does work but the co-ordinates are slightly off by a couple of pixels as you can see from my demo code whenever the mouse is moved which is to be expected as it's translating between pyqtgraph and Qt co-ordinate systems. Can anyone suggest a better way to do this or how to line up the arrows in the demo with the exact values ? Screenshot and code: from PyQt5.QtWidgets import QWidget, QDesktopWidget, QApplication, QLabel, QMainWindow, QHBoxLayout, QVBoxLayout from PyQt5.QtCore import QThread from PyQt5.QtCore import QObject from PyQt5.QtCore import pyqtSlot, pyqtSignal import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui from mainwindowgraph import Ui_MainWindow as QTestGraphMainWindow import sys class TestGraphWidget(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.ui = QTestGraphMainWindow() self.ui.setupUi(self) self.setWindowTitle('Test Graphwindow') #This line is required to get the corect viewbox self.vb = self.ui.mainplot.plotItem.vb proxy = pg.SignalProxy(self.ui.mainplot.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved) self.ui.mainplot.scene().sigMouseM…
tagged with: python
tagged with: pyqtgraph
score: 2
answer count: 0
downvote count: 0
has title: Drawing and Displaying objects and labels over the Axis in pyqtgraph - How to do it effectively?
tagged with: pyqt5
type: Question
upvote count: 2

http://stackoverflow.com/q/52377710
has comment: http://stackoverflow.com/comment/91700319
has comment: http://stackoverflow.com/comment/91700158
tagged with: postgresql
answer count: 1
favorite count: 0
upvote count: 2
tagged with: django
tagged with: python
tagged with: psycopg2
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91700261
has comment: http://stackoverflow.com/comment/91700255
has comment: http://stackoverflow.com/comment/91700209
tagged with: django-models
has body: I am developing a web application with Django and PostgreSQL support. I am using Psycopg2 to connect with my PostgreSQL database. I am attempting to list all of the tables in my database on my Home.html document. I am having trouble showing this in the Home.html document. Below I have included my code. models.py from django.db import models import psycopg2 # Create your models here.def __init__(self, db='giquery-data'): class Tables(models.Model): conn = psycopg2.connect("dbname='giquery-data' user='postgres' host='localhost' password='admin'") cur = conn.cursor() # """SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA='public'""" cur.execute("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA='public'") rows = cur.fetchall() views.py from django.shortcuts import render from django.http import HttpResponse from .models import Tables from django.template import loader # Create your views here. def index(request): all_tables = Tables.rows template = loader.get_template('tablesearch/home.html') context = { 'all_tables': all_tables } return HttpResponse(template.render(context, request)) Home.html Title {% for rows in all_tables %} {{ rows.table_catalog }} - {{ rows.table_name }} Test {% endfor %} Currently, my results look like: How can I show the names of the database tables on Home.html?
has title: How do I show the results of my [Django] model in [HTML] from a [PostgreSQL] database?
type: Question
has comment: http://stackoverflow.com/comment/91700127
has comment: http://stackoverflow.com/comment/91700091
has answer: http://stackoverflow.com/a/52377833
has comment: http://stackoverflow.com/comment/91700124
downvote count: 0
accepted answer: http://stackoverflow.com/a/52377833

http://stackoverflow.com/comment/91508029
comment on: http://stackoverflow.com/q/52279965
score: 0
type: Comment
type: QuestionComment
has text: @jasonharper, should I add while break then?

http://stackoverflow.com/comment/91721867
has text: Why is `while len(stack)` unacceptable? It seems like an okay workaround for this non-conforming interpreter.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52388374

http://stackoverflow.com/a/52352206
upvote count: 3
has comment: http://stackoverflow.com/comment/91649514
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52351819
answers question: http://stackoverflow.com/q/52351819
has comment: http://stackoverflow.com/comment/91649591
type: Answer
has body: The only problem here is that your URL pattern doesn't accept dots. You could change it to a str, which accepts anything: path('user/&lt;str:slug&gt;/', Or use a regex if you want to be a bit more selective about what you accept: re_path(r'user/(?P&lt;slug&gt;[\w.]+)/$',
score: 3
downvote count: 0

http://stackoverflow.com/q/52407321
has comment: http://stackoverflow.com/comment/91780547
downvote count: 1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91758585
upvote count: 0
has body: I am building a predictive model where I want to know can I predict whether a package will be delivered on time (Binary Yes / No), in the event that the package is not delivered on time, I wish to be able to predict by when it will be delivered in categories of &lt;7days, &lt;14days, &lt;21days >28days after expected date. I have built and tested a model for binary classification and have got an f Score of 0.92, which is satisfactory for my needs. However, when I train my categorical model, I start to see training accuracy and validation accuracy diverge (training accuracy is much better than validation accuracy). This is a sign of overfitting. However, I have tried regularization and different values, plus using dropout and different values, and the validation accuracy never gets above 0.7. My total training set is of ~10k examples, ~3k validation, and whilst the catgorical spread is not equal there are sufficient examples of each category (I think). I am using a NN and have increased / decreased both layers and activations and still no joy Any thoughts on where to go next. Thanks
has answer: http://stackoverflow.com/a/52408502
has title: Strategies for solving overfitting - other options?
has comment: http://stackoverflow.com/comment/91760504
tagged with: categorical-data
has comment: http://stackoverflow.com/comment/91758433
has comment: http://stackoverflow.com/comment/91760417
score: -1
favorite count: 0
has comment: http://stackoverflow.com/comment/91785099
tagged with: classification
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/52437787

http://stackoverflow.com/q/52401976
answer count: 1
tagged with: service
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52402343
tagged with: python
has body: My python script use, for now, the os.environ['SECRET_KET']. The server is launch with a system service : [Unit] Description=Escota Dev Service After=multi-user.target [Service] Type=simple User=vagrant WorkingDirectory=/var/www/myproject ExecStart=/var/www/myproject/env/bin/python web/myproject_project/manage.py runserver 127.0.0.1:8000 Restart=on-abort [Install] WantedBy=multi-user.target The service is running : ● myproject-dev.service - myproject Dev Service Loaded: loaded (/lib/systemd/system/myproject-dev.service; enabled; vendor preset: enabled) Active: active (running) since mer. 2018-09-19 10:18:35 CEST; 179ms ago Main PID: 10081 (python) Tasks: 1 Memory: 1.2M CPU: 58ms CGroup: /system.slice/myproject-dev.service └─10081 /var/www/myproject/env/bin/python web/myproject_project/manage.py runserver 127.0.0.1:8000 sept. 19 10:18:35 vm systemd[1]: Started myproject Dev Service. And finally, the error message : [CRITICAL] -&gt; 19/09/2018 09:10 : ('Environment(Config) Error ! =&gt; ', ConnectionError(MaxRetryError("HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /firerisk/zone/ (Caused by NewConnectionError('&lt;urllib3.connection.HTTPConnection object at 0x7fe9b4d72b38&gt;: Failed to establish a new connection: [Errno 111] Connection refused',))",),), &lt;class 'requests.exceptions.ConnectionError'&gt;) But it's not relevant 'cause the real error is : Sep 19 10:18:39 vm python[10081]: File "/var/www/myproject/web/myproject_project/myproject_project/settings.py", line 30, in &lt;module&gt; Sep 19 10:18:39 vm python[10081]: if os.environ['SECRET_KEY']: Sep 19 10:18:39 vm python[10081]: File "/var/www/escota/env/lib/python3.5/os.py", line 725, in __getitem__ Sep 19 10:18:39 vm python[10081]: raise KeyError(key) from None Sep 19 10:18:39 vm python[10081]: KeyError: 'SECRET_KEY' Can you help me ? Thanks. Fabrice
type: Question
has title: KeyError using environement variable, with a system service
score: 0
tagged with: environment-variables

http://stackoverflow.com/comment/91631765
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52340190
type: Comment
has text: why `-1` ? ? ? ?

http://stackoverflow.com/comment/91926844
type: Comment
comment on: http://stackoverflow.com/q/52420373
has text: Any given REST endpoint should simply accept requests, check the existing data to make sure the originating account/customer/user/whatever has completed any relevant prerequisites, and apply the requested changes or return the requested data if appropriate. If that involves seeing what product the request is associated with, that should either be part of the logic in the impacted endpoints or the separate products should have separate code, depending on how much the differences will turn your code into if/else Swiss cheese. The 'flow' is just a result of how the UI calls the endpoints.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91667334
score: 0
type: Comment
type: QuestionComment
has text: Have you tried substituting the divisor in your `precision` with `(TP+FP)`, and the divisor in `recall` with `(TP+FN)`? Just to make sure your `len()` calls do return something similar.
comment on: http://stackoverflow.com/q/52360978

http://stackoverflow.com/a/57631325
type: Answer
has body: a,b=map(int,input().split()) n=0 for i in range(a): for j in range(b): n=n+1 if(j&lt;(b-1)): print(n,end =' ') elif(n==a*b): print(n,end ='') else: print(n)
answers question: http://stackoverflow.com/q/52391765
score: 0

http://stackoverflow.com/comment/91652841
comment on: http://stackoverflow.com/q/52354081
has text: @Aran-Fey thanks, I can't believe I didn't see that. Thanks it has been solved
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/52288888
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52288635
has comment: http://stackoverflow.com/comment/109164660
has body: Stacking requires same number of dimensions. One way would be to unsqueeze and stack. For example: a.size() # 2, 3, 4 b.size() # 2, 3 b = torch.unsqueeze(b, dim=2) # 2, 3, 1 # torch.unsqueeze(b, dim=-1) does the same thing torch.stack([a, b], dim=2) # 2, 3, 5
type: Answer
downvote count: 6
answers question: http://stackoverflow.com/q/52288635
has comment: http://stackoverflow.com/comment/112604144
score: 37
has comment: http://stackoverflow.com/comment/101819785
upvote count: 43

http://stackoverflow.com/q/52371724
has title: odoo many2one as selection field in combobox
score: -3
tagged with: python
type: UnansweredQuestion
downvote count: 3
has body: I'm creating a module in odoo and I wanna use a many2one as a selection field, the problem is on the name of the city 'ville en francais' the dropdown works and it saves the id of the city(from database) but the name is like obj.ville,1 (it shows the name of the module, id instead of the name of the city in database) enter image description here enter image description here enter image description here
tagged with: odoo
type: Question
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52380149

http://stackoverflow.com/comment/91578814
score: 0
comment on: http://stackoverflow.com/q/52315229
type: Comment
type: QuestionComment
has text: Possible duplicate of [PySpark: inconsistency in converting timestamp to integer in dataframe](https://stackoverflow.com/questions/46122846/pyspark-inconsistency-in-converting-timestamp-to-integer-in-dataframe). tl;dr: you need to convert one of the columns to the other type. There are functions to do this, but it also depends on your spark version. Please update your question to include a [reproducible example](https://stackoverflow.com/questions/48427185/how-to-make-good-reproducible-apache-spark-dataframe-examples) and your spark version.

http://stackoverflow.com/a/52397090
has comment: http://stackoverflow.com/comment/91739296
upvote count: 1
has body: You can use list comprehension: temp_list = ["'{}'".format(x) for x in ticker_symbols] Result in: ['500.SI', '502.SI', '504.SI',...]
has comment: http://stackoverflow.com/comment/91739509
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52396975
has comment: http://stackoverflow.com/comment/91738927
has comment: http://stackoverflow.com/comment/91739256

http://stackoverflow.com/comment/91492125
type: Comment
has text: I've not coded anything yet since I am trying to know if it's doable. The filters are checkboxes and dropdown menus
comment on: http://stackoverflow.com/q/52272406
score: 0
type: QuestionComment

http://stackoverflow.com/a/52369557
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52369454
answers question: http://stackoverflow.com/q/52369454
has comment: http://stackoverflow.com/comment/91684170
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91684125
has body: You can use list comprehension for list of DataFrames and then create list of filenames used for parameter keys in concat: dfs = [pd.read_excel(f, sheet_name="Base data",index_col=None,header=0) for f in allFiles] keys = [os.path.basename(f) for f in allFiles] frame = pd.concat(dfs, keys=keys) #if want remove default index values #frame = pd.concat(dfs, keys=keys).reset_index(level=1, drop=True)

http://stackoverflow.com/comment/91808753
type: Comment
comment on: http://stackoverflow.com/a/52422539
has text: thanks for the reply. I am getting this error on running the code: "AttributeError: module 'seaborn' has no attribute 'catplot' "
score: 0
type: AnswerComment

http://stackoverflow.com/a/52357004
has body: An alternative solution would be to have separate item for "simple" and "subscription" classes: class SimpleTransaction(models.Model): # ... item = models.ForeignKey('SimpleItem') # ... # ... class SubscriptionTransaction(models.Model): # ... item = models.ForeignKey('SubscriptionItem') # ... But this way there would be no direct way (without using a conditional operator or like this) to refer to a related transaction from an item: i.simpletransaction if i.simpletransaction else i.subscriptiontransaction So I rule out this way as non-acceptable. It is possible to add these properties, however: class SimpleTransaction(Transaction): @property def simple_item(self): return self.item.simpleitem class SubscriptionTransaction(Transaction): @property def subscription_item(self): return self.item.subscriptionitem I see no other ways to tackle this problem.
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52356414
answers question: http://stackoverflow.com/q/52356414

http://stackoverflow.com/q/52306666
has comment: http://stackoverflow.com/comment/91560837
type: Question
tagged with: numpy
score: 0
has body: I'm working on a problem to help get better at coding in Python/Pandas and I'm stuck on this scenario. Step 1: Multiply each individual character by a given number. Step 2: Add the results to create a sum. Step 3: Subtract the sum from the nearest equal or higher multiple of ten. I want to do this for numbers in a series. For example: Series=[123456789012],[02345434225],[2349349723]
has title: Multiplying each digit in a number pandas
answer count: 1
favorite count: 0
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/91560588
has answer: http://stackoverflow.com/a/52306925
type: UnansweredQuestion
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/122338642
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/54321350
score: 0
has text: I wrote the [troubleshooting of opencv-dll-load-failed](https://programming-review.com/python/opencv-dll-load-failed) and media features pack was a problem on my end.

http://stackoverflow.com/q/52296019
answer count: 1
linked to: http://stackoverflow.com/q/23154400
has title: python handle wav file with wave and numpy
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 2
score: 1
has answer: http://stackoverflow.com/a/52300862
downvote count: 1
has body: I'm trying to extract frequency from .wav files. So I'm using python wave and numpy, I'm almost done! But I face an error.. I followed this url's answer : Extracting frequencies from a wav file python when I exract frequency from .wav file that created myself by following that answer, it succeed. However, when I exract frequency from .wav file that recorded by mic. it raised an error : struct.error: unpack requires a buffer of 288768 bytes following is my code import wave import struct import numpy as np if __name__ == '__main__': wf = wave.open('test6.wav', 'rb') frame = wf.getnframes() data_size = wf.getnframes() frate = wf.getframerate() data = wf.readframes(data_size) wf.close() duration = frame / float(frate) data = struct.unpack('{n}h'.format(n=data_size), data) data = np.array(data) w = np.fft.fft(data) freqs = np.fft.fftfreq(len(w)) print(freqs.min(), freqs.max()) # (-0.5, 0.499975) # Find the peak in the coefficients idx = np.argmax(np.abs(w)) freq = freqs[idx] freq_in_hertz = abs(freq * frate) print('freqiency: ',freq_in_hertz) print('duration: ',duration) 288768 in error message is exactly double of data_size. So when I use data_size=wf.getnframes()*2, it does not raise error. But, it raise an error with file that created by code. How can I solve this?
type: Question
linked to: http://stackoverflow.com/q/40996620
tagged with: numpy

node.js
tags question: http://stackoverflow.com/q/52327099
tags question: http://stackoverflow.com/q/52317379
tags question: http://stackoverflow.com/q/52351217
tags question: http://stackoverflow.com/q/52363006
tags question: http://stackoverflow.com/q/52384221
tags question: http://stackoverflow.com/q/52412882
tags question: http://stackoverflow.com/q/52388791
tags question: http://stackoverflow.com/q/52317957
tags question: http://stackoverflow.com/q/52419935
tags question: http://stackoverflow.com/q/52342226
type: Tag
tags question: http://stackoverflow.com/q/52429553
tag name: node.js
tags question: http://stackoverflow.com/q/52342412
tags question: http://stackoverflow.com/q/52379556

http://stackoverflow.com/q/52406661
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91757167
tagged with: python
has answer: http://stackoverflow.com/a/52428694
accepted answer: http://stackoverflow.com/a/52428694
type: AnsweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/91757209
tagged with: feature-descriptor
tagged with: convex-hull
has body: How can I calculate the eccentricity of a 2D convex hull in Python? Eccentricity: a parameter of an ellipse (or a closed shape) indicating its deviation from the circularity whose value ranging from 0 (circle) to 1 (line).
upvote count: 1
type: Question
score: -1
has title: Eccentricity of a 2D convex hull in Python

http://stackoverflow.com/comment/91510494
score: 0
has text: Sorry about typos
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52280944

http://stackoverflow.com/comment/91675562
type: QuestionComment
score: 1
has text: Could you also paste some sample data to recreate the error?
comment on: http://stackoverflow.com/q/52365561
type: Comment

http://stackoverflow.com/a/52418130
has body: I believe need set_index with unstack, but then necesary transpose, swaplevel and last sort_index: df = pd.read_csv('active_inactive8.csv', index_col=0) df2 = df.set_index(['STATUS','DISTRICT']).unstack().T.swaplevel(1,0).sort_index() df2 = df.pivot(index='STATUS', columns='DISTRICT').T.swaplevel(1,0).sort_index() print (df2.head(10)) STATUS Active Inactive DISTRICT 1 BLANK 128547.0 8436.0 CON 11778.0 643.0 DEM 144470.0 10086.0 GRE 1108.0 96.0 IND 23245.0 1545.0 OTH 394.0 28.0 REF 41.0 3.0 REP 162308.0 8290.0 WEP 150.0 5.0 WOR 2066.0 130.0
answers question: http://stackoverflow.com/q/52415977
downvote count: 0
type: AcceptedAnswer
score: 1
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/91790319
accepted answer of: http://stackoverflow.com/q/52415977

http://stackoverflow.com/comment/91550836
comment on: http://stackoverflow.com/a/52301438
type: Comment
score: 0
type: AnswerComment
has text: @RushabhMehta Well why shouldn't it? It's just plain old python. Also the meaningless names you chose make hard to explain the code. What's what you don't understand?

http://stackoverflow.com/comment/91572956
comment on: http://stackoverflow.com/q/52311724
score: 0
has text: just commit out this line ```STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ```
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91732475
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52392085
has text: Side-note: `set.intersection` doesn't need the arguments to be sets; any iterable works, so preconverting is pointless. And since you're not using the keys for anything, `set.intersection(*(set(v) for k,v in d.items()))` could simplify to the faster and simpler `set.intersection(*d.values())`.

http://stackoverflow.com/a/52407123
downvote count: 0
type: Answer
score: 4
has body: One can only speculate, of course. sorted used to have a different type of arguments in Python 2.x. So, it is very likely that the Python 3.x version forces you to use keyword arguments for the new arguments to avoid, accidentally, passing Python 2 code that does something entirely different in Python 3, without giving you any warning. On the other hand, this is the exception, not the rule. The enumerate example you give has nothing special, it follows the standard Python rules.
accepted answer of: http://stackoverflow.com/q/52407021
answers question: http://stackoverflow.com/q/52407021
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/a/52283830
type: AcceptedAnswer
score: -2
downvote count: 2
type: Answer
has body: Real quick, what testing have you done? Is this if row == "False": being executed? Have you added a quick print statement to see if conditional is even executing? If you've done the above and the conditional isn't executing, have you looked at the output of what Row in cursor: returns? I can't remember off the top of my head, but I believe cursor is going to return a Tuple for you. You need to unpack the Tuple into actual variables than do the comparison. You are essentially doing ('False',) == "False". You could test that by simply changing your comparison to row == ('False',) and that will probably work, but you should probably unpack the Tuples Try f, _ = row if f == "False":
has comment: http://stackoverflow.com/comment/91516387
upvote count: 0
accepted answer of: http://stackoverflow.com/q/52283721
answers question: http://stackoverflow.com/q/52283721
has comment: http://stackoverflow.com/comment/91516232
has comment: http://stackoverflow.com/comment/91515934

http://stackoverflow.com/comment/91768962
comment on: http://stackoverflow.com/a/52412205
has text: I think that is why its giving me `ValueError: time data 0 does not match format '%H%M%S' (match)`
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52325759
score: 1
has body: Use json.dumps: payloads = {"message": s} r = requests.post(url, data=json.dumps(payloads), headers=headers)
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52325727

http://stackoverflow.com/comment/91534473
score: 0
type: AnswerComment
has text: Exactly what I needed. Thanks!
comment on: http://stackoverflow.com/a/52293255
type: Comment

http://stackoverflow.com/a/52296197
accepted answer of: http://stackoverflow.com/q/52287976
has body: It seems you are trying to display multiple figures. show takes a single object which it should display, the second argument is which browser it is supposed to use for that (e.g. firefox, chrome, IE, vivaldi, ...). While you wrote it worked with scatter I guess that it did not throw an error but did not actually work. Bokeh has some documentation on displaying multiple plots. Short version is you need to tell it in which way it should layout it. A very general function is layout : from bokeh.layouts import layout ... # your code without show(...) show(layout([p,select]))
has comment: http://stackoverflow.com/comment/91546491
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52287976
type: Answer

http://stackoverflow.com/q/52312494
has body: I wondered if there is a way - didn't find in on the internet but I heard it was possible- to get many parameters in a python script as a combination of letters ? I explain myself : if the user wants to send many optional parameters Example : If the options are tiger, frog, cat and dog: instead of writing python ./myScript.py --tiger --frog --cat --dog To write : python ./myScript.py --tfcd Is there a way to do that ? Thanks
has title: Combination of letters as parameters in python
has answer: http://stackoverflow.com/a/52312578
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91571930
type: UnansweredQuestion
score: 6
tagged with: python
upvote count: 7
downvote count: 1
type: Question

http://stackoverflow.com/q/52316343
tagged with: python
has comment: http://stackoverflow.com/comment/91580924
tagged with: amazon-s3
score: 0
has title: Download file from S3 bucket with Flask
linked to: http://stackoverflow.com/q/43215889
has comment: http://stackoverflow.com/comment/91580739
has body: To download files from S3 with Flask, I am using the following code: @app.route('/downloads3', methods=['GET','POST']) def download_s3(): if not google.authorized: return redirect(url_for("google.login")) resp = google.get("/oauth2/v2/userinfo") tekst = resp.text user_data = json.loads(tekst) user_id = user_data['id'] s3 = boto3.resource('s3') fileid = request.form.get('file_id') try: s3.Bucket(user_id).download_file(str(fileid),current_app.root_path(str(fileid))) return 'gedownload' except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == "404": print("The object does not exist.") else: raise return redirect('/s3') The file is downloaded to the server but I want the file to be downloaded to the client instead.
duplicate of: http://stackoverflow.com/q/43215889
answer count: 0
type: UnansweredQuestion
tagged with: boto3
tagged with: flask
type: Question
tagged with: download

http://stackoverflow.com/a/76278606
has comment: http://stackoverflow.com/comment/136375974
answers question: http://stackoverflow.com/q/52298917
score: 0
type: Answer
has body: A feedback to @Jake Morris answer: Yes, openpyxl doesn't have the capability till data to perform a recalculation operation on a excel file. But we can still solved the above problem by opening the excel file through a COM object via win32com(pywin32) library, where we can just do the following: Open the excel file using win32com(pywin32) library. Perform Recalculation operation using win32com(pywin32) recalculate function. Save, Close and Quite the excel file. If automatic recalculation is enabled in your excel file then you may skip step 2 and just perform step 1 and 3. Thank you for your time Velton Angelis D'silva

http://stackoverflow.com/q/52359042
tagged with: model-view-controller
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52360040
possible better answer: http://stackoverflow.com/a/56706642
type: Question
answer count: 2
tagged with: pyqt
has comment: http://stackoverflow.com/comment/91662569
has comment: http://stackoverflow.com/comment/91662756
has comment: http://stackoverflow.com/comment/91662741
has body: I'm creating my first application in Python. Currently I'm implementing the first view with PyQt5 and the MVC pattern. Therefore I created a "main" class that is starting the controller by creating a new controller object (The first programming language I learned was Java, so maybe this is not necassary?). In this controller objects init method I'm creating the first view. The view class itself creates a new QWidget. After the QWidget is created the controller is calling a method of the view (QWidget). This method should show the login screen. To show the login screen a new class (Login) is created. That class is of the type QVBoxLayout and is added to the main view (QWidget). This combination leads to an application that is showing a window with the login. This means main class -> controller -> main window (QWidget) -> login (QVBoxLayout). Here I have the following question: Is it the correct way to create a main window (QWidget) and use methods to add the inner layout to the window (using other files/classes)? Or should everything be written in one class? Now I reached the point that my layout and window are displayed correctly. What is missing is the model and how the model is invoked. I searched how I can check if a button was pressed. I found button.clicked.connect(callfunction). This seems to be the right way but how can I call this function from the controller? So that the controller creates the application window and displays the login inside this window. Then the controller listens and waits until the button is pressed. Then the inputs will be forwarded to the model and in the model the credentials will be checked. Here is my sourcecode for the controller with my try on listening to the button: class Controller(object): def __init__(self): # Applikation starten und Login anzeigen app = QApplication(sys.argv) widget = View() widget.showLogin(0, "") widget.loginButton.clicked.connect(self.loginPressed()) sys.exit(app.exec_()) def loginPressed(self): widget.sh…
downvote count: 0
accepted answer: http://stackoverflow.com/a/52360040
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/91662548
score: 6
tagged with: pyqt5
has answer: http://stackoverflow.com/a/56706642
has comment: http://stackoverflow.com/comment/91662523
upvote count: 6
has title: Python - PyQt5 - MVC

http://stackoverflow.com/q/52283087
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/52414394
has answer: http://stackoverflow.com/a/52283238
answer count: 2
tagged with: python-3.5
possible better answer: http://stackoverflow.com/a/52283238
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/52414394
has body: I am trying to build a simple Radius server with pyrad. It works fine, but to check the user's password to my records I need the plaintext password at first. My code: #!/usr/bin/python from __future__ import print_function from pyrad import dictionary, packet, server import six import logging from pyrad.tools import * from pyrad.packet import AuthPacket try: import hashlib md5_constructor = hashlib.md5 except ImportError: # BBB for python 2.4 import md5 md5_constructor = md5.new logging.basicConfig(filename="pyrad.log", level="DEBUG", format="%(asctime)s [%(levelname)-8s] %(message)s") def dump(obj): for attr in dir(obj): if hasattr( obj, attr ): print( "obj.%s = %s" % (attr, getattr(obj, attr))) class FakeServer(server.Server): def HandleAuthPacket(self, pkt): pwd = pkt.PwDecrypt(pkt['User-Password'][0]) uname = pkt['User-Name'][0] print (uname) print ('Plaintext PW: {}' . format(pwd)) print("Received an authentication request") print("Attributes: ") for attr in pkt.keys(): print("%s: %s" % (attr, pkt[attr])) reply = self.CreateReplyPacket(pkt, **{ "Service-Type": "Framed-User", "Framed-IP-Address": '192.168.0.1', "Framed-IPv6-Prefix": "fc66::1/64" }) reply.code = packet.AccessAccept self.SendReplyPacket(pkt.fd, reply) def HandleAcctPacket(self, pkt): print("Received an accounting request") print("Attributes: ") for attr in pkt.keys(): print("%s: %s" % (attr, pkt[attr])) reply = self.CreateReplyPacket(pkt) self.SendReplyPacket(pkt.fd, reply) def HandleCoaPacket(self, pkt): print("Received an coa request") print("Attributes: ") for attr in pkt.keys(): print("%s: %s" % (attr, pkt[attr])) reply = self.CreateReplyPacket(pkt) self.SendReplyPacket(pkt.fd, reply) def HandleDisconnectPacket(self, pkt): print("Received an disconnect request") print("Attributes: ") for attr in pkt.keys(): print("%s: %s" % (attr, pkt[attr])) reply = self.CreateReplyPacket(pkt) # COA NAK reply.code = 45 self.SendReplyPacket(pkt.fd, reply) if __name__ == '__main__': # create server and read dic…
tagged with: radius
has title: pyrad get plaintext password

http://stackoverflow.com/q/52304663
has answer: http://stackoverflow.com/a/52308026
accepted answer: http://stackoverflow.com/a/52308026
downvote count: 0
has body: I'm currently trying to use re to search this file and delete a zone // // Do any local configuration here // // Consider adding the 1918 zones here, if they are not used in your // organization //include "/etc/bind/zones.rfc1918"; zone "domain.com" { type master; file "/etc/bind/zones/domain.com.signed"; allow-transfer { 1.2.3.4; }; }; zone "4.3.2.in-addr.arpa" { type master; file "/etc/bind/rev.domain.com"; allow-transfer { 1.2.3.4; }; }; zone "example.com" { type master; file "/etc/bind/zones/example.com"; }; Currently I have this import re string = 'zone "example.com" { type master; file "/etc/bind/zones/example.com";};' with open('zone.conf.local') as thing: re.sub(r'^%s$' % string, '', thing) But when I try and run this I get this error Traceback (most recent call last): File "zone.py", line 5, in &lt;module&gt; re.sub(r'^%s$' % string, '', thing) File "/home/john/.virtualenvs/hw/lib/python3.6/re.py", line 191, in sub return _compile(pattern, flags).sub(repl, string, count) TypeError: expected string or bytes-like object I thought that maybe I shouldn't put a string the pattern for re but when I try this import re string = 'zone "example.com" { type master; file "/etc/bind/zones/example.com";};' with open('zone.conf.local') as thing: re.sub('^$', string, '', thing) This still doesn't work and outputs this Traceback (most recent call last): File "zone.py", line 5, in &lt;module&gt; re.sub('^$', string, '', thing) File "/home/john/.virtualenvs/hw/lib/python3.6/re.py", line 191, in sub return _compile(pattern, flags).sub(repl, string, count) TypeError: '_io.TextIOWrapper' object cannot be interpreted as an integer
has comment: http://stackoverflow.com/comment/91556967
type: Question
score: 1
has comment: http://stackoverflow.com/comment/91557168
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91557614
tagged with: python
tagged with: regex
has title: Match and delete a string from a file
type: AnsweredQuestion

http://stackoverflow.com/comment/91772314
type: QuestionComment
has text: To add to the previously mentioned comments (I hope I do not have a typo in there), change `cmd` definition to `cmd = ["rsync", "-e", "ssh -o StrictHostKeyChecking=no", "-auPz", "--exclude", args.exclude, "{}@{}:{}".format(rsync_user, host, args.source), "{}/".format(dest_dir)]` and ditch the `shell=True`.
score: 0
comment on: http://stackoverflow.com/q/52408841
type: Comment

http://stackoverflow.com/comment/91620847
type: AnswerComment
type: Comment
has text: By the looks of your file it is not comma separated, but tab separated. I would suggest trying with K = pd.read_csv("kona_python.csv", sep="\t")
comment on: http://stackoverflow.com/a/52280734
score: 0

http://stackoverflow.com/comment/91698140
type: QuestionComment
has text: Are you installing it via pip? Or are you installing via github and running setup.py?
comment on: http://stackoverflow.com/q/52376405
score: 0
type: Comment

http://stackoverflow.com/q/52374924
has answer: http://stackoverflow.com/a/70785809
tagged with: python
possible better answer: http://stackoverflow.com/a/52386921
has title: Google Cloud Dataflow Python, Retrieving Job ID
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52375670
has body: I am currently working on a Dataflow Template in Python, and I would like to access the Job ID and use it to save to a specific Firestore Document. Is it possible to access the Job ID? I cannot find anything regarding this in the documentation.
upvote count: 3
has answer: http://stackoverflow.com/a/70975479
accepted answer: http://stackoverflow.com/a/52395692
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/52395692
tagged with: google-cloud-dataflow
has answer: http://stackoverflow.com/a/52386921
tagged with: google-cloud-platform
favorite count: 0
answer count: 5

http://stackoverflow.com/a/52350622
answers question: http://stackoverflow.com/q/52350412
type: Answer
upvote count: 1
score: 1
downvote count: 0
has body: Here is one way to do it, by spawning a child python process from within node. test.js: const { spawn } = require('child_process'); const p = spawn('python', ['yourscript.py', '1']); p.stdout.on('data', (data) =&gt; { console.log(`stdout: ${data}`); }); yourscript.py import sys def change_var(x): print('hello from python: {:d}'.format(int(x) + 2)) change_var(sys.argv[1]) output of running node ./test.js: stdout: hello from python: 4 directory layout ➜ test tree . ├── test.js └── yourscript.py 0 directories, 2 files related: https://nodejs.org/docs/latest-v8.x/api/child_process.html https://docs.python.org/2/library/sys.html#sys.argv https://docs.python.org/3/library/subprocess.html Calling an external command in Python
has comment: http://stackoverflow.com/comment/91646868

http://stackoverflow.com/comment/91822012
has text: Thanks! Worked well.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52433281
type: Comment

http://stackoverflow.com/a/52356537
type: Answer
answers question: http://stackoverflow.com/q/52356052
has body: I know the question is about how to obtain a solution in python, still, I will leave this solution using data.table and reshape2. library(data.table) library(reshape2) setDT(df)[,new := (1:.N), by = question] dcast(df, new ~ question, value.var = "answer") new q1 q2 q3 q4 q5 1: 1 a1 a2 a3 a4 a5 2: 2 a1 a2 a3 a4 a5 3: 3 a1 a2 a3 a4 a5
downvote count: 1
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/91657567

http://stackoverflow.com/comment/91751125
type: QuestionComment
has text: Start by understanding how computers store numbers, and especially how this works for *negative* numbers. Once you understand how that works, take both a positive and a negative integer number, and write out their binary representations. Write down all the zeros and ones. Then, write out their inverse, flip the 1s for 0s and the 0s for 1s, and work out the integer value (so go the other direction). See what happened there?
comment on: http://stackoverflow.com/q/52403521
score: 0
type: Comment

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/52340088
tags question: http://stackoverflow.com/q/52372620
tags question: http://stackoverflow.com/q/52394908
tags question: http://stackoverflow.com/q/52386265
tags question: http://stackoverflow.com/q/52425060
tags question: http://stackoverflow.com/q/52380572
tags question: http://stackoverflow.com/q/52409544
tags question: http://stackoverflow.com/q/52302072
type: Tag
tags question: http://stackoverflow.com/q/52283535
tags question: http://stackoverflow.com/q/52298957
tags question: http://stackoverflow.com/q/52423984
tags question: http://stackoverflow.com/q/52334135
tags question: http://stackoverflow.com/q/52410927
tags question: http://stackoverflow.com/q/52319095
tags question: http://stackoverflow.com/q/52297550

http://stackoverflow.com/a/52389343
has comment: http://stackoverflow.com/comment/93996716
has comment: http://stackoverflow.com/comment/133617325
downvote count: 1
has comment: http://stackoverflow.com/comment/93948391
has comment: http://stackoverflow.com/comment/134781482
has body: You can simply write the data in response to a file: with open('myfile.wav', mode='bx') as f: f.write(response) If you want to access the audio data as a NumPy array without writing it to a file first, you can do this with the soundfile module like this: import io import soundfile as sf data, samplerate = sf.read(io.BytesIO(response)) See also this example: https://pysoundfile.readthedocs.io/en/0.9.0/#virtual-io
score: 12
has comment: http://stackoverflow.com/comment/133643262
type: Answer
upvote count: 13
has comment: http://stackoverflow.com/comment/93980687
has comment: http://stackoverflow.com/comment/93958342
answers question: http://stackoverflow.com/q/52369925

http://stackoverflow.com/comment/91535791
score: 0
type: Comment
has text: Is it fixed for all the computers?
type: AnswerComment
comment on: http://stackoverflow.com/a/52282660

http://stackoverflow.com/q/52346241
tagged with: arrays
downvote count: 0
score: 4
favorite count: 0
tagged with: python-2.7
has body: I have a numpy array and I have a list of elements I want to insert at specific locations (not contiguous) into that array. The indices are in another numpy array. target answer: [1,2,3,4,5] original array: [1,3,5] elements to insert: [2,4] indices: [1,3] numpy.insert(arr,[1,3],[2,4]) dosen't give the desired result. It gives [1,2,3,5,4]. Any pointers?
has title: Better way to insert elements into numpy array
has answer: http://stackoverflow.com/a/52346287
accepted answer: http://stackoverflow.com/a/52346287
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91638123
possible better answer: http://stackoverflow.com/a/52347749
has comment: http://stackoverflow.com/comment/91638297
tagged with: scipy
has answer: http://stackoverflow.com/a/52347749
type: Question
upvote count: 4
tagged with: numpy
has comment: http://stackoverflow.com/comment/91638447
answer count: 2
has comment: http://stackoverflow.com/comment/91639046

http://stackoverflow.com/a/52284448
has comment: http://stackoverflow.com/comment/91517326
has comment: http://stackoverflow.com/comment/91517845
downvote count: 0
has comment: http://stackoverflow.com/comment/91517437
has comment: http://stackoverflow.com/comment/91517810
answers question: http://stackoverflow.com/q/52284418
has comment: http://stackoverflow.com/comment/91517196
has comment: http://stackoverflow.com/comment/91517198
has comment: http://stackoverflow.com/comment/91517217
has comment: http://stackoverflow.com/comment/91517260
has comment: http://stackoverflow.com/comment/91517332
score: 5
has comment: http://stackoverflow.com/comment/91517234
has comment: http://stackoverflow.com/comment/91517165
upvote count: 5
has body: Your function doesn't have a return statement anywhere. If a function doesn't return anything explicitly, it always returns None. And it's almost certainly intentional that this function doesn't return anything. Notice that the function mutates its argument in-place: &gt;&gt;&gt; a = [7,1,3,5,9,2,3] &gt;&gt;&gt; insertion_sort(a) &gt;&gt;&gt; a [1, 2, 3, 3, 5, 7, 9] In Python, it's idiomatic for functions that do this to not return anything. See, for example, builtin methods like list.sort and list.append. And notice that in the cited video, this is exactly what the instructor does—they don't print the result of insertion_sort, they just call it, and then look at the value of the variable. Also, in general, functions that mutate a value in-place, like this one, take an imperative verb, like the list method sort, while functions that leave the argument unchanged but return a transformed value, take a past participle, like the built-in function sorted. So, if this function were named insertion_sorted, Python programmers would expect it to leave its argument alone and return a new, sorted list; since it's named insertion_sort, they'll expect it to sort its argument in-place and return nothing.
type: Answer
has comment: http://stackoverflow.com/comment/91517209
has comment: http://stackoverflow.com/comment/91517393

http://stackoverflow.com/comment/91789006
comment on: http://stackoverflow.com/q/52422610
score: 0
has text: What if you use `header=False` rather than `header=None`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52284556
answer count: 2
possible better answer: http://stackoverflow.com/a/52284571
has comment: http://stackoverflow.com/comment/91518249
score: 0
has answer: http://stackoverflow.com/a/52284589
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91518169
accepted answer: http://stackoverflow.com/a/52284589
tagged with: python
has comment: http://stackoverflow.com/comment/91517440
has comment: http://stackoverflow.com/comment/91517503
has body: I would like to check if 'n' number of variables is True. The code I am using to get certain variables a true or false value is this: for row in range(mw): for col in range(mh): if matrix[row-1][col] == 0: left = False else: left = True if matrix[row-1][col-1] == 0: botleft = False else: botleft = True if matrix[row][col-1] == 0: bot = False else: bot = True Now if I want to check if from these variables: left, botleft, bot if 2 of them are True how would I do that? If I had a larger list of variables, like 8 variables how would I check if 5 of those are True? ("matrix" is a 2d array)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91519677
has answer: http://stackoverflow.com/a/52284571
has title: Check whether 'n' number of variables match a condition in Python
type: Question

http://stackoverflow.com/q/52372430
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52372724
type: UnansweredQuestion
has body: I have a dataframe with 2 columns, one of which is a comma separated list of values: A 1,2,3,4,6 B 1,5,6,7 C 1,3,2,8,9,7 D 1,3,6,8 I also have an array: [2,3,9] And I'd like to end up with the same dataframe, transformed in such a way that values not in the array are filtered out. Eg: A 2,3 B C 3,2,9 D 3 Could anyone point me in the right direction? I've had a look around but have hit a bit of a wall.
tagged with: python
score: 2
has title: Remove specific values in a dataframe based on whether or not they're in an array
downvote count: 0
has answer: http://stackoverflow.com/a/52373016
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/52373221
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/91689476
favorite count: 0

http://stackoverflow.com/a/52319535
has body: Using input example from @Veera df=pd.DataFrame({"string1":['CA','MI','AZ','NY'],"string2":['CA','MA','FL','NY']}) df[df.string1==df.string2] string1 string2 0 CA CA 3 NY NY
type: Answer
answers question: http://stackoverflow.com/q/52319375
score: 0

http://stackoverflow.com/comment/91622729
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52337621
has text: Thank you very much. This explanation helped alot!
type: AnswerComment

http://stackoverflow.com/comment/91533817
type: Comment
type: QuestionComment
has text: The challenge I set myself was to capture a part of the URL using regex, AFTER having proven to myself that I could do it using the accepted method for the class. I should have been satisfied with just proving that I could write a regex to extract what I wanted. But having made it that far, I wanted to see if I could use it as an alternative way of achieving the same results. I can see in retrospect that one method or the other one, but not combining both, was probably the way to go. I learned a lot in the effort, and am still learning things from the comments and answers here.
comment on: http://stackoverflow.com/q/52283259
score: 0

http://stackoverflow.com/q/52418546
favorite count: 0
has answer: http://stackoverflow.com/a/52418577
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/54079259
has body: I could import excel data into python 3.6 using pandas. Code I used for this purpose is as follows: import pandas as pd import numpy as np df=pd.read_excel("I:/Python/Excel.xlsx") df.head() This above code shows me the Table1 on Jupyter notebook. I am not getting how to convert two columns from the Table1 (obtained from above code) which I can see in Jupyter notebook to numpy arrays inorder to carry out further analysis on them. There are in all 17 columns in this table. I need 'Column 15' and 'Column 16' from pandas frame work into numpy array so that final structure is as follows: data_set=[[x1,y1],[x2,y2],...[x1000,y1000]] # x1 = row1 from Column 15 # y1 = row1 from Column 16 I will be finally using this data to plot 'xy scatter plot' into matplotlib. This part I know how to do. Learned a lot from this forum. Thanks to all! I looked online for this solution, but unable to find a solution for it. Thanks for reading.
possible better answer: http://stackoverflow.com/a/54079259
upvote count: 3
answer count: 2
tagged with: pandas
has title: Excel to pandas to numpy array conversion
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/52418577
type: AnsweredQuestion
score: 3
downvote count: 0

http://stackoverflow.com/a/52350100
has body: Quick update: I think I've managed to debug my code my using a numpy array for C instead of a list. Here is the updated version: import numpy as np def poly_mult_dc_naive(A, B, n: int, a: int, b: int): C = np.zeros(2*n - 1, dtype=int) # here I changed it from list to np array if n == 1: C[0] = A[a] * B[b] return C[0] C[0:n-1] = poly_mult_dc_naive(A, B, n//2, a, b) C[n:2*n-1] = poly_mult_dc_naive(A, B, n//2, a + (n // 2), b + (n // 2)) W = poly_mult_dc_naive(A, B, n//2, a, b + (n // 2)) V = poly_mult_dc_naive(A, B, n/2, a + (n//2), b) C[(n // 2) : (3*n // 2) - 1] += W + V return C BONUS QUESTION: Does anyone know of a better way I could keep the arguments n, a, and b as int types? I just feel like having to write: n = int(n) a = int(a) b = int(b) might not be the most elegant way.
has comment: http://stackoverflow.com/comment/91645666
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91645678
has comment: http://stackoverflow.com/comment/91645864
has comment: http://stackoverflow.com/comment/91650875
score: 1
answers question: http://stackoverflow.com/q/52350000
has comment: http://stackoverflow.com/comment/91645849
upvote count: 2
has comment: http://stackoverflow.com/comment/91645711

http://stackoverflow.com/q/52393855
tagged with: python-3.x
answer count: 0
has comment: http://stackoverflow.com/comment/91752722
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91750007
tagged with: pytest
has title: pytest: how to use a fixture to parametrize
has body: in conftest.py there is a fixture defined that returns a list: @pytest.fixture(scope="session") def targets_to_try(): with open( "{}/xxx/cicd/xxx/manifest.yaml".format(os.environ["APPFOLDER"]), "rt" ) as f: manifest = yaml.safe_load(f.read()) schema = Manifest.ManifestSchema() appobj = schema.load(manifest) return appobj.data["targets_to_try"] In test file test_interfaces_cfg.py I would like to use the above fixture in order to parametrize the test function import pytest @pytest.mark.parametrize("target", targets_to_try) def test_interfaces_cfg(manifest, target): pass This causes the following error: E NameError: name 'targets_to_try' is not defined Could you please advise how to achieve the desired behaviour ? EDIT: if targets_to_try() is not a fixture in conftest.py then I get the following error: @pytest.mark.parametrize("target", targets_to_try()) E NameError: name 'targets_to_try' is not defined EDIT: directory layout is as follows: $ tree . |-- attributes | `-- __init__.py |-- bgp | `-- __init__.py |-- Blueprint.py |-- communities | `-- __init__.py |-- conftest.py |-- customize | `-- __init__.py |-- Head.py |-- interfaces | |-- __init__.py | `-- test_interfaces_configlet.py |-- InterfacesIx.py |-- InterfacesLacp.py |-- manifest | |-- __init__.py | `-- test_schema.py |-- Manifest.py |-- NeighborIx.py |-- policies | `-- __init__.py |-- prefixes | `-- __init__.py |-- pytest.ini |-- Stack.py `-- Tail.py
type: Question
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/105884424
score: 4
has comment: http://stackoverflow.com/comment/91734274
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/91748935

http://stackoverflow.com/q/52302060
has answer: http://stackoverflow.com/a/52302241
has title: how to use this working regular expression (re) on a pandas df to remove redundant non-numeric character , asterisk (*)?
possible better answer: http://stackoverflow.com/a/52302241
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52302095
type: Question
tagged with: pandas
tagged with: regex
answer count: 2
has body: By using the code below, I am able to use re to change a string like this: *12.2 to a float number like this: 12.2: import re numeric_const_pattern = '[-+]? (?: (?: \d* \. \d+ ) | (?: \d+ \.? ) )(?: [Ee] [+-]? \d+ ) ?' rx = re.compile(numeric_const_pattern, re.VERBOSE) print('converted string to float number is', float(rx.findall("*12.2")[0])) converted string to float number is 12.2 But I have a pandas df, which is: df = pd.DataFrame([[10, '*41', '-0.01', '2'],['*10.5', 54, 34.2, '*-0.076'], [65, -32.01, '*344.32', 0.01], ['*32', '*0', 5, 43]]) 0 1 2 3 0 10 *41 -0.01 2 1 *10.5 54 34.2 *-0.076 2 65 -32.01 *344.32 0.01 3 *32 *0 5 43 How can I apply the function above to this df in order to remove all of asterisk characters and also make a complete float dtype pandas df like below? 0 1 2 3 0 10 41 -0.01 2 1 10.5 54 34.2 -0.076 2 65 -32.01 344.32 0.01 3 32 0 5 43
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52302095

http://stackoverflow.com/comment/91571943
comment on: http://stackoverflow.com/a/52311527
score: 0
type: AnswerComment
type: Comment
has text: Fancy indexing, which is what the OP is doing, does not return a view, so he will not be holding a reference to the big array.

http://stackoverflow.com/q/52424088
type: AnsweredQuestion
upvote count: 0
has title: Variable name from a string
has answer: http://stackoverflow.com/a/52424225
has comment: http://stackoverflow.com/comment/91790942
downvote count: 1
has comment: http://stackoverflow.com/comment/91790991
type: Question
has body: Is this possible? i = 1 for var in ['var1', 'var2', 'var3', 'var4']: eval(var) = i i + 1 Somehow I want to create a new variable (with new name) with each loop. [EDIT:] A lot of people said, it's not useful so below is my actual code I wanted to use it for: import pandas as pd # Convert categorical variables to dummies PPE_WAW_DISTRICT = pd.get_dummies(X['PPE_WAW_DISTRICT'], prefix='PPE_WAW_DISTRICT') PPE_TARIFF_TYPE = pd.get_dummies(X['PPE_TARIFF_TYPE'], prefix='PPE_TARIFF_TYPE') PPE_OSD = pd.get_dummies(X['PPE_OSD'], prefix='PPE_OSD') VariantProdEE = pd.get_dummies(X['VariantProdEE'], prefix='VariantProdEE') CUS_OWNER = pd.get_dummies(X['CUS_OWNER'], prefix='CUS_OWNER') CUS_LEGAL_FORM = pd.get_dummies(X['CUS_LEGAL_FORM'], prefix='CUS_LEGAL_FORM') CUS_CITY = pd.get_dummies(X['CUS_CITY'], prefix='CUS_CITY') CUS_DISTRICT = pd.get_dummies(X['CUS_DISTRICT'], prefix='CUS_DISTRICT') X.drop(['PPE_WAW_DISTRICT', 'PPE_TARIFF_TYPE', 'PPE_OSD', 'CUS_OWNER', 'CUS_LEGAL_FORM', 'CUS_CITY', 'CUS_DISTRICT'], axis=1, inplace=True) X = pd.concat([PPE_WAW_DISTRICT, PPE_TARIFF_TYPE, PPE_OSD, VariantProdEE, CUS_OWNER, CUS_LEGAL_FORM, CUS_CITY, CUS_DISTRICT], axis=1) Basically I want to create dummy columns from each of the selected oclumns and then with prefix add it to main dataframe (X) Thanks, Matt
score: -1
has comment: http://stackoverflow.com/comment/91791298
answer count: 1
has comment: http://stackoverflow.com/comment/91791229
duplicate of: http://stackoverflow.com/q/1373164
favorite count: 0
has comment: http://stackoverflow.com/comment/91791414
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91791393
linked to: http://stackoverflow.com/q/1373164
accepted answer: http://stackoverflow.com/a/52424225
tagged with: python
has comment: http://stackoverflow.com/comment/91791015

http://stackoverflow.com/q/52401629
has comment: http://stackoverflow.com/comment/91747076
type: AnsweredQuestion
type: Question
tagged with: charts
accepted answer: http://stackoverflow.com/a/52402772
has comment: http://stackoverflow.com/comment/91747046
score: 0
has comment: http://stackoverflow.com/comment/91747106
tagged with: pandas
answer count: 1
tagged with: web
has title: Creating chart with filled gap between lines
tagged with: python
has body: I'm trying to create a chart like shown in the image. I've created this in excel, but I'd like to include it in a real-time web dashboard. The chart contains two separate data streams (stream1 and stream2). I need to create a chart which will paint in green all areas were stream1 has value greater than stream 2, and red when it's lower. I have the timseries as dataframes in pandas, python. Could anyone suggest the best/easiest way I could create such a chart? Thank you.
has answer: http://stackoverflow.com/a/52402772

http://stackoverflow.com/q/52278119
tagged with: pandas
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/91505325
type: UnansweredQuestion
has title: Building a function that can iterate through rows and pull from different columns
has answer: http://stackoverflow.com/a/52279011
has body: The dataframe is a little simpler than what I'm working with, but I'm trying to write a function that will look at three different budgets in which we have funds. We have a daily spend rate that is consistent, regardless of budget, but look to pull from the first budget first, the second second, etc. I've started writing the function, but have already run into issues without getting into the larger complexities. The function that I'm trying to create will decrement the respective budget by whatever is spent and return that corresponding value in the "spent" column. If the amount to be spent exceeds the budget, it will pull from the second budget (and then the third), decrementing each respectively. import pandas as pd import matplotlib.pyplot as plt ID = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Budget_1 = [1000, 1200, 1300, 100 ,500, 0, 800, 950, 4321, 800, 1000, 1200, 1300, 100 ,500, 0, 800, 950, 4321, 800] Budget_2 = [1000, 1200, 1300, 100 ,500, 0, 800, 950, 4321, 800, 1000, 1200, 1300, 100 ,500, 0, 800, 950, 4321, 800] Budget_3 = [1000, 1200, 1300, 100 ,500, 0, 800, 950, 4321, 800, 1000, 1200, 1300, 100 ,500, 0, 800, 950, 4321, 800] FY = [2018, 2018, 2018, 2018, 2018, 2018, 2018, 2018, 2018, 2018, 2019, 2019, 2019, 2019, 2019, 2019, 2019, 2019, 2019, 2019] Days = [250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250] spend = [2.5, 3.0, 4.0, 5.0, 4.0, 10.0, 2.5, 2.0, 4.0, 2.5, 2.5, 3.0, 4.0, 5.0, 4.0, 10.0, 2.5, 2.0, 4.0, 2.5] Spent_1 = '' Spent_2 = '' Spent_3 = '' Total_Spent = '' d = {'ID': ID, 'Budget 1': Budget_1, 'Budget 2': Budget_2, 'Budget 3': Budget_3, 'Fiscal Year': FY, 'Days': Days, 'Spent 1': Spent_1, 'Spent 2': Spent_2, 'Spent 3': Spent_3, 'Total Spent': Total_Spent, 'Spend Rate': spend} df = pd.DataFrame(d) print(df) df = df.sort_values(['Fiscal Year', 'ID'], ascending = True) def funded_calc(spendrate): spent1 = spendrate*df['Days'] df['Spent 1'] = df['Spent 1'] - spent1 return spen…
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91504951

http://stackoverflow.com/a/52277628
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91503232
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52277564
has comment: http://stackoverflow.com/comment/91503376
has body: You don't initialize the value of total between the sequences so it keeps on counting. def count_squences(string): i= 0 total = 0 total_char_list = [] while i &lt; len(string): if string[i] == "x": total += 1 if string[i] == "y": if total != 0: total_char_list.append(total) total = 0 i = i + 1 if total != 0: total_char_list.append(total) return total_char_list Update (17:00) - fixed the original procedure and I thought of a better solution - my_str = "xxxxyyxyxx" [len(z) for z in re.split("y+", my_str)]

http://stackoverflow.com/comment/91738814
comment on: http://stackoverflow.com/a/52287288
type: Comment
score: 0
type: AnswerComment
has text: if it's the first element of classes and x, what would be the shape of y_pred[0] ? bit confused here

http://stackoverflow.com/a/52321210
answers question: http://stackoverflow.com/q/52321021
accepted answer of: http://stackoverflow.com/q/52321021
type: Answer
has body: It would probably be better if self.ext were a dictionary with keys out, sol, etc, instead of separate attributes for each. As is, you can use setattr with an appropriate dict. d = {x: x for x in ['out', 'mid', 'sol', 'text']} d['in'] = 'out' x = 'ext_' + d.get(self.newdataframe.iloc[i]['FT'], 'other') setattr(self, x, getattr(self, x) + edis) The better approach: self.ext[d.get(self.newdataframe.iloc[i]['FT'], 'other')] += edis
score: 2
has comment: http://stackoverflow.com/comment/91613934
downvote count: 0
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/91618650
type: QuestionComment
type: Comment
has text: @I'-'I Apologies, you're on the right trail. It would be -40 the spoilage counted on 9/1. (not 8/31) I edited the original post. Thank you!
score: 0
comment on: http://stackoverflow.com/q/52335386

http://stackoverflow.com/a/52375011
score: 5
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You should be clear about exactly which word-vector set you're using: different sets will have a different ability to perform well on analogy tasks. (Those trained on the tiny text8 dataset might be pretty weak; the big GoogleNews set Google released would probably do well, at least under certain conditions like discarding low-frequnecy words.) You're doing the wrong arithmetic for the analogy you're trying to solve. For an analogy "A is to B as C is to ?" often written as: A : B :: C : _?_ You begin with 'B', subtract 'A', then add 'C'. So the example: France : Paris :: Italy : _?_ ...gives the formula in your excerpted text: wv('Paris') - wv('France') + wv('Italy`) = target_coordinates # close-to wv('Rome') And to solve instead: Paris : France :: Berlin : _?_ You would try: wv('France') - wv('Paris') + wv('Berlin') = target_coordinates ...then see what's closest to target_coordinates. (Note the difference in operation-ordering to your attempt.) You can think of it as: start at a country-vector ('France') subtract the (country&amp;capital)-vector ('Paris'). This leaves you with an interim vector that's, sort-of, "zero" country-ness, and "negative" capital-ness. add another (country&amp;capital)-vector ('Berlin'). This leaves you with a result vector that's, again sort-of, "one" country-ness, and "zero" capital-ness. Note also that gensim's most_similar() takes multiple positive and negative word-examples, to do the arithmetic for you. So you can just do: sims = word_vectors.most_similar(positive=['France', 'Berlin'], negative=['Paris'])
answers question: http://stackoverflow.com/q/52364632
upvote count: 5
accepted answer of: http://stackoverflow.com/q/52364632

http://stackoverflow.com/comment/91622827
score: 1
has text: yes it is important
comment on: http://stackoverflow.com/q/52337617
type: Comment
type: QuestionComment

http://stackoverflow.com/a/70639439
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52404529
has comment: http://stackoverflow.com/comment/127953369
downvote count: 0
has body: In my case the problem was because I was using WSL to host my project so the project address used by PyCharm to create and select the venv was wrong. Instead of using the option Virtualenv Environment to create the environment: You need to select the WSL option from the side bar and then enter the path to your new or existing venv.
upvote count: 2

http://stackoverflow.com/comment/91778190
comment on: http://stackoverflow.com/q/52417494
has text: Your SQL qurey says, `select .... FROM product_management_product`, which is the second relation, right?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52319924
score: 0
has body: It looks like this vim plugin will do what you want: https://github.com/requalix/detect-indentation.
type: Answer
answers question: http://stackoverflow.com/q/52319776

http://stackoverflow.com/q/52414766
tagged with: python
has answer: http://stackoverflow.com/a/52414944
has comment: http://stackoverflow.com/comment/91773263
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/91773352
possible better answer: http://stackoverflow.com/a/52415536
has answer: http://stackoverflow.com/a/52415536
type: Question
accepted answer: http://stackoverflow.com/a/52414944
has comment: http://stackoverflow.com/comment/91773463
has title: Python parsing *unknown format string to json or dict
has comment: http://stackoverflow.com/comment/91773442
answer count: 2
downvote count: 0
favorite count: 0
has body: The reason I say unknown is because it is being sent from an IOS 12 extension, I have no-hand in creating this format but lets just suppose there is no way I can do any formatting over there. In Python what I receive is a string in the following format: { "body": '{\n carrierName = "AT&amp;T";\n dateRecieved = "2018-08-07 20:29:56 +0000";\n \n}' } I want to know what this format {foo="bar"; top="long";} is called? It is what gets returned from iOS native Libraries so it has to be something; And is there any built-in way to parse it as a json or a dict. I can write my own parser for sure, but im looking for something built-in or something that exist in some generic library.
tagged with: python-3.x

http://stackoverflow.com/q/52274139
has answer: http://stackoverflow.com/a/52274262
favorite count: 0
has comment: http://stackoverflow.com/comment/91495635
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91495542
has comment: http://stackoverflow.com/comment/91495691
tagged with: django-views
score: 1
accepted answer: http://stackoverflow.com/a/52274262
upvote count: 1
type: Question
has title: Optimalizing Django's QuerySetSequences
has body: In one of my views I have problem, that going into this url makes CPU usage 100% for like 5-10 mins. It means that for the next 5-10 mins my webpage is useless. My bet is that's because of how many database queries I am trying to send. Views.py that gives me trouble: def guild_details(request, guild_name): fixed_guild_name = urllib.parse.unquote(guild_name) players = Player.objects.filter(guild=fixed_guild_name) last_month = datetime.today() - timedelta(days=30) deaths = reduce(QuerySetSequence, [Deaths.objects.filter(killed=player, date__gte=last_month) for player in players]) kills = reduce(QuerySetSequence, [Deaths.objects.filter(killer=player, date__gte=last_month) for player in players]) return render(request, 'guild.html', {'players': players, 'deaths': deaths.order_by('-date'), 'kills': kills.order_by('-date'), 'guild_name': guild_name}) It seems not that bad, but consider that: Database includes over 6000+ "Players". (and rising) Database includes over 26000+ "Deaths". (and rising) At first, I was thinking about doing cache for this webpage, but it's deaths / kills might change every 30 mins or so, so I don't think that will help much - considering that I have trouble accessing this page for the first time if players count is high (10+). If player count is small, I have no trouble accessing this page. Also, I'm running redis / celery with scrapping on same server. Is there something I could optimalize to make it work? Or should I just simply put more CPU into this? My "top" command: last pid: 69974; load averages: 4.28, 4.78, 5.49 up 2+11:16:22 12:40:46 14 processes: 5 running, 9 sleeping CPU: 33.1% user, 1.4% nice, 6.0% system, 0.0% interrupt, 59.4% idle Mem: 8965M Active, 30G Inact, 112K Laundry, 82G Wired, 3594M Free ARC: 64G Total, 41G MFU, 19G MRU, 17M Anon, 857M Header, 2934M Other 55G Compressed, 97G Uncompressed, 1.76:1 Ratio Swap: PID USERNAME THR PRI NICE SIZE RES STATE C TIME WCPU COMMAND 41281 xxxx 1 103 0 65500K 61516K CPU0 0 15:27 100.34% pytho…
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/91799582
comment on: http://stackoverflow.com/a/52426861
type: AnswerComment
has text: @J.walker it DOES return the new total. But you don't seem to understand what "returning" mean.
score: 0
type: Comment

http://stackoverflow.com/a/52373238
answers question: http://stackoverflow.com/q/52373014
has body: Without using numpy: import random as rd arr = [[rd.uniform(0.0001,1) for _ in range(8)] for _ in range(arrlen)]
has comment: http://stackoverflow.com/comment/91693966
downvote count: 0
has comment: http://stackoverflow.com/comment/91691778
has comment: http://stackoverflow.com/comment/91692645
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/91691143
score: 1

http://stackoverflow.com/q/52394435
has title: python selenium scrape multi page table
tagged with: selenium
type: Question
has body: The purpose of this code is to scrape a multipage table of data from a certain URL. And it worked fine just for the first row no more. Here is the code: from selenium import webdriver class DataEngine: def __init__(self): self.url = 'https://www.investing.com/economic-calendar/house-price-index-147' self.driver = webdriver.PhantomJS(r"D:\Projects\Tutorial\Driver\phantomjs-2.1.1-windows\bin\phantomjs.exe") def title(self): self.driver.get(self.url) title = self.driver.find_elements_by_xpath('//*[@id="leftColumn"]/h1') for title in title: print(title.text) def table(self): self.driver.get(self.url) while True: table = self.driver.find_elements_by_xpath('//*[@id="historicEvent_372690"]') for table in table: print(table.text)
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52398859
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91741149
tagged with: selenium-webdriver

http://stackoverflow.com/a/52366824
has body: considering s to be a sequence, assuming is to be a sequence with numbers and considering the first Java-style code in the first part s = [0,1,2,3,4,5,..] x = 5 for i in range(1, len(s)): if s[i] +s[i-1] == x: print("Success")
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52366574
answers question: http://stackoverflow.com/q/52366574
score: 2
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/91708777

http://stackoverflow.com/q/52342780
has answer: http://stackoverflow.com/a/52342812
has body: I have this simple SQLite code in python. box = 'XDS.SI' sqlite_cur.execute(''' SELECT id from box_infos WHERE box = ?; ''', box ) I get the following error; sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied. When I run the simple select statement in another way, sqlite_cur.execute(''' SELECT id from box_infos WHERE box = 'XDS.SI'; ''' ) I received no error. What is wrong with the first code segment? Both looks similar. I am using sqlite3 and python v3.6
has comment: http://stackoverflow.com/comment/91631799
tagged with: sql
tagged with: sqlite
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52342812
has title: What is wrong with this simple sqlite select statement code in python to produce this binding error?
has comment: http://stackoverflow.com/comment/91631875
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/91631843
downvote count: 1
type: Question

http://stackoverflow.com/q/52356171
upvote count: 1
has comment: http://stackoverflow.com/comment/91657915
favorite count: 0
score: 0
has answer: http://stackoverflow.com/a/52356497
accepted answer: http://stackoverflow.com/a/52356497
downvote count: 1
has answer: http://stackoverflow.com/a/61700878
tagged with: python
tagged with: tkinter
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/61700878
has body: I wrote a python GUI which should create and update a .csv file by clicking a button called "Start" and should stop the while loop which updates .csv by clicking another button called "Stop". But whenever I run the GUI and click on start it freezes. Although, I see that the .csv file is continuously updating but I can't stop the .csv from updating new rows. I am just simply running the code using python 2.7 &amp; ubuntu terminal writing python filename.py. Can anyone please check what's wrong in my code? from Tkinter import * import datetime import sys import time import csv import math A1 = 0 def csv_write(label): global A1 A1 = 0 A = str(datetime.datetime.now()) + ".csv" start = time.time() elapsed = 0 with open(A, 'wt') as filename: csv_writer = csv.writer(filename, delimiter=',') csv_writer.writerow(('IMU', 'Time', 'A.Sensor.X', 'A.Sensor.Y', 'A.Sensor.Z', 'G.Sensor.X', 'G.Sensor.Y', 'G.Sensor.Z', 'M.Sensor.X', 'M.Sensor.Y', 'M.Sensor.Z', 'IMU', 'Time', 'A.Sensor.X', 'A.Sensor.Y', 'A.Sensor.Z', 'G.Sensor.X', 'G.Sensor.Y', 'G.Sensor.Z', 'M.Sensor.X', 'M.Sensor.Y', 'M.Sensor.Z', 'IMU', 'Time', 'A.Sensor.X', 'A.Sensor.Y', 'A.Sensor.Z', 'G.Sensor.X', 'G.Sensor.Y', 'G.Sensor.Z', 'M.Sensor.X', 'M.Sensor.Y', 'M.Sensor.Z', 'IMU', 'Time', 'A.Sensor.X', 'A.Sensor.Y', 'A.Sensor.Z', 'G.Sensor.X', 'G.Sensor.Y', 'G.Sensor.Z', 'M.Sensor.X', 'M.Sensor.Y', 'M.Sensor.Z', 'IMU', 'Time', 'A.Sensor.X', 'A.Sensor.Y', 'A.Sensor.Z', 'G.Sensor.X', 'G.Sensor.Y', 'G.Sensor.Z', 'M.Sensor.X', 'M.Sensor.Y', 'M.Sensor.Z', 'IMU', 'Time', 'A.Sensor.X', 'A.Sensor.Y', 'A.Sensor.Z', 'G.Sensor.X', 'G.Sensor.Y', 'G.Sensor.Z', 'M.Sensor.X', 'M.Sensor.Y', 'M.Sensor.Z')) while (A1==0): elapsed = str(time.time() - start) label['text']=elapsed csv_writer.writerow((1, 1, 2, 3, 4, 5, 6, 7,8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7)) def stop(): global A1 A1 = 1 root = Tk() frame…
type: Question
has title: Break a while loop with a stop button in tkinter
answer count: 2

http://stackoverflow.com/comment/91655494
comment on: http://stackoverflow.com/a/52354573
has text: No, rows 5 isn't the same in both cases, there's another row on that index in df2.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91735827
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/52395388
type: Comment
has text: `A[0][0]` though this is prob a duplicate

http://stackoverflow.com/comment/91660680
comment on: http://stackoverflow.com/q/52357964
score: 0
type: Comment
type: QuestionComment
has text: Edited original.

http://stackoverflow.com/q/52396257
tagged with: reinforcement-learning
tagged with: deep-learning
has answer: http://stackoverflow.com/a/52396304
tagged with: python
possible better answer: http://stackoverflow.com/a/78572150
score: 1
favorite count: 0
has body: I was following How to build your own AlphaZero AI using Python and Keras The git is here In run.ipynb, this part of the code: memory.clear_stmemory() if len(memory.ltmemory) &gt;= config.MEMORY_SIZE: The post didn't explain much on it. What are memory.ltmemory and memory.stmemory used for?
upvote count: 2
tagged with: machine-learning
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52396304
type: Question
answer count: 2
tagged with: keras
has answer: http://stackoverflow.com/a/78572150
has title: stmemory and ltmemory in "How to build your own AlphaZero AI using Python and Keras"

html-entities
tags question: http://stackoverflow.com/q/52414568
type: Tag
tag name: html-entities

http://stackoverflow.com/a/52357022
answers question: http://stackoverflow.com/q/52356890
downvote count: 0
has body: You can use re.split and filter: filter(None, re.split("[, \-!?:]+", a]) Where I have put the string "[, \-!?:]+", you should put whatever characters it is that are your delimiters. filter will just remove any empty strings because of leading/trailing separators.
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/q/52305866
tagged with: matrix
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52309241
tagged with: python
tagged with: pygame
type: Question
has title: When checking the cells around a single cell in a 2d array, code always returns either 1 or 0 for all cells
has body: Using the following code: import random import pygame mw = 165 # Matrix width mh = 165 # Matrix height margin = 0 newmatrix = [] finished = False pygame.init() matrix = [] for i in range(mw): # This block of code just creates a new 2d array and fill it with either a 1 or a 0 in each cell matrix.append([]) for j in range(mh): matrix[i].append(random.randint(0, 1)) def neighborchecker(): """This long block of code checks the 8 cells around matrix[r][c] and checks if it is a 0 or 1, and based on that assigns that cell true or false, adding each cell up to see how many cells are 1s or 0s and then assigning matrix[r][c] based on its neighbors""" for r in range(mw): for c in range(mh): try: if matrix[r - 1][c] == 0: left = False else: left = True if matrix[r - 1][c - 1] == 0: botleft = False else: botleft = True if matrix[r][c - 1] == 0: bot = False else: bot = True if matrix[r + 1][c + 1] == 0: botright = False else: botright = True if matrix[r + 1][c] == 0: right = False else: right = True if matrix[r + 1][c + 1] == 0: topright = False else: topright = True if matrix[r][c - 1] == 0: top = False else: top = True if matrix[r - 1][c + 1] == 0: topleft = False else: topleft = True except IndexError: pass allneighbor = sum([left, botleft, bot, botright, right, topright, top, topleft]) if allneighbor &lt; 2 or allneighbor &gt; 3: return 0 if allneighbor == 3: return 1 def createnewmatrix(): # This block creates a new matrix with new values based on what neighborchecker() returns for x in range(mw): newmatrix.append([]) for y in range(mh): newmatrix[x].append(neighborchecker()) print(newmatrix) while not finished: createnewmatrix() Each block of code has a comment saying what each of it does/ at least should do What I'm expecting to get is I run this, get a matrix full of 1s and 0s, then throwing that in a loop to check each cell's neighbors and changing the corresponding cell on 'newmatrix' based on that. Then that also goes into a loop to keep updating newmatrix. If you are …
score: 0

http://stackoverflow.com/comment/108429442
has text: sorry ,not clean but autoclean will clean unwanted packages and other stuffs basically some respositorys may be outdated or unavailable for downloading using main server respository of ubuntu it will increase your speed check if python2 interpreter is updated.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/60694330

http://stackoverflow.com/comment/91539265
comment on: http://stackoverflow.com/a/52295009
score: 0
type: AnswerComment
has text: Hey Akshay, no need to create ajax/foo.html my exemple reload element `$("#idImg").html(data);` after modification with `SomeFunction(request)`. If you don't need reload element `#idImg` you can finish with this : `success: function (data) { }` . `/ajax/foo` is symbolic link with your view just for run a `SomeFunction(request)` in same page on image and send element with JS.
type: Comment

http://stackoverflow.com/a/52307538
downvote count: 0
type: Answer
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/52307503
has body: You can do this with list comprehension, In [18]: [i+j for i,j in zip(list1,list2)] Out[18]: [[4, 'a'], [5, 'b'], [6, 'c'], [7, 'd']]

http://stackoverflow.com/q/52311755
has comment: http://stackoverflow.com/comment/91574692
downvote count: 0
has comment: http://stackoverflow.com/comment/91571640
has comment: http://stackoverflow.com/comment/91570906
has comment: http://stackoverflow.com/comment/91571040
favorite count: 0
has comment: http://stackoverflow.com/comment/91573042
has comment: http://stackoverflow.com/comment/91571427
has answer: http://stackoverflow.com/a/52314863
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/52311975
type: AnsweredQuestion
tagged with: python-3.x
score: 2
has title: Avoid nested for loops using List Comprehension and/or map
tagged with: list
has comment: http://stackoverflow.com/comment/91570618
upvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/91571096
has answer: http://stackoverflow.com/a/52312431
has comment: http://stackoverflow.com/comment/91571574
has answer: http://stackoverflow.com/a/52313468
accepted answer: http://stackoverflow.com/a/52313468
has body: For a couple of days I've been struggling with how to optimize (not only make it look nicer) the 3 nested loops containing a conditional and a function call inside. What I have right now is the following: def build_prolongation_operator(p,qs): ''' p: dimension of the coarse basis q: dimension of the fine basis The prolongation operator describes the relationship between the coarse and fine bases: V_coarse = np.dot(V_fine, I) ''' q = sum(qs) I = np.zeros([q, p]) for i in range(0, q): for j in range(0, p): for k in range(0, qs[j]): # if BV i is a child of j, we set I[i, j] = 1 if i == f_map(j, k, qs): I[i, j] = 1 break return I where f_map is: def f_map(i, j, q): ''' Mapping which returns the index k of the fine basis vector which corresponds to the jth child of the ith coarse basis vector. ''' if j &lt; 0 or j &gt; q[i]: print('ERROR in f_map') return None result = j for k in range(0, i): result += q[k] return result When profiling my whole code I get that build_prolongation_operator is called 45 times and f_map approximately 8.5 million times!! Here is the picture: I have tried to do the same with list comprehension and a map, but without any luck. Here is a sample of the inputs that build_prolongation_operator expects: p = 10 qs = randint(3, size=p)
tagged with: optimization
tagged with: numpy
possible better answer: http://stackoverflow.com/a/52311975
has comment: http://stackoverflow.com/comment/91577018

http://stackoverflow.com/a/52314764
upvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52314186
has comment: http://stackoverflow.com/comment/91581470
has comment: http://stackoverflow.com/comment/91583448
has comment: http://stackoverflow.com/comment/91580147
downvote count: 1
has body: You can approach the problem in a completely different way. Instead of trying to produce a value when the key 'default' is requested on the fly, you can initialize the dict with the key 'default' set to your desired value, and then protect the value of the 'default' key by overriding all the methods that can potentially alter the content of the dict so that the value of the key 'default' is never altered: class T(dict): def __init__(self, **kwargs): kwargs['default'] = 'DEFAULT' super(T, self).__init__(**kwargs) def __setitem__(self, key, value): if key != 'default': super(T, self).__setitem__(key, value) def __delitem__(self, key): if key != 'default': super(T, self).__delitem__(key) def clear(self): super(T, self).clear() self.__init__() def pop(self, key, **kwargs): if key == 'default': return self[key] return super(T, self).pop(key, **kwargs) def popitem(self): key, value = super(T, self).popitem() if key == 'default': key2, value2 = super(T, self).popitem() super(T, self).__setitem__(key, value) return key2, value2 return key, value def update(self, other, **kwargs): if kwargs: if 'default' in kwargs: del kwargs['default'] elif 'default' in other: del other['default'] super(T, self).update(other, **kwargs)
has comment: http://stackoverflow.com/comment/91585250
has comment: http://stackoverflow.com/comment/91580320
has comment: http://stackoverflow.com/comment/91579825
score: -1
has comment: http://stackoverflow.com/comment/91579941

http://stackoverflow.com/comment/91517497
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52284529
has text: I posted an answer as you're a new user so many find some existing solutions confusing. Hopefully you can see how this question is very similar to the following https://stackoverflow.com/a/24918803/4013571 I would recommend seeing if you can follow that answer as well

http://stackoverflow.com/comment/91760476
score: 2
has text: @martineau I found the problem, it needed a restart, but thanks for the useful information
comment on: http://stackoverflow.com/q/52332554
type: Comment
type: QuestionComment

encoding
tags question: http://stackoverflow.com/q/52332988
type: Tag
tags question: http://stackoverflow.com/q/52351619
tags question: http://stackoverflow.com/q/52301077
tag name: encoding
tags question: http://stackoverflow.com/q/52337401
tags question: http://stackoverflow.com/q/52296980
tags question: http://stackoverflow.com/q/52381020
tags question: http://stackoverflow.com/q/52333043
tags question: http://stackoverflow.com/q/52309407
tags question: http://stackoverflow.com/q/52387450
tags question: http://stackoverflow.com/q/52409827
tags question: http://stackoverflow.com/q/52292669

http://stackoverflow.com/comment/91527918
score: 0
type: Comment
has text: Thank you, I added the rest. The mask works for an individual file, but when I apply the function to `C:/Users/me/Desktop/myfolder/data/*.csv` an error appears.
comment on: http://stackoverflow.com/a/52289265
type: AnswerComment

http://stackoverflow.com/q/52385580
favorite count: 0
has title: Pandas | Save Index Value of last row
has body: Trying to find the last index value and save to variable but I cant seem to pull only the index column alone. I want to be able to use the date to determine if new values have been generated. Process is as follows: Parse excel for latest (last) date Save latest (last) date to variable Continue to monitor for new entries and save latest (last) to that variable again. df = pd.read_csv('USDT_XRP_4HOUR_JAN_2017.csv', index_col='date',delimiter=',') print('INDEX - LAST 1 LINES') print(df.iloc[-1:,-1]) print('END OF INDEX - LAST 1 LINES') OUTPUT END OF INDEX - LAST 1 LINES date 2018-09-18 10:55:00 0.274509 Name: high, dtype: float64 END OF INDEX - LAST 1 LINES
has answer: http://stackoverflow.com/a/52385720
upvote count: 1
tagged with: python
tagged with: indexing
type: AnsweredQuestion
score: 1
tagged with: col
type: Question
tagged with: pandas
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/52385720

http://stackoverflow.com/q/52302352
tagged with: python
accepted answer: http://stackoverflow.com/a/52302923
score: 2
upvote count: 2
has title: TensorFlow estimators vs manual/session approach
tagged with: tensorflow
type: AnsweredQuestion
has body: I am fairly new to deep learning and TensorFlow, and in the set of lectures from the course I am taking they go over two methods of employing TensorFlow: using estimators and using sessions. It seems like the estimators method is much easier to understand and simpler as it is similar to what I have done using the sklearn classifier packages. Is there any particular reason why one would use sessions instead of estimators? Or will it depend on the type of dataset I am dealing with?
type: Question
tagged with: tensorflow-estimator
tagged with: deep-learning
has answer: http://stackoverflow.com/a/52302923
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/110420377
type: Comment
comment on: http://stackoverflow.com/a/52434908
score: 0
type: AnswerComment
has text: is there a paper regarding the permutation test you used above?

http://stackoverflow.com/comment/91797214
has text: self.resp_df.loc[self.resp_df['id'].isin(post_req['id']), 'returnType'] = 'CTR'
comment on: http://stackoverflow.com/a/52426496
score: 0
type: AnswerComment
type: Comment

keras
tags question: http://stackoverflow.com/q/52380387
tags question: http://stackoverflow.com/q/52307460
tags question: http://stackoverflow.com/q/52395506
tags question: http://stackoverflow.com/q/52413371
tags question: http://stackoverflow.com/q/52372118
tags question: http://stackoverflow.com/q/52311754
tags question: http://stackoverflow.com/q/52395135
tags question: http://stackoverflow.com/q/52369544
tags question: http://stackoverflow.com/q/52353540
tags question: http://stackoverflow.com/q/52356068
tags question: http://stackoverflow.com/q/52320059
tags question: http://stackoverflow.com/q/52415751
tags question: http://stackoverflow.com/q/52418248
tags question: http://stackoverflow.com/q/52330726
tags question: http://stackoverflow.com/q/52282108
tags question: http://stackoverflow.com/q/52317007
tags question: http://stackoverflow.com/q/52272780
tags question: http://stackoverflow.com/q/52290839
tags question: http://stackoverflow.com/q/52347906
tags question: http://stackoverflow.com/q/52396257
tags question: http://stackoverflow.com/q/52378942
tags question: http://stackoverflow.com/q/52390397
tags question: http://stackoverflow.com/q/52328433
tags question: http://stackoverflow.com/q/52362534
tags question: http://stackoverflow.com/q/52363416
tags question: http://stackoverflow.com/q/52362368
tags question: http://stackoverflow.com/q/52360546
tags question: http://stackoverflow.com/q/52317804
tags question: http://stackoverflow.com/q/52317262
tags question: http://stackoverflow.com/q/52289594
tags question: http://stackoverflow.com/q/52322794
tags question: http://stackoverflow.com/q/52303130
tags question: http://stackoverflow.com/q/52286247
tags question: http://stackoverflow.com/q/52317452
tags question: http://stackoverflow.com/q/52417056
tags question: http://stackoverflow.com/q/52389205
tags question: http://stackoverflow.com/q/52398936
tags question: http://stackoverflow.com/q/52374493
tags question: http://stackoverflow.com/q/52361110
tags question: http://stackoverflow.com/q/52378761
tags question: http://stackoverflow.com/q/52352678
tags question: http://stackoverflow.com/q/52359905
tags question: http://stackoverflow.com/q/52402822
tags question: http://stackoverflow.com/q/52408404
tags question: http://stackoverflow.com/q/52299913
tags question: http://stackoverflow.com/q/52422327
tags question: http://stackoverflow.com/q/52390449
tags question: http://stackoverflow.com/q/52306842
tags question: http://stackoverflow.com/q/52411530
tags question: http://stackoverflow.com/q/52313836
tags question: http://stackoverflow.com/q/52271644
tags question: http://stackoverflow.com/q/52351038
tags question: http://stackoverflow.com/q/52284154
tags question: http://stackoverflow.com/q/52355321
tags question: http://stackoverflow.com/q/52387192
tags question: http://stackoverflow.com/q/52424172
tags question: http://stackoverflow.com/q/52299108
tags question: http://stackoverflow.com/q/52394840
tags question: http://stackoverflow.com/q/52399923
tags question: http://stackoverflow.com/q/52381912
tags question: http://stackoverflow.com/q/52329721
tags question: http://stackoverflow.com/q/52384386
tags question: http://stackoverflow.com/q/52419866
tags question: http://stackoverflow.com/q/52286374
tags question: http://stackoverflow.com/q/52365491
tags question: http://stackoverflow.com/q/52332042
tags question: http://stackoverflow.com/q/52426885
tags question: http://stackoverflow.com/q/52291187
tags question: http://stackoverflow.com/q/52429551
tags question: http://stackoverflow.com/q/52299946
tags question: http://stackoverflow.com/q/52358241
tags question: http://stackoverflow.com/q/52388233
tags question: http://stackoverflow.com/q/52340372
tags question: http://stackoverflow.com/q/52326106
tags question: http://stackoverflow.com/q/52281037
tags question: http://stackoverflow.com/q/52279355
tags question: http://stackoverflow.com/q/52287080
tags question: http://stackoverflow.com/q/52355409
tags question: http://stackoverflow.com/q/52357812
tags question: http://stackoverflow.com/q/52298987

http://stackoverflow.com/a/52396263
has comment: http://stackoverflow.com/comment/91739696
has comment: http://stackoverflow.com/comment/91739060
has comment: http://stackoverflow.com/comment/91742650
has comment: http://stackoverflow.com/comment/91772146
has comment: http://stackoverflow.com/comment/91774030
has comment: http://stackoverflow.com/comment/91739623
has comment: http://stackoverflow.com/comment/91742660
has body: (1) Did you specify --runtime-version when you deployed the model? By default, it is 1.0, but presumably you need TensorFlow version 1.8 or something like that. If your model uses ops that were added after 1.0, you might get this message. (2) You can use gcloud ml-engine local predict even with TF Records. Presumably the model that is exported has a single string tensor input with dimension [None] that feeds directly into a ParseExample operation. You just follow the standard JSON API syntax in that case by sending a batch of strings containing serialize tf.Example records (base64 encoding them and using the syntax to indicate such): {"instances": [{"b64": base64.b64encode(example1), {"b64": base64.b64encode(example2}}, ...]} Another (better) option re-export it (doesn't have to be retrained, you can always export from checkpoints or SavedModel by writing a script with a few lines to load the model and export the new one) and instead of using build_parsing_transforming_serving_input_receiver_fn use build_default_transforming_serving_input_receiver_fn. Then your JSON is simple: {"instances": [{"input_name": [10,3,5,6]}]} If you just have the one input, you can simplify further to: {"instances": [[10,3,5,6]]}
has comment: http://stackoverflow.com/comment/91813291
score: 0
answers question: http://stackoverflow.com/q/52395021
type: Answer
has comment: http://stackoverflow.com/comment/91774842
has comment: http://stackoverflow.com/comment/91835754

http://stackoverflow.com/q/52420704
answer count: 1
tagged with: nested
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91784534
tagged with: python
tagged with: dictionary
type: UnansweredQuestion
has title: Looping thru a text file and trying to create a nested dictionary but the dictionary only prints last loop iteration not full loop nested together
upvote count: 1
type: Question
score: 1
tagged with: for-loop
has body: I am trying to create a nested dictionary from some for loops. If my code is positioned like this: for figure in problem.figures: for object in problem.figures[figure].objects: attribute_dict_A = {} nested_dict = {} for k, v in problem.figures[figure].objects[object].attributes.items(): attribute_dict_A[k] = v attribute_dict_A.update({'object': object}) nested_dict[figure] = attribute_dict_A print(nested_dict) Then the output shows the entire loop iterated through as below: {'A': {'shape': 'square', 'object': 'a', 'fill': 'yes', 'size': 'very large'}} {'B': {'shape': 'square', 'object': 'b', 'fill': 'yes', 'size': 'very large'}} {'C': {'shape': 'square', 'object': 'c', 'fill': 'yes', 'size': 'very large'}} {'1': {'shape': 'pentagon', 'object': 'd', 'fill': 'yes', 'size': 'very large'}} {'2': {'shape': 'square', 'object': 'e', 'fill': 'yes', 'size': 'very large'}} {'3': {'shape': 'triangle', 'object': 'f', 'fill': 'yes', 'size': 'very large'}} {'4': {'shape': 'pac-man', 'object': 'g', 'fill': 'yes', 'size': 'very large'}} {'5': {'shape': 'star', 'object': 'h', 'fill': 'yes', 'size': 'very large'}} {'6': {'shape': 'heart', 'object': 'i', 'fill': 'yes', 'size': 'very large'}} But if my code is properly indented (see the 'print(nested_dict)') indentation then it only prints the last iteration of the loop. How can I the loop to iterate and also store everything I need? for figure in problem.figures: for object in problem.figures[figure].objects: attribute_dict_A = {} nested_dict = {} for k, v in problem.figures[figure].objects[object].attributes.items(): attribute_dict_A[k] = v attribute_dict_A.update({'object': object}) nested_dict[figure] = attribute_dict_A print(nested_dict) My final output is coming like this: {'6': {'shape': 'heart', 'object': 'i', 'fill': 'yes', 'size': 'very large'}} EDIT---- I updated my code to this but I am still not getting the result I need. It seems to be overriding my dictionary each time it iterates through the loop. nested_dict = {} attri…
has answer: http://stackoverflow.com/a/52420785

http://stackoverflow.com/comment/91575839
comment on: http://stackoverflow.com/q/52314094
score: 0
has text: Is there any particular reason why you want to use seaborn for this? This would be perfectly doable using just matplotlib and numpy.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52342029
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52346597
score: -1
type: Question
has title: extract key-value pairs from a python dictionary, according to the value of a specific key
possible better answer: http://stackoverflow.com/a/52342273
answer count: 2
has answer: http://stackoverflow.com/a/52342273
upvote count: 0
has body: I have a list of dictionary or a dictionary of list, d1 and d2 as below. d1 = [{'A':1, 'B':2, 'score':1},{'A':11, 'B':22, 'score':2},{'A':111, 'B':2222, 'score':3}] d2 = {'A':[1,11,111], 'B':[2,22,222], 'score':[1,2,3]} I need to 'filter' the dictionary by value of a key. For example, I need the value of 'A' and 'B' , where score is highest. What I want is: {'A':111, 'B':2222} One way I can do is to convert the dictionary list to pandas dataframe, filter rows and convert back to dictionary. But that is really inefficient.... Thanks a lot for advice in advance.
favorite count: 0
accepted answer: http://stackoverflow.com/a/52346597
tagged with: python
downvote count: 1

http://stackoverflow.com/a/52295442
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52295061
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52295061
has body: If you want to store the schedule in database you can use django-celery-beat database backed periodic task. https://django-celery-beat.readthedocs.io/en/latest/
type: AcceptedAnswer

http://stackoverflow.com/q/52406884
tagged with: python
has answer: http://stackoverflow.com/a/52406932
downvote count: 1
type: Question
score: -1
has title: "No Such File or Directory" in Python
has body: I'm trying to create an encryption program that is also capable of using a username and password to be accessed, alongside the password being able to be changed, however, I am getting the following error when trying to read the password from a file. Traceback (most recent call last): File "C:/Users/Matthew/AppData/Local/Programs/Python/Python37-32/a.py", line 28, in &lt;module&gt; password() File "C:/Users/Matthew/AppData/Local/Programs/Python/Python37-32/a.py", line 9, in password var2 = open("Users\Matthew\AppData\Local\Programs\Python\Python37-32\password.txt","r") FileNotFoundError: [Errno 2] No such file or directory: 'Users\\Matthew\\AppData\\Local\\Programs\\Python\\Python37-32\\password.txt' Password is saved in the Users\Matthew\AppData\Local\Programs\Python\Python37-32\password.txt directory. Below is the code. import os import time def password(): while True: username = input ("Enter Username: ") password = input ("Enter Password: ") var1 = "admin" var2 = open("Users\Matthew\AppData\Local\Programs\Python\Python37-32\password.txt","r") if username == var1 and password == var2: time.sleep(1) print ("Login successful!") answer = input("Do you wish to change your password (Y/N): ") if input == "Y" or "y": var2 = input("Enter new password: ") elif input == "N" or "n": break logged() break else: print ("Password did not match!") def logged(): time.sleep(1) print ("Welcome to the encryption program.") password() def main(): result = 'Your message is: ' message = '' choice = 'none' while choice != '-1': choice = input("\nDo you want to encrypt or decrypt the message?\nEnter 1 to Encrypt, 2 to Decrypt, -1 to Exit Program: ") if choice == '1': message = input("\nEnter the message to encrypt: ") for i in range(0, len(message)): result = result + chr(ord(message[i]) - 2) print (result + '\n\n') result = '' elif choice == '2': message = input("\nEnter the message to decrypt: ") for i in range(0, len(message)): result = result + chr(ord(message[i]) + 2) print (result +…
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/52347991
answers question: http://stackoverflow.com/q/52347965
downvote count: 0
type: Answer
has body: &gt;&gt;&gt; names = ['one', 'two'] &gt;&gt;&gt; names = [n.title() for n in names] &gt;&gt;&gt; names ['One', 'Two'] &gt;&gt;&gt; If you want it to work with a capital letter in it like oNe will be ONe then: &gt;&gt;&gt; names = ['oNe', 'twO'] &gt;&gt;&gt; names = [n[0].upper()+n[1:] if n else "" for n in names] &gt;&gt;&gt; names ['ONe', 'TwO'] &gt;&gt;&gt;
score: 7
upvote count: 7

http://stackoverflow.com/q/52336679
has body: I am attempting to use paramiko to send powershell commands over ssh to a Windows box with OpenSSH on it. The commands appear to be successful (return code 0) even when they should fail, and I'm not getting any output on the pipes. When I try commands like making a directory, it is not created, which makes it seem as though the commands aren't reaching the remote system, but also aren't throwing errors. First, here's my code: version = self.oscall.run_remote(['java', '-version']) def run_remote(self, command): # Command is a list of command + args string = "" self.timeout = 300 for arg in command: string = string + " " + arg self.client.connect(self.host, username=self.user, password=self.pw, timeout=self.timeout) self.transport = self.client.get_transport() self.transport.set_keepalive(1) self.channel = self.transport.open_session(timeout=self.timeout) # transport is abstract connection, session is socket if self.channel.gettimeout() == None: self.channel.settimeout(self.timeout) self.channel.exec_command(string) self.out = self.channel.makefile() self.err = self.channel.makefile_stderr() self.output = CallOutput(self.out, self.err, None) self.output.returncode = self.channel.recv_exit_status() self.channel.close() return self.output class CallOutput(object): def __init__(self, out, err, rc): self.out = out.readlines() self.err = err.readlines() self.outfile = tempfile.TemporaryFile() for line in self.out: if isinstance(line, unicode): line = line.encode('utf-8') self.outfile.write(line + '\n') self.outfile.seek(0) self.errfile = tempfile.TemporaryFile() for line in self.err: if isinstance(line, unicode): line = line.encode('utf-8') self.errfile.write(line + '\n') self.errfile.seek(0) self.returncode = rc Sorry for the wall of text, but I went for completeness. This is part of a larger application. This code works perfectly connecting to Linux, so I don't expect there to be many little bugs. The returncode is always 0, even for garbage, and there is never any outpu…
tagged with: python
type: AnsweredQuestion
tagged with: openssh
tagged with: paramiko
type: Question
tagged with: powershell
score: 0
has answer: http://stackoverflow.com/a/52539460
answer count: 1
has title: Paramiko connection to Windows fails silently (appears to succeed)
accepted answer: http://stackoverflow.com/a/52539460

http://stackoverflow.com/q/52381171
has answer: http://stackoverflow.com/a/52381446
has comment: http://stackoverflow.com/comment/91715639
tagged with: python
has comment: http://stackoverflow.com/comment/91707220
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91714643
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/52382114
type: Question
tagged with: numpy
has title: Using numpy.where to prevent out of bound
tagged with: arrays
answer count: 2
has comment: http://stackoverflow.com/comment/91707080
downvote count: 0
accepted answer: http://stackoverflow.com/a/52382114
has body: I am trying to look up values in an array based on an array of indices. This array of indices can contain indices that could be out of bound. In that case I want to return a particular value (here 0). (I could use a for loop but that would be too slow.) So I am doing this: data = np.arange(1000).reshape(10, 10, 10) i = np.arange(9).reshape(3, 3) i[0, 0] = 10 condition = (i[:, 0] &lt; 10) &amp; (i[:, 1] &lt; 10) &amp; (i[:, 2] &lt; 10) values = np.where(condition, data[i[:, 0], i[:, 1], i[:, 2]], 0) However I still get an out of bound error: IndexError: index 10 is out of bounds for axis 0 with size 10 I guess it is because the second parameters is not lazily evaluated and is evaluated before the function call. Is there a solution in numpy to access an array based on a condition but still retain the order? By retaining the order I mean that I can't filter the array first because I could loose the order in the end result. In the end, in that particular example, I still want the values array to contain a 0 when the indices are out of bound. So the end result would be: array([ 0, 345, 678])
tagged with: where-clause
favorite count: 0
possible better answer: http://stackoverflow.com/a/52381446

http://stackoverflow.com/q/52352985
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52353045
accepted answer: http://stackoverflow.com/a/52353045
tagged with: python
tagged with: generator
has comment: http://stackoverflow.com/comment/91650927
type: AnsweredQuestion
upvote count: 0
has title: Why I can't use a method class as a generator?
linked to: http://stackoverflow.com/q/37349439
type: Question
has comment: http://stackoverflow.com/comment/91650980
score: -2
has body: I am in a very strange situation. I know I can use a method class as a generator as I have done it before. In this other question Can a method within a class be generator? someone asks for the same thing and they say that yes, it can be done. However, I get an error when I try it. Here is a minimal example: class SomeClass(object): def first_ten(self): for i in range(10): yield i a = SomeClass(); next(a.first_ten) 'method' object is not an iterator why? How is this possible? Thank you edited: fixed code indentation
downvote count: 2

http://stackoverflow.com/q/52354178
has comment: http://stackoverflow.com/comment/91653080
has comment: http://stackoverflow.com/comment/91653238
has comment: http://stackoverflow.com/comment/91653060
linked to: http://stackoverflow.com/q/18024298
has comment: http://stackoverflow.com/comment/91653445
has comment: http://stackoverflow.com/comment/91653002
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91653056
has comment: http://stackoverflow.com/comment/91653268
has title: Regex for multiple file paths
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/91653177
has comment: http://stackoverflow.com/comment/91653297
answer count: 0
duplicate of: http://stackoverflow.com/q/18024298
type: Question
has comment: http://stackoverflow.com/comment/91653248
has comment: http://stackoverflow.com/comment/91652999
has body: I want to match files located in multiple directories. The file could be located in various depths of a directory, for example: /root_dir/a.txt or /root_dir/dir_a/b.txt or /root_dir/dir_b/dir_d/c.txt I tried the following regular expression: (('/root_dir')[^/.]+['.txt']) but it seems to be incorrect.
has comment: http://stackoverflow.com/comment/91653362
has comment: http://stackoverflow.com/comment/91653012
has comment: http://stackoverflow.com/comment/91653487
score: 0

http://stackoverflow.com/q/52413246
answer count: 2
tagged with: pandas
has title: How to provide a reproducible copy of your DataFrame with to_clipboard()
downvote count: 1
upvote count: 40
linked to: http://stackoverflow.com/q/45725500
linked to: http://stackoverflow.com/q/32536193
favorite count: 0
tagged with: jupyter-notebook
score: 39
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/113125439
linked to: http://stackoverflow.com/q/45528198
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/45800520
has body: 2018-09-18_reproducible_dataframe.ipynb This question was previously marked as a duplicate of How to make good reproducible pandas examples. Go to that question if you need to make synthetic (fake) data to share. The other question and associated answers cover how to create a reproducible dataframe. They do not cover how to copy an existing dataframe with .to_clipboard, while this question specifically covers .to_clipboard. This may seem like an obvious question. However, many of the users asking questions about Pandas are new and inexperienced. A critical component of asking a question is How to create a Minimal, Complete, and Verifiable example, which explains "what" and "why", but not "how". For example, as the OP, I may have the following dataframe: For this example, I've created synthetic data, which is an option for creating a reproducible dataset, but not within the scope of this question. Think of this, as if you've loaded a file, and only need to share a bit of it, to reproduce the error. import pandas as pd import numpy as np from datetime import datetime from string import ascii_lowercase as al np.random.seed(365) rows = 15 cols = 2 data = np.random.randint(0, 10, size=(rows, cols)) index = pd.bdate_range(datetime.today(), freq='d', periods=rows) df = pd.DataFrame(data=data, index=index, columns=list(al[:cols])) a b 2020-07-30 2 4 2020-07-31 1 5 2020-08-01 2 2 2020-08-02 9 8 2020-08-03 4 0 2020-08-04 3 3 2020-08-05 7 7 2020-08-06 7 0 2020-08-07 8 4 2020-08-08 3 2 2020-08-09 6 2 2020-08-10 6 8 2020-08-11 9 6 2020-08-12 1 6 2020-08-13 5 7 The dataframe could be followed by some other code, that produces an error or doesn't produce the desired outcome Things that should be provided when asking a question on Stack Overflow. A well written coherent question - as formatted text The code that produces the error - as formatted text The entire error Traceback - as formatted text Potentially, the current & expected outcome - as formatted text, or image if it's a pl…
tagged with: dataframe
linked to: http://stackoverflow.com/q/63163254
accepted answer: http://stackoverflow.com/a/52413247
has answer: http://stackoverflow.com/a/52413302
type: Question
has answer: http://stackoverflow.com/a/52413247
possible better answer: http://stackoverflow.com/a/52413302
linked to: http://stackoverflow.com/q/20109391

http://stackoverflow.com/comment/91783975
type: QuestionComment
has text: Ahhhh ok, sorry, well, lines in File are not organized by lines, so its extremely hard, so, the most efficient way is to save a new file with the new data, https://stackoverflow.com/a/23598472/1400926
comment on: http://stackoverflow.com/q/52420064
score: 0
type: Comment

http://stackoverflow.com/q/52406813
has body: I'm trying to create a partial function but with dynamic arguments that are stored as class attributes and changed accordingly. Something like the following code: from functools import partial def foo(*args, msg): print(msg) class Bar: def __init__(self, msg): self.msg = msg self.functions = dict() self.functions['foo'] = partial(foo, msg=self.msg) def foo_method(self, *args): return self.functions['foo'](*args) b =Bar('1') b.foo_method() b.msg = '2' b.foo_method() Only, of course, both statements will print '1' as the partial object fixes the arguments. The only alternative I found was changing the attribute to a property and manually changing the partial attributes with the setter: class Bar: def __init__(self, msg): self._msg = None self.functions = dict() self.functions['foo'] = partial(foo) self.msg = msg def foo_method(self, *args): return self.functions['foo'](*args) @property def msg(self): return self._msg @msg.setter def msg(self, msg): self._msg = msg self.functions['foo'].keywords['msg'] = msg I would like to know if there is a more "pythonic" / efficient way to do this, since I really don't need to use properties except for this workaround.
has answer: http://stackoverflow.com/a/52407367
downvote count: 0
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52407367
tagged with: python
answer count: 4
type: AnsweredQuestion
has title: creating a partial-like object with dynamic arguments
upvote count: 3
possible better answer: http://stackoverflow.com/a/52407257
type: Question
has answer: http://stackoverflow.com/a/52407569
has answer: http://stackoverflow.com/a/52407257
score: 3
has answer: http://stackoverflow.com/a/74520227

http://stackoverflow.com/comment/91618947
comment on: http://stackoverflow.com/a/52335544
type: Comment
has text: You're right. The Jacobi function code was provided by my professor so I am not sure what he was going for when asking to make this code. I will contact him about the error. Thank you for the help!!
score: 0
type: AnswerComment

scikit-learn
tags question: http://stackoverflow.com/q/52356567
tags question: http://stackoverflow.com/q/52376272
tags question: http://stackoverflow.com/q/52382440
tags question: http://stackoverflow.com/q/52374311
tags question: http://stackoverflow.com/q/52384806
tags question: http://stackoverflow.com/q/52279834
tags question: http://stackoverflow.com/q/52354229
tags question: http://stackoverflow.com/q/52324800
tags question: http://stackoverflow.com/q/52295283
tags question: http://stackoverflow.com/q/52351608
tags question: http://stackoverflow.com/q/52273090
tags question: http://stackoverflow.com/q/52318155
tags question: http://stackoverflow.com/q/52296041
tags question: http://stackoverflow.com/q/52390059
tags question: http://stackoverflow.com/q/52278759
tags question: http://stackoverflow.com/q/52316237
tags question: http://stackoverflow.com/q/52366421
tags question: http://stackoverflow.com/q/52363770
tags question: http://stackoverflow.com/q/52392489
tags question: http://stackoverflow.com/q/52410626
tags question: http://stackoverflow.com/q/52391030
tags question: http://stackoverflow.com/q/52339693
tags question: http://stackoverflow.com/q/52398849
tags question: http://stackoverflow.com/q/52346725
tags question: http://stackoverflow.com/q/52322233
tags question: http://stackoverflow.com/q/52331348
tags question: http://stackoverflow.com/q/52379210
tags question: http://stackoverflow.com/q/52427626
tags question: http://stackoverflow.com/q/52373318
tags question: http://stackoverflow.com/q/52289942
tags question: http://stackoverflow.com/q/52346002
tags question: http://stackoverflow.com/q/52416187
tags question: http://stackoverflow.com/q/52338532
tags question: http://stackoverflow.com/q/52367645
tags question: http://stackoverflow.com/q/52413325
tags question: http://stackoverflow.com/q/52362842
tags question: http://stackoverflow.com/q/52354098
tags question: http://stackoverflow.com/q/52372690
tag name: scikit-learn
tags question: http://stackoverflow.com/q/52345054
tags question: http://stackoverflow.com/q/52393979
tags question: http://stackoverflow.com/q/52293899
tags question: http://stackoverflow.com/q/52359797
tags question: http://stackoverflow.com/q/52385474
tags question: http://stackoverflow.com/q/52315128
type: Tag
tags question: http://stackoverflow.com/q/52310347
tags question: http://stackoverflow.com/q/52372282
tags question: http://stackoverflow.com/q/52384400
tags question: http://stackoverflow.com/q/52302047
tags question: http://stackoverflow.com/q/52272901
tags question: http://stackoverflow.com/q/52394823
tags question: http://stackoverflow.com/q/52359458
tags question: http://stackoverflow.com/q/52370048
tags question: http://stackoverflow.com/q/52290175
tags question: http://stackoverflow.com/q/52411992
tags question: http://stackoverflow.com/q/52397002
tags question: http://stackoverflow.com/q/52356128
tags question: http://stackoverflow.com/q/52350074
tags question: http://stackoverflow.com/q/52345236
tags question: http://stackoverflow.com/q/52358114
tags question: http://stackoverflow.com/q/52279902
tags question: http://stackoverflow.com/q/52408949
tags question: http://stackoverflow.com/q/52349169

http://stackoverflow.com/q/52283149
has title: Python: add multiple values foreach
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91514459
has body: Working with Selenium + Python, I am trying to work in multiple values to send in a foreach loop, so far I am able to send to values, but if I insert looks like the syntax is not correct: lists = { 'name1' : 'surname1' 'name2' : 'surname2' 'name2' : 'surname2' } What I need to pass to Selenium via foreach is this kind of data: lists = { 'name1' : 'surname1' : 'age1' : 'location1' 'name2' : 'surname2' : 'age2' : 'location2' 'name2' : 'surname2' : 'age3' : 'location3' } I am sure I am doing some bad syntax here, any help?
answer count: 2
tagged with: automated-tests
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91514772
has answer: http://stackoverflow.com/a/52283542
type: UnansweredQuestion
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/52283290

http://stackoverflow.com/q/52380524
score: 0
upvote count: 1
answer count: 1
downvote count: 1
tagged with: lcm
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: primes
has title: Least Common Multiple of 2 numbers by prime factors of number
has body: In this code, I am trying to get prime factors for the prime method to find LCM. then I am trying to save it by counter but I am not able to divide both key and values for the proper method. I'm stuck at counter, please can anyone help me? from collections import Counter def q2_factor_lcm(a, b): #function for lcm fa = factor_list(a) #factor list for a fb = factor_list(b) #factorlist for b c = Counter(fa) #variables to save counter for a d = Counter(fb) #variables to save counter for b r = c | d r.keys() for key, value in sorted(r.items()): # for loop for getting counter subtraction l = pow(key, value) result = [] # I am getting confused what to do now for item in l: result.append(l) return result #will return result def factor_list(n): # it is to generate prime numbers factors = [] # to save list iprimes = iter( primes_list(n) ) # loop while n &gt; 1: p = next(iprimes) while n % p == 0: # python calculation n = n // p factors.append(p) return factors # it will return factors
type: Question
linked to: http://stackoverflow.com/q/588004
has answer: http://stackoverflow.com/a/52382533

http://stackoverflow.com/a/52403946
accepted answer of: http://stackoverflow.com/q/52403815
downvote count: 0
answers question: http://stackoverflow.com/q/52403815
has comment: http://stackoverflow.com/comment/91752229
has comment: http://stackoverflow.com/comment/91752160
has comment: http://stackoverflow.com/comment/91752195
upvote count: 2
type: AcceptedAnswer
has body: Use vectorized solution with numpy.where and broadcasting boolean mask: cols = ['GOD_odd','mug_price','market_price','goat_price'] mask = df['is_won'] == 1 df[cols] = np.where(mask[:, None], (df[cols] - 1) * -1, 0) Details: print (mask[:, None]) [[False] [False] [False] [ True] [False]] print (np.where(mask[:, None], (df[cols] - 1) * -1, 0)) [[ 0. 0. 0. 0. ] [ 0. 0. 0. 0. ] [ 0. 0. 0. 0. ] [-0.818182 -0.737355 -0.83153 -0.816891] [ 0. 0. 0. 0. ]] print (df) GOD_prob GOD_odd market_prob market_price goat_prob goat_price \ 0 0.31 0.000000 0.301941 0.00000 0.317631 0.000000 1 0.19 0.000000 0.198653 0.00000 0.190179 0.000000 2 0.02 0.000000 0.019226 0.00000 0.019889 0.000000 3 0.55 -0.818182 0.545992 -0.83153 0.550391 -0.816891 4 0.33 0.000000 0.376325 0.00000 0.341564 0.000000 mug_prob mug_price mug_payback_prob mug_payback_price is_won \ 0 0.287306 0.000000 0.320741 3.117783 0 1 0.211225 0.000000 0.208422 4.797962 0 2 0.018166 0.000000 0.023553 42.457316 0 3 0.575588 -0.737355 0.618493 1.616833 1 4 0.326000 0.000000 0.276040 3.622663 0 GOD_brier_score market_brier_score mug_brier_score goat_brier_score \ 0 0.0961 0.091169 0.082545 0.100890 1 0.0361 0.039463 0.044616 0.036168 2 0.0004 0.000370 0.000330 0.000396 3 0.2025 0.206124 0.180126 0.202149 4 0.1089 0.141620 0.106276 0.116666 mug_payback_brier_score 0 0.102875 1 0.043440 2 0.000555 3 0.145548 4 0.076198
type: Answer
score: 2

http://stackoverflow.com/a/52406328
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/91757078
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52406104
answers question: http://stackoverflow.com/q/52406104
score: 5
type: AcceptedAnswer
has body: You can make the csv writer write to a io.StringIO object instead and then convert the output to an io.BytesIO object after encoding its text value to bytes: import io csvfile = io.StringIO() writer = csv.DictWriter(csvfile, fieldnames=csv_columns1) #csv_columns1 is a list of value to become as heading writer.writeheader() for data in vals['details']:# values for the header writer.writerow(data) writer = csv.DictWriter(csvfile, fieldnames=csv_columns2)#csv_columns1 is a list of value to become as heading writer.writeheader() writer = csv.DictWriter(csvfile, fieldnames=csv_columns)#csv_columns1 is a list of value to become as heading writer.writeheader() for data in vals['OrderLine']:# values for the header writer.writerow(data) print(os.system('pwd')) Output_Directory = "ftp_path_to_store_file" username = "ftp_user_names" password = "ftp_password" ftp_ip = "ftp_host_ip" a1 = 'STOR %s.csv' % (order.name) try: ftp = FTP(ftp_ip) ftp.login(username, password) ftp.cwd(Output_Directory) ftp.storbinary('STOR ' + os.path.basename(csv_file), io.BytesIO(csvfile.getvalue().encode()))

http://stackoverflow.com/a/75257952
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52407797
has body: For a performant way to count the lines in a gzip file you can use the pragzip package: import pragzip result = 0 with pragzip.open(myfile) as file: while chunk := file.read( 1024*1024 ): result += chunk.count(b'\n') print(f"Number of lines: {result}") Comparing the timing of the above with @DmitryKovriga's answer: Number of lines: 33468793 Elapsed time is 22.373915 seconds. File datasets/binance-futures_incremental_book_L2_2020-07-01_BTCUSDT.csv.gz contain 33468793 lines Elapsed time is 31.278056 seconds. A speed up of more like 10x should be possible with a suitable setup. See https://unix.stackexchange.com/a/713093/163459 for more info.
type: Answer
downvote count: 0

http://stackoverflow.com/comment/91638928
comment on: http://stackoverflow.com/a/52343813
score: 0
type: AnswerComment
has text: Add logging before every line, see where it's barfing.
type: Comment

http://stackoverflow.com/q/52303349
has body: i tried something using python and while the encrypt() function works fine, the decrypt() function doesnt give me any output, not even an error :( My code: import os abc=['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', ' ', '.', ',', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '+', '-', ':', "'"] mixed=abc[::-1] os.system("clear") def menu(): print "-----------" print "[1] Encrypt" print "[2] Decrypt" print "-----------" if input("&gt;&gt;&gt; ")==1: encrypt() elif input("&gt;&gt;&gt; ")==2: decrypt() def encrypt(): os.system('clear') text=raw_input("&gt;&gt;&gt; ").lower() text=list(text) textnew=text for i in range(len(text)): textnew[i]=mixed[abc.index(text[i])] print ''.join(textnew) menu() def decrypt(): os.system('clear') text=raw_input("&gt;&gt;&gt; ").lower() text=list(text) textnew=text for i in range(len(text)): textnew[i]=abc[mixed.index(text[i])] print ''.join(textnew) menu() menu()
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
answer count: 2
has title: Almost the same function, but doesnt work?
accepted answer: http://stackoverflow.com/a/52303463
downvote count: 0
possible better answer: http://stackoverflow.com/a/52303636
has answer: http://stackoverflow.com/a/52303636
tagged with: python-2.x
favorite count: 0
has comment: http://stackoverflow.com/comment/91554459
has comment: http://stackoverflow.com/comment/91554418
has answer: http://stackoverflow.com/a/52303463
tagged with: python

http://stackoverflow.com/a/56620105
answers question: http://stackoverflow.com/q/52390804
has body: You installed the Datadog agent &amp; trace agent on a Mac, listening on localhost. You installed the flask application and ddtrace library in a docker container on a linux vm sending traffic to localhost. Those two localhosts are describing two different machines. The easiest option is going to be running both the Agent &amp; flask app on the Mac, or running both in docker. The latter is most similar to an eventual production deployment. Do that.
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/91711098
has text: @ThomasStrub, @ Jon Clements I've edited the with the built result and src code. ITEM_PIPELINES have enabled
type: Comment
comment on: http://stackoverflow.com/q/52382517
score: 0
type: QuestionComment

http://stackoverflow.com/a/52346686
has body: There are two minor issues with the code snippet you posted: The a + b computation is happening outside the context of the tape, so it is not being recorded. Note that GradientTape can only differentiate computation that is recorded. Computing a + b inside the tape context will fix that. Source tensors need to be "watched". There are two ways to signal to the tape that a tensor should be watched: (a) explicitly invoking tape.watch, or (b) Using a tf.Variable (all variables are watched), see documentation Long story short, two trivial modifications to your snippet do the trick: import tensorflow as tf tf.enable_eager_execution() a = tf.constant(0.) with tf.GradientTape() as tape: tape.watch(a) b = 2 * a c = a + b da, db = tape.gradient(c, [a, b]) print(da) print(db) Hope that helps.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/52340645
answers question: http://stackoverflow.com/q/52340645
upvote count: 4

http://stackoverflow.com/comment/128810916
score: 0
has text: This code example does not showcase the actual usage of a mutex with the threading library. The 1st link is dead.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/59112442

http://stackoverflow.com/q/52343688
tagged with: python
score: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/91649675
has comment: http://stackoverflow.com/comment/91640591
type: Question
tagged with: apache-spark-sql
has body: Let's assume that we have data like this(sorted by time) and created the dummy column for the classes in Pyspark dataframe: ID class e_TYPE_B e_TYPE_C e_TYPE_L e_TYPE_A e_TYPE_E e_TYPE_G 1 G 0 0 0 0 0 1 1 B 1 0 0 0 0 0 1 B 1 0 0 0 0 0 2 E 0 0 0 0 1 0 2 E 0 0 0 0 1 0 2 C 0 1 0 0 0 0 2 C 0 1 0 0 0 0 2 E 0 0 0 0 1 0 2 E 0 0 0 0 1 0 3 L 0 0 1 0 0 0 3 L 0 0 1 0 0 0 3 B 1 0 0 0 0 0 3 E 0 0 0 0 1 0 4 A 0 0 0 1 0 0 4 A 0 0 0 1 0 0 5 B 1 0 0 0 0 0 5 B 1 0 0 0 0 0 5 A 0 0 0 1 0 0 5 A 0 0 0 1 0 0 Now, I am trying to findout the count of ID moving from one class to another.It can be consecutive or may have some other classes in between. The relation should be created for each class from top to bottom on ID basis. For Example, ID 1 goes from G to B then 1 should be added to G to B counter, ID 2 goes from E to C then 1 should be added to E to C counter, ID 2 goes from C to E then 1 should be added to C to E counter, ID 3 goes from L to B then 1 should be added to L to B counter, ID 3 goes from B to E then 1 should be added to B to E counter, Also ID 3 goes from L to E then 1 should be added to L to E counter, ID 4 have only one class so it should be discarded I thought of using Window operation which should partition on ID, but how to iterate the partition to calculate the count of above class relation is that i am struggling on. Please provide the solution/code snippet for this. Thanks.
tagged with: pyspark
upvote count: 2
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/91684054
has title: PySpark Dataframe - Iterate over window partition by
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52386284
upvote count: 2
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/52388536
score: 2
type: AnsweredQuestion
has title: How to serialize result of objects.filter django based on foreign key object
type: Question
possible better answer: http://stackoverflow.com/a/52386487
has answer: http://stackoverflow.com/a/52386487
has answer: http://stackoverflow.com/a/52388536
answer count: 2
downvote count: 0
tagged with: django-rest-framework
favorite count: 0
has body: I have two models one with a foreign key to the other: class Booking(models.Model): type_course_requested = models.ManyToManyField(TypePost, blank=True) ..... #Presentation Message message = models.CharField(max_length=1000) class BookingDemand(models.Model): booking = models.ForeignKey(Booking, on_delete=models.CASCADE, null=True, blank=True) I want to get bookingdemands based on certain condition, and then serializing to have something like the code below: { 'booking1': { 'key1':... 'bookingDemands': {....} }, 'booking2': {...} } Filtering is done like this: bookings=BookingDemand.objects.filter(booking__post__person=self.request.user) which returns a queryset, but I can't find how to serialize them to have each booking separatly as mentionned above.

http://stackoverflow.com/comment/91795422
type: QuestionComment
comment on: http://stackoverflow.com/q/52423443
type: Comment
has text: the url you are trying to hit from lambda, is it a public endpoint? Is you lambda inside the vpc? if so it should be launched inside a public subnet, check your n/w configuration.
score: 0

http://stackoverflow.com/comment/91668328
type: Comment
comment on: http://stackoverflow.com/a/52361681
has text: So In that case whenever new function has been added then that function has to be add in mapping variable. And Thanks for the answer it resolves my problem.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52348653
type: AnsweredQuestion
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52348894
possible better answer: http://stackoverflow.com/a/52348753
type: Question
has body: I'm trying to make a permanent account creation for my game that i'm making which requires you to create an account before being able to play the game. I was trying to figure out how to add it and this is the closest I managed to get to adding it to the file. What happens is that it asks for the user to input their name and then it is meant to save it to the list in the first row of my variables.py, This is what I attempted to do elif menu == '3': enterUsername = input('Please Enter A New Username') with open('variables.py', 'a') as text_file: print ("{}".format(enterUsername)[0], file=text_file) continue Unfortunately this doesn't seem to work and it adds the name to the bottom of the file. There is existing names already in the list so I want to add it for example main.py User inputs = "TestUserName" variables.py authUsers = ['David', 'John', 'Ali','TestUserName'] I also attempted to change the [0] on line 4 to [authUsers] but it returned with an error saying that it can only be integers. As well as this I read the documents here https://developers.google.com/edu/python/lists . Thanks if anyone can help!
has answer: http://stackoverflow.com/a/52348753
accepted answer: http://stackoverflow.com/a/52348894
score: 0
answer count: 2
has title: Trying to add user inputted variable into already existing list in a different file?
has comment: http://stackoverflow.com/comment/91643202
favorite count: 0
tagged with: python

http://stackoverflow.com/a/54954401
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/136382150
downvote count: 1
answers question: http://stackoverflow.com/q/52334538
type: Answer
has body: You don't need to do ft = turtle.Turtle() , Rather just import turtle, then the function for the shape is shape(name = "turtle"). This is what the program should look like: import turtle shape(name = "turtle") color("blue") #The color you want forward(100) backward(50) left(90) forward(200)

http://stackoverflow.com/comment/91779202
score: 0
type: AnswerComment
type: Comment
has text: I got an error 'AttributeError: module 'os' has no attribute 'abspath' ' but I already did 'from os.path import abspath'
comment on: http://stackoverflow.com/a/52418047

http://stackoverflow.com/q/52372346
has comment: http://stackoverflow.com/comment/91727727
upvote count: 1
type: Question
has body: In Sympy, for sqrt(3)- it gives me sqrt(3)(which is not evaluated) Now for sqrt(3.2)- it gives me 1.78885438199983 (which is evaluated) Is there any way it is left unevaluated? I mean for sqrt(3.2) should give me sqrt(3.2) (in symbolic form) similarly for 1./3 it should give the same symbolic expression as 1/3
has title: Numerical evaluation in sympy
downvote count: 0
has comment: http://stackoverflow.com/comment/91730328
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1

http://stackoverflow.com/comment/91692718
type: QuestionComment
has text: Understood. This is really helpful!
comment on: http://stackoverflow.com/q/52372760
score: 0
type: Comment

http://stackoverflow.com/comment/91800444
has text: You haven't read the tutorial correctly. It does not say to *call* `iloc`.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52428472

http://stackoverflow.com/comment/91787442
score: 0
has text: So according to your output, you need combination of indexes such as [01, 23, 45, 67, 89, ...] for given series. Is that right?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52421932

http://stackoverflow.com/comment/91733258
type: Comment
has text: Thanks, and I will keep it to one question per post going forward. Regards, w
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52393991

http://stackoverflow.com/q/52333154
tagged with: python
has comment: http://stackoverflow.com/comment/91613216
has comment: http://stackoverflow.com/comment/91614822
has comment: http://stackoverflow.com/comment/91613234
downvote count: 3
type: Question
upvote count: 0
answer count: 1
has body: I want to write a function called compress, which takes in a list, two indices and a function, and spits out the same list with the two elements specified "compressed" together with the given function. I have implemented this with copy.deepcopy as follows: import copy def compress(l, i, j, f): r = copy.deepcopy(l) r[i] = f(r[i], r[j]) r.pop(j) return r Is there a more pythonic way to do this? Or perhaps a more "pure" functional way?
has comment: http://stackoverflow.com/comment/91627211
tagged with: functional-programming
has answer: http://stackoverflow.com/a/52334405
has title: Apply function to part of list python
favorite count: 0
type: UnansweredQuestion
score: -3

http://stackoverflow.com/q/52322923
accepted answer: http://stackoverflow.com/a/52323042
type: Question
tagged with: python
score: 1
upvote count: 1
tagged with: request
answer count: 1
has title: Getting data from flask request is slow
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/52323042
tagged with: flask
has body: I have a device sending POSTs to my server. In python, I grab the posted data using either: request.data request.get_data request.get_json But the times I can getting for these simple data gets varies. I test with something like this: start = time.time() resp = request.data return str(time.time() - start) From some end nodes, I see times of sub 1ms, and some, I see over 100ms, for the same amount of data. Since the request object is already created, and I assume the data is already received, what contributes to this variance in speed?
favorite count: 0

http://stackoverflow.com/comment/91533651
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52292724
score: 0
has text: As I said, understanding these basics, you can easily adapt your VBA code to the `pandas` code that suits you. Take your time, experiment and make adaptation of your VBA an exercise for yourself to completely understand the concepts. Good luck with `pandas`! :)

http://stackoverflow.com/q/52333570
upvote count: 1
favorite count: 0
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91614206
has title: How to give user input to Django RestAPI using postman?
has body: I have made an DjangoRestApi and giving user input using postman(POST method).but the error is TypeError: Object of type 'JSONDecodeError' is not JSON serializable it is showing in django server where i am going wrong please help Thanks views.py import spacy from django.shortcuts import render,HttpResponse from django.http import Http404 from rest_framework.views import APIView from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from django.http import JsonResponse from django.core import serializers from django.conf import settings import json nlp = spacy.load('en_core_web_sm') @api_view(["POST"]) def nounphrases(requestdata): try: text = json.loads(requestdata.body) nounphrases = [] for word in (nlp((text))): c = (word.lemma_) nounphrases.append(c) output = [{"nounphrases" : nounphrases }] return JsonResponse(json.dumps(output)) except ValueError as e: return Response(e,status.HTTP_400_BAD_REQUEST)
score: 1
has comment: http://stackoverflow.com/comment/91683457
type: Question
tagged with: api
tagged with: django-rest-framework

http://stackoverflow.com/a/52297928
upvote count: 2
has comment: http://stackoverflow.com/comment/91543839
type: Answer
has body: In the original code example, if b == 44993: compares the parameter b to 44993. Since b is expected to be a boolean, this comparison will always return false. Here is my solution: def compute_xp(i, b): if b: return 44993 + i else: return 44993 if b: checks the boolean value of b, so if b is true, then return 44993 + i will be executed. If b is false, then return 44993 will be executed.
answers question: http://stackoverflow.com/q/52297819
score: 2
downvote count: 0

http://stackoverflow.com/a/52345369
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52345349
upvote count: 1
has body: for a in b iterates through b by calling iter(b) first to get an iterator of b, and repeatedly calling next() on the iterator and assigning the values to a before running the loop body. An iterator of a python dictionary generates all its keys, so you're getting all keys of thisdict with x in your loop and printing them.

http://stackoverflow.com/q/52353499
has comment: http://stackoverflow.com/comment/91652244
answer count: 1
has comment: http://stackoverflow.com/comment/91651835
has comment: http://stackoverflow.com/comment/91651889
has comment: http://stackoverflow.com/comment/91651829
favorite count: 0
has comment: http://stackoverflow.com/comment/91651781
has comment: http://stackoverflow.com/comment/91651945
has comment: http://stackoverflow.com/comment/91652053
has comment: http://stackoverflow.com/comment/91651811
has comment: http://stackoverflow.com/comment/91651793
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91651838
tagged with: python
has comment: http://stackoverflow.com/comment/91652118
has comment: http://stackoverflow.com/comment/91651814
has comment: http://stackoverflow.com/comment/91652466
has answer: http://stackoverflow.com/a/52353810
score: -5
has title: Python while loop, if then conditions not working properly
has comment: http://stackoverflow.com/comment/91652017
has body: I am new to Python and attempting my first while loop. The below code is meant to iterate over the defined formula as defined by the user in the number_of_moves variable. When i = 1, it should execute one formula, however when i &gt; 1 it should execute another. So I defined an if else statement inside a formula. Issue is that when i &gt; 1 it does not pick up the 2nd formula but continues to use the first defined formula, which is (22695477 * x + 1) % 2 ** 31. Effectively, the else statement x2 should equal to the output from the previous iteration x1 and x3 should equal the value from the output of x2 ... and so on ... using this formula (22695477 * x2 + 1) % 2 ** 31. print("Choose the type of game(1:Easy;2 Difficult)") levelinput = int(input()) print("") print("Enter the number of moves") number_of_moves = int(input()) i =1 x = 79 randomvalue = (22695477*x+1)%2**31 x2 = randomvalue machine = int() while i &lt;= number_of_moves: print("") print("Choose your move number", i ,"(0 or 1)") move_selection = int(input()) if i == 1: randomvalue = (22695477*x+1)%2**31 else: randomvalue = (22695477*x2+1)%2**31 i = i +1 if randomvalue &lt;= 2**31: machine == int(0) else: machine == int(1) def resultgame (move_selection,machine): if move_selection == machine: return("Computer Wins") else: return("Player Wins") result = resultgame print("player = ", move_selection, "machine = ", machine,"-", result(move_selection,machine))
has comment: http://stackoverflow.com/comment/91651913
has comment: http://stackoverflow.com/comment/91652185
tagged with: loops
has comment: http://stackoverflow.com/comment/91651901
type: Question
has comment: http://stackoverflow.com/comment/91651876
downvote count: 5
has comment: http://stackoverflow.com/comment/91651804
has comment: http://stackoverflow.com/comment/91652187
has comment: http://stackoverflow.com/comment/91652356
tagged with: while-loop
upvote count: 0
has comment: http://stackoverflow.com/comment/91652032

http://stackoverflow.com/q/52288565
favorite count: 0
has body: I'm trying to create Actix Actor which has PyO3 Python interpreter &amp; Py objects. Question is what is the correct way to create python interpreter actor? I think err caused by Actor trait defined static. https://docs.rs/actix/0.7.4/actix/trait.Actor.html Is there the way of Actor or Context have object require life parameter? rust version: nightly-2018-09-04, actix version: 0.7.4 This is current code. extern crate actix; extern crate actix_web; extern crate pyo3; use actix::prelude::*; use actix_web::{http, server, ws, App, HttpRequest, HttpResponse, Error}; use pyo3::{Python, GILGuard, PyList}; struct WsActor&lt;'a&gt; { // addr: Addr&lt;PyActor&gt;, gil: GILGuard, python: Python&lt;'a&gt;, pylist: &amp;'a PyList, } impl&lt;'a&gt; Actor for WsActor&lt;'a&gt; { type Context = ws::WebsocketContext&lt;Self&gt;; } fn attach_ws_actor(req: &amp;HttpRequest&lt;()&gt;) -&gt; Result&lt;HttpResponse, Error&gt; { let gil = Python::acquire_gil(); let python = gil.python(); let pylist = PyList::empty(python); let actor = WsActor {gil, python, pylist}; ws::start(req, actor) } fn main() { let sys = actix::System::new("example"); server::new(move || { App::new() .resource("/ws/", |r| r.method(http::Method::GET).f(attach_ws_actor)) }).bind("0.0.0.0:9999") .unwrap() .start(); } This code can't compile with this err. error[E0478]: lifetime bound not satisfied --&gt; src/main.rs:15:10 | 15 | impl&lt;'a&gt; Actor for WsActor&lt;'a&gt; { | ^^^^^ | note: lifetime parameter instantiated with the lifetime 'a as defined on the impl at 15:6 --&gt; src/main.rs:15:6 | 15 | impl&lt;'a&gt; Actor for WsActor&lt;'a&gt; { | ^^ = note: but lifetime parameter must outlive the static lifetime
upvote count: 1
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52289118
score: 1
tagged with: rust-actix
has comment: http://stackoverflow.com/comment/91526085
type: Question
has title: How can actix Actor have PyO3 Python?
answer count: 2
has answer: http://stackoverflow.com/a/52365425
accepted answer: http://stackoverflow.com/a/52365425
downvote count: 0
tagged with: rust
has comment: http://stackoverflow.com/comment/91525709
tagged with: pyo3
has answer: http://stackoverflow.com/a/52289118
tagged with: python

http://stackoverflow.com/q/52306661
answer count: 1
has answer: http://stackoverflow.com/a/59481034
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91580658
has comment: http://stackoverflow.com/comment/91560626
tagged with: python
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91629947
has body: I am new user of python and networks, I have trouble to read some data from .gml file My IDE is Spyder,Anaconda,and OS is macOS is I follow the instruction online ,here is my code ,here is the Dataset import networkx as nx import matplotlib.pyplot as plt G = nx.Graph() G = nx.read_gml('karate.gml') print (nx.info(G)) then the complier shows "node #0 has no 'label' attribute". How could it happens
has comment: http://stackoverflow.com/comment/99322794
tagged with: networkx
has comment: http://stackoverflow.com/comment/91581439
type: Question
linked to: http://stackoverflow.com/q/39200898
has comment: http://stackoverflow.com/comment/91560585
has comment: http://stackoverflow.com/comment/91563559
upvote count: 1
has title: node #0 has no 'label' attribute?How come it happens

http://stackoverflow.com/a/52315164
type: Answer
has comment: http://stackoverflow.com/comment/105095745
upvote count: 20
has comment: http://stackoverflow.com/comment/93744530
downvote count: 0
answers question: http://stackoverflow.com/q/52295117
has comment: http://stackoverflow.com/comment/93527705
has comment: http://stackoverflow.com/comment/91610330
has body: Following mewahl's comment I've added to my .bashrc (I use bash): export PROJ_LIB=/path/to/your/instalation/of/anaconda/share/proj/ and now basemap (and others work).
score: 20

http://stackoverflow.com/q/52304678
tagged with: python
has title: Fetch all emails from gmail of a particular label
upvote count: 1
tagged with: imaplib
type: Question
has body: I want to fetch all the emails from gmail of a particular label called important. I am using imaplib and python 2. Below is my code, import email, getpass, imaplib, os detach_dir = '.' user = raw_input("Enter your GMail username:") pwd = getpass.getpass("Enter your password: ") # connecting to the gmail imap server m = imaplib.IMAP4_SSL("imap.gmail.com") m.login(user,pwd) m.select("important") resp, items = m.search(None, "ALL") items = items[0].split() print len(items) for emailid in items: resp, data = m.fetch(emailid, "(RFC822)") email_body = data[0][1] mail = email.message_from_string(email_body) if mail.get_content_maintype() != 'multipart': continue print "["+mail["From"]+"] :" + mail["Subject"] for part in mail.walk(): if part.get_content_maintype() == 'multipart': continue if part.get('Content-Disposition') is None: continue filename = mail["From"] + "_hw1answer" att_path = os.path.join(detach_dir, filename) if not os.path.isfile(att_path) : fp = open(att_path, 'wb') fp.write(part.get_payload(decode=True)) fp.close() The error is showing, imaplib.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED But, if I use INBOX then it is working. Working when m.select("inbox") What is the recommended way to achieve it ?
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/52323097
downvote count: 0
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91555802
type: Comment
has text: Go pandas.! (-:
comment on: http://stackoverflow.com/a/52302366
score: 1
type: AnswerComment

http://stackoverflow.com/comment/91565881
type: QuestionComment
comment on: http://stackoverflow.com/q/52304128
type: Comment
has text: Oh thanks for pointing that out! I didn't find it before. I'm still confused though, why would jetbrains make examples like this if it isn't supported?
score: 0

http://stackoverflow.com/comment/91508522
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52280007
has text: see the edit. I thought you were doing a 5D regression with 1 point. I have updated
type: AnswerComment

http://stackoverflow.com/q/52331966
has comment: http://stackoverflow.com/comment/91613599
has comment: http://stackoverflow.com/comment/91610962
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52332273
has title: Read a txt-file as dict containing a numpy-array
has comment: http://stackoverflow.com/comment/91611078
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91611528
has body: I have a lot of .txt files that I want to read. The .txt files were saved by converting a python dictionary to a string and saving the string in a .txt file. param_string = str(parameters-as-dict) text_file = open(parameter_file_path, "w") text_file.write(param_string) text_file.close() The entries of the dict are of mixed types (float, int, string,...). In some of the files one entry of the dict is a numpy-array and is saved in the txt-file as 'epsilons': array([...]) Because I want to access the values saved in the dict by their names, I now want to read the txt-file and load them as a dict again. This works easily with f = open(path, 'r') parameters = ast.literal_eval(f.read()) as long as there is no numpy array in the file. When the numpy-array is present, I get the error: File ".../python3.6/ast.py", line 84, in _convert raise ValueError('malformed node or string: ' + repr(node)) ValueError: malformed node or string: &lt;_ast.Call object at 0x7fb5428cc630> Which makes sense, looking at the as.literal_eval documentation (https://docs.python.org/2/library/ast.html) which says Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None. Since I can't resave the file differently, I don't know at which position the array is and I want to avoid cumbersome regex parsing, I'm searching for a solution that transforms my txt-file into a dict containing a numpy-array. EDIT: the problem is not only the numpy array but also when I saved an object of e.g. a specific class: , 'foo' : &lt;class bar&gt;, A solution, where everything that can not be parsed as some kind of number/bool/some knonw datatype is automatically saved as a string just as it is would satisfy my needs.
has comment: http://stackoverflow.com/comment/91611726
has comment: http://stackoverflow.com/comment/91611782
answer count: 2
has answer: http://stackoverflow.com/a/52333348
has comment: http://stackoverflow.com/comment/91611104
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/a/52335255
has body: The problem is that you made equipped_weapon a class attribute, not an instance attribute. del instance.attribute only deletes instance attributes, it doesn't even look for class attributes. If the goal is just to change the instance, you can just remove the del entirely; the next line will add (if no instance attribute exists, shadowing the class attribute) or replace (if an instance attribute already exists) the instance's specific weapon. If the goal is to change the class, you need to change the assignment to operate on the class: type(player).equipped_weapon = new_weapon_code or explicitly naming the class: Player.equipped_weapon = new_weapon_code Either way, the del isn't necessary; assigning the new value replaces the old one, implicitly dropping the reference to the old value in the same way that del does explicitly. It would be perfectly legal to do del type(player).equipped_weapon or del Player.equipped_weapon to delete the class attribute specifically, but it's pointless; whatever the desired behavior, simple assignment to either the class or the instance attribute will discard the old reference anyway. UPDATE: As you noted, removing the del prevents the exception, but your output (from see_inventory) never changes. That's because see_inventory is looking at Player.inv, which in turn contains a reference to the original value of Player.ui_equipped_weapon. Problem is, while ui_equipped_weapon and equipped_weapon are initialized based on the same default weapon, they're not synced to one another; changing one has no effect on the other (and therefore changing equipped_weapon, on the class or instance, doesn't affect inv, so see_inventory never changes). Really, the solution here is to make a sane class. None of your class attributes make sense; they're all logically instance attributes and should be defined as such. In a few cases, they're just convenience-oriented transformations of another attribute; in those cases, they shouldn't be attributes at all, bu…
upvote count: 3
has comment: http://stackoverflow.com/comment/91619452
has comment: http://stackoverflow.com/comment/91619606
score: 3
accepted answer of: http://stackoverflow.com/q/52335181
has comment: http://stackoverflow.com/comment/91618317
answers question: http://stackoverflow.com/q/52335181
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91621119
has comment: http://stackoverflow.com/comment/91625125
type: Answer

http://stackoverflow.com/comment/91588767
type: AnswerComment
comment on: http://stackoverflow.com/a/52320250
has text: Thanks for helpful answer, works great! Users have to be deleted due to privacy policy in our case :)
type: Comment
score: 0

http://stackoverflow.com/a/52375122
has comment: http://stackoverflow.com/comment/91695253
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91696382
answers question: http://stackoverflow.com/q/52374941
has comment: http://stackoverflow.com/comment/91695371
has comment: http://stackoverflow.com/comment/91695320
has comment: http://stackoverflow.com/comment/91696358
accepted answer of: http://stackoverflow.com/q/52374941
has comment: http://stackoverflow.com/comment/91695408
has body: You need to use json.loads() to convert a JSON string to a Python dictionary or list. Use the decode() method to convert the bytes to a string. data = json.loads(source.decode('utf-8')) You're also accessing the JSON incorrectly. data['value'] is a list of dictionaries, not a dictionary by itself. The loop should be: for value in data['value']: print(value['temp'])
upvote count: 1
has comment: http://stackoverflow.com/comment/91696514
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91696300
has comment: http://stackoverflow.com/comment/91696463
has comment: http://stackoverflow.com/comment/91695299
has comment: http://stackoverflow.com/comment/91695820
type: Answer

http://stackoverflow.com/a/52300587
answers question: http://stackoverflow.com/q/52300157
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52300157
type: Answer
downvote count: 0
score: 1
has body: Suppose data = db_iter.get_next(), where db_iter is the iterator you are using from tf.data. I suppose you are traning the 3 ops in 3 different sess.run statements. In that case they will all use 3 different batches as data will be evaluated 3 times. The fact is that, if the input to each of the three training ops are provided from data as defined above, and run within each sess.run, they will all use the same batch.
upvote count: 1

http://stackoverflow.com/q/52349807
tagged with: ubuntu
score: 0
answer count: 2
has body: I am new on VM, but is following the book - Learning Scrapy by DKL. It seems to be setting up a Virtual environment via Vagrant and VirtualBox. I think I have everything set up - installed Vagrant and VirtualBox of ubuntu 12.04.5 LTS. Then I use Cmder.exe (in my project folder e:...\Project) to access Vagrant λ vagrant up Bringing machine 'default' up with 'virtualbox' provider... ==&gt; default: Checking if box 'hashicorp/precise64' is up to date... ==&gt; default: Machine already provisioned. Run `vagrant provision` or use the `--provision` ==&gt; default: flag to force provisioning. Provisioners marked to run always will still run. λ vagrant ssh Welcome to Ubuntu 12.04.5 LTS (GNU/Linux 3.2.0-23-generic x86_64) * Documentation: https://help.ubuntu.com/ New release '14.04.5 LTS' available. Run 'do-release-upgrade' to upgrade to it. This Ubuntu 12.04 LTS system is past its End of Life, and is no longer receiving security updates. To protect the integrity of this system, it’s critical that you enable Extended Security Maintenance updates: * https://www.ubuntu.com/esm Welcome to your Vagrant-built virtual machine. Last login: Sat Sep 15 23:40:43 2018 from 10.0.2.2 vagrant@precise64:~$ sudo apt-get install scrapy Reading package lists... Done Building dependency tree Reading state information... Done E: Unable to locate package scrapy
tagged with: scrapy-shell
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52350122
tagged with: vagrant
has title: Unable to install Scrapy (Shell) in Ubuntu virtual machine on a Win system
has answer: http://stackoverflow.com/a/52351878
tagged with: scrapy
type: Question

http://stackoverflow.com/comment/91532824
type: Comment
type: QuestionComment
has text: @OwaisAjaz You can use tls_set() function for configuring tls related options for more info on function check : https://pypi.org/project/paho-mqtt/
comment on: http://stackoverflow.com/q/52281398
score: 0

http://stackoverflow.com/q/52303407
has answer: http://stackoverflow.com/a/52305025
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52305025
has title: numpy.dtype=object very slow compared to numpy.dtype=int
has comment: http://stackoverflow.com/comment/91557047
type: Question
tagged with: numpy
answer count: 1
tagged with: int
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91557418
has body: I am entering high values (greater than 2^70) inside numpy arrays using numpy.dtype=object: numpy.array([1], dtype=numpy.object) &lt;&lt; 70 array([1180591620717411303424], dtype=object) The only reason I am using dtype=numpy.object here is that numpy.int's limit is crossed when you try to enter high values inside it. numpy.array([1]) &lt;&lt; 70 &gt;&gt;&gt; array([64], dtype=int32) #the result should have been array([1180591620717411303424], dtype=object) The details is expained in my other question here.. In such cases using dtype=object works fine. But I found that using dtype=numpy.object is very slow. To verify, I compared the timings of the following operations: You can see that dtype=int is much faster. So is there any workaround for entering high values inside numpy arrays?
has comment: http://stackoverflow.com/comment/91554647
linked to: http://stackoverflow.com/q/52301276
has comment: http://stackoverflow.com/comment/91557681
tagged with: object

http://stackoverflow.com/comment/91695777
type: Comment
type: QuestionComment
score: 4
has text: Did you try something? What exactly is the problem?
comment on: http://stackoverflow.com/q/52375465

http://stackoverflow.com/comment/91546376
has text: I'm not. model2.layers[:-2] returns all BUT the last two layers. Thus the inception base model is being held stationary. I realize that some of the top layers of the inception should be unfrozen for fine tuning, but it shouldn't be causing this issue.
comment on: http://stackoverflow.com/q/52282108
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91780547
type: QuestionComment
comment on: http://stackoverflow.com/q/52407321
score: 0
has text: @1961DarthVader Ok that doesn't seem too bad... maybe you could still try to resample your data and just use let's say ~1k samples for each category, just to see what happens. See also https://machinelearningmastery.com/tactics-to-combat-imbalanced-classes-in-your-machine-learning-dataset/
type: Comment

http://stackoverflow.com/q/52382841
has title: How to make query in an NLP Api?
tagged with: api
downvote count: 0
tagged with: django-rest-framework
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I am Making an API in which I want help is how to make query?. I can display result using 127.0.0.1:8000/Naturallanguageprocessing/ It is getting All attributes that i included parts of speech,lemmatization etc.but i have to display in this way 127.0.0.1:8000/?q = "querytext"&amp;all = 1 It should display all parts of speech ,lemmatization etc. and if i call 127.0.0.1:8000/?q = "querytext" &amp; partsofspeech = 1 &amp; lemmatization = 1. It should display parts of speech and lemmatization. Below is my views.py. from django.shortcuts import render,redirect,HttpResponse from django.views.generic.edit import FormView from rest_framework.decorators import api_view from django.http import JsonResponse from django.conf import settings from rest_framework.response import Response from django.views import View import json import spacy import pdb nlp = spacy.load('en_core_web_sm') @api_view(["POST"]) def Naturallanguageprocessing(requestdata): try: text = str(requestdata.body) stopwordsremoval = [] partsofspeech= [] nounphrases = [] word_lemma = [] tokenization = [] nameentityrecognization = [] for word in (nlp(text)): a = (word.is_stop, word.text) b = (word.text, word.pos_, word.tag_) d = (word.lemma_) e = (word.text) tokenization.append(e) word_lemma.append(d) stopwordsremoval.append(a) partsofspeech.append(b) for word in (nlp(text).noun_chunks): c = (word.text) nounphrases.append(c) for word in (nlp(text).ents): f = (word.text,word.label_) nameentityrecognization.append(f) output = {"stopwordremoval": stopwordsremoval, "partsofspeech": partsofspeech, "nounphrases" : nounphrases, "word_lemma":word_lemma, "tokenization":tokenization, "nameentityrecognization":nameentityrecognization } return JsonResponse(output,safe = False) except ValueError as e: return Response(e.args[0],status.HTTP_400_BAD_REQUEST)
answer count: 0
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/91627083
comment on: http://stackoverflow.com/q/52339907
has text: The intercept should be 4, so there's something wrong with the way you're plotting/the coefficients aren't being interpreted as you intend.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91640823
has text: It would appear as though `l` is a list, not a dictionary.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52347737

http://stackoverflow.com/comment/91737162
has text: @AaronMills, probably. It's hard to say for sure without more context.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52395887

http://stackoverflow.com/a/52383418
answers question: http://stackoverflow.com/q/52382590
has body: As I suspected, this is a circular import problem. You can track the closed loop of dependencies looking at the traceback: app -&gt; resources -&gt; database -&gt; app This is a common mistake and not properly documented in Flask tutorials. As explained here by Lepture, you should avoid declaring db in the __init__.py I always keep this one certain rule when writing modules and packages: Don't backward import from root __init__.py. How should you do it, then? declare db in the proper module (db.py) import it inside the application factory I found myself reluctant towards this pattern, I thought those import statements didn't belong inside a function. But this is the way to go. So, your files should look something alike: app/common/db.py from flask_pymongo import PyMongo mongo = PyMongo app/__init__.py from flask import Flask ... def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) from app.common.db import mongo mongo.init_app(app) ... and when you need your database connection, i.e. in resources module, you should import it like from app.common.db import mongo Note: to avoid future problems, your blueprints should also be declared elsewhere and import on creation time. I really encourage you to read the post by Lepture to better understand this approach.
type: Answer
has comment: http://stackoverflow.com/comment/91713466
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/52382590
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92073709

http://stackoverflow.com/q/52402817
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52403013
has title: How to keep the fraction in the output without evaluating
type: Question
tagged with: sympy
has body: I try to find out the Characteristic Polynomial and Eigen values using sympy. But when I print the results in Jupyter notebook all the fractions in the coefficients of the polynomials have been evaluated as float(e.g-0.5x**2+1) but I want $(1/2)x^2+1$). Is there anything to solve this problem. Thank you. My Code import sympy as sp from sympy import * x, y, z = symbols('x,y,z') init_printing(use_unicode=False, wrap_line=False) M = sp.Matrix([[0, -1/2], [1/3, 0]]) x = symbols('x') p = M.charpoly(x) p Output.
score: 0
linked to: http://stackoverflow.com/q/13208286
answer count: 1
has answer: http://stackoverflow.com/a/52403013

http://stackoverflow.com/comment/91784291
comment on: http://stackoverflow.com/q/52408253
type: Comment
type: QuestionComment
has text: Because it is more efficient. Because there is only the array, no elements. Because the array stores values. Because it was implemented this way. Because... Which kind of answer do you seek?
score: 0

http://stackoverflow.com/q/52310501
downvote count: 1
type: Question
has title: Trying to write CSV file to Oracle databse table with pandas
tagged with: pandas
has answer: http://stackoverflow.com/a/52314849
answer count: 1
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: I am trying to write aa table to an Oracle database using Python's pandas. Here's is my code: import cx_Oracle import pandas as pd import csv df = pd.read_csv('C:/Users/admin/Desktop/customer.csv') conn = cx_Oracle.connect('SYSTEM/Mouni123$@localhost/orcl') df = df.to_sql('cust', conn, 'if_exists=replace') conn.close() df I get the following error: DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ORA-01036: illegal variable name/number What am I doing wrong?
score: 1

http://stackoverflow.com/a/52275996
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52275262
has comment: http://stackoverflow.com/comment/91499728
has comment: http://stackoverflow.com/comment/91499952
has comment: http://stackoverflow.com/comment/91507461
has comment: http://stackoverflow.com/comment/91507390
downvote count: 0
has body: Basically using DataFrame.groupby and diff. Unfortunately the first rows, lacking a previous row for the difference, are nan, and this required some messy cleaning up. There may be a prettier way. df = pd.DataFrame( data=[ ['01-01-2018', 'Jakob', 5, 10], ['01-01-2018', 'Adomas', 10, 20], ['01-01-2018', 'Thomas', 15, 30], ['01-02-2018', 'Jakob', 50, 30], ['01-02-2018', 'Adomas', 100, 40], ['01-02-2018', 'Thomas', 150, 65], ['01-03-2018', 'Jakob', 60, 30], ['01-03-2018', 'Adomas', 120, 45], ['01-03-2018', 'Thomas', 200, 75] ], columns=['Date', 'Sales rep', 'item A', 'item B'] ) cum_columns = ['item A', 'item B'] result = df.merge( df.groupby('Sales rep')[cum_columns].diff(), left_index=True, right_index=True, suffixes=['', '_uncum'] ).fillna({'{}_uncum'.format(cum_column): df[cum_column] for cum_column in cum_columns}) print(result) Out: Date Sales rep item A item B item A_uncum item B_uncum 0 01-01-2018 Jakob 5 10 5.0 10.0 1 01-01-2018 Adomas 10 20 10.0 20.0 2 01-01-2018 Thomas 15 30 15.0 30.0 3 01-02-2018 Jakob 50 30 45.0 20.0 4 01-02-2018 Adomas 100 40 90.0 20.0 5 01-02-2018 Thomas 150 65 135.0 35.0 6 01-03-2018 Jakob 60 30 10.0 0.0 7 01-03-2018 Adomas 120 45 20.0 5.0 8 01-03-2018 Thomas 200 75 50.0 10.0

http://stackoverflow.com/q/52313457
type: Question
has answer: http://stackoverflow.com/a/52313780
has comment: http://stackoverflow.com/comment/91574016
has comment: http://stackoverflow.com/comment/91574240
tagged with: pandas
answer count: 1
downvote count: 0
has title: Group by month, week using date column
accepted answer: http://stackoverflow.com/a/52313780
favorite count: 0
has body: I have a dataframe with the following columns: user,dates,quantity,location and I am thinking of useful group by procedures to make. pd.to_numeric(x['quantity'], errors='coerce').groupby(x['user']).sum().reset_index() gives this: user quanity 0 user_01 8900.0 1 user_02 0.0 2 user_03 0.0 3 user_04 232.0 4 user_05 21.0 5 user_06 110.0 6 user_07 240.0 7 user_08 20500.0 How can I do this including location and dates? Example: to be able to easily change between weekly checks or by month? Note: the dates column is of object type sample data dates user quantity location 0 2018-09-03 user_01 23 GR 1 2018-09-03 user_01 - GR 2 2018-09-03 user_02 3 SW 3 2018-09-03 user_03 - POR 4 2018-09-03 user_04 222 PAN 5 2018-09-03 user_04 - PAN
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91574078
score: 2
has comment: http://stackoverflow.com/comment/91574481
upvote count: 2
has comment: http://stackoverflow.com/comment/91573869

http://stackoverflow.com/a/52360544
has body: You cannot delete an object directly in Python - an object's memory is automatically reclaimed, by garbage collection, when it's no longer possible to reference the object. So long as an object is in a list, it may be referenced again later (via the list). So you need to destroy the list too. For example, like so: while mylst: each_item = mylst.pop() # removes an object from the end of the list # use the item
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52360506
score: 5
upvote count: 5

http://stackoverflow.com/a/52302286
accepted answer of: http://stackoverflow.com/q/52302062
upvote count: 5
answers question: http://stackoverflow.com/q/52302062
downvote count: 0
has comment: http://stackoverflow.com/comment/91552640
score: 5
type: AcceptedAnswer
has body: Your solution might be this one: names=["MARTIN","JAMES","LOUIS","BABYSHARK"] name = input('Enter your name:').upper() if name in names: print('You can play my game') else: print('Access Denied')
type: Answer

http://stackoverflow.com/comment/91534597
comment on: http://stackoverflow.com/q/52292599
score: 0
type: Comment
type: QuestionComment
has text: As far as I'm aware, the top 3 answers in Arne's dupe do apply to python 3. I don't see anything wrong with that dupe target.

http://stackoverflow.com/comment/91605416
type: QuestionComment
comment on: http://stackoverflow.com/q/52329341
score: 1
has text: Your input list doesn't have single quotes in the values. Those are part of the string representations, not the contained characters.
type: Comment

http://stackoverflow.com/comment/91675558
type: AnswerComment
type: Comment
has text: Yeah the byte format is the format of the S2 composite. I want to mimick that. How would I go about scaling the values down?
comment on: http://stackoverflow.com/a/52343443
score: 1

http://stackoverflow.com/comment/91799838
comment on: http://stackoverflow.com/a/52428013
score: 0
type: AnswerComment
has text: Thank you, this is quite awesome :-)
type: Comment

http://stackoverflow.com/a/52275470
has comment: http://stackoverflow.com/comment/91505283
type: Answer
has comment: http://stackoverflow.com/comment/91505366
has comment: http://stackoverflow.com/comment/91505698
has body: I believe the most likely scenario is that you have to close the stdin PIPE, before the subprocess starts executing and printing something. Most likely scenario is that the subprocess is still wainting for input. You might want to try debug as such, close the stdin and see if that works: p.stdin.close() p.stdout.read() If that works see what the subprocess expects as an END of command. E.g. it might be that it expects \r\n insted of \n. Without knowing how the underlying process works, it's difficult to say what's going wrong here.
answers question: http://stackoverflow.com/q/52274383
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52274383
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/52341748
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/52342697
has answer: http://stackoverflow.com/a/52342697
tagged with: django-models
score: -1
accepted answer: http://stackoverflow.com/a/52343200
answer count: 2
has title: How to retrieve models data having nested relationship using serializers in Django Rest Framework?
upvote count: 0
tagged with: django-rest-framework
favorite count: 0
tagged with: django
tagged with: python
has body: i am explaining in detail about a problem that i am facing and seek help from this community. I followed this Django Rest Framework documentation but couldn't get the desired result for multi-level nesting Consider the relationship of models as explained : A user can have multiple Workspaces A workspace can have multiple Projects A Project can have multiple ProjectLists ProjectList can have multiple Tasks Tasks can have multiple updates User | Workspaces (ForeignKey="User") |____Projects (ForeignKey="Workspaces") |____TodoList (ForeignKey="Projects") |____Tasks (ForeignKey="TodoList") |____Updates (ForeignKey="Tasks") So what i want is to get all the data that a User has in a nested json format like this: [ { "workspace_id": "99a961ec-b89e-11e8-96f8-529269fb1459", "workspace_owner": "1", "workspace_title": "Indie Dev Works", "projects": [ { "project_id":"db09cfa0-b89e-11e8-96f8-529269fb1459", "todo_list":[ { "list_id": "9dc64e4c-b89f-11e8-96f8-529269fb1459", "list_name":"Project list -1", "tasks":[ "task_name":"Create HTML docs", "updates":[ { "id":"d5eb660e-b89f-11e8-96f8-529269fb1459", "text":"Creating using PUG" }, { ..... ..... ..... ..... }, ] ] } ] }, { "project_id":".........", .... .... .... .. .. . }, ] } ] So when my User logs in by entering email, i am trying to get all the Workspaces instance and then pass it to the serializers in my views as mentioned below: views.py class InitializeHome(viewsets.ViewSet): def list(self,request): user_email = request.user.email user_instance = utils.getUserInstance(user_email) workspace_instance = WorkSpace.objects.filter(workspace_owner=user_instance) testing_serializer = WorkSpaceSerializer(workspace_instance,many=True) return Response(testing_serializer.data) serializers.py class UpdateSerializer(serializers.ModelSerializer): class Meta: # depth = 2 fields = '__all__' model = Update class TaskSerializer(serializers.ModelSerializer): updates = UpdateSerializer(many=True,read_only=True) class Meta: # depth = 2 fields =…
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/64008694
has answer: http://stackoverflow.com/a/52343200

http://stackoverflow.com/a/52300721
type: Answer
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/52300650
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52300650
downvote count: 0
has body: Probably pandas should refuse to take the mean of a string column. But it doesn't, so what you get is: In [154]: s = pd.Series([15,18,16,14,20,16,15]).astype(str) In [155]: s.sum() Out[155]: '15181614201615' In [156]: float(s.sum()) / len(s) Out[156]: 2168802028802.1428 In [157]: s.mean() Out[157]: 2168802028802.1428 s.min() and s.max() will "work", but it's the lexicographic minimum and maximum, not the numerical, so '111' &lt; '20'. Make your column numerical, whether int or float, whichever you prefer, and remember that .astype doesn't work in-place, so you'll need delay["If Delayed, for how long?"] = delay["If Delayed, for how long?"].astype(int) if you want the column to actually change.

http://stackoverflow.com/a/52410685
answers question: http://stackoverflow.com/q/52377617
has body: You can use the quantize function in the decimal module: &gt;&gt;&gt; import decimal &gt;&gt;&gt; y = decimal.Decimal('78.459') &gt;&gt;&gt; z = decimal.Decimal('.01') &gt;&gt;&gt; y.quantize(z, rounding=decimal.ROUND_DOWN) Decimal('78.45')
score: 0
type: Answer

http://stackoverflow.com/q/52334113
linked to: http://stackoverflow.com/q/39823625
has body: I want to sum the elements of a list that are placed only on an even number position. This is what I have, but it doesn't seam to work. code=input("SVP entrez le code :") r=range(0,11,2) sum=(sum(i) for i in r) print(sum)
type: AnsweredQuestion
score: 2
tagged with: list
upvote count: 2
accepted answer: http://stackoverflow.com/a/52334351
has title: Summing elements of a list that are placed only on an even number position
type: Question
has answer: http://stackoverflow.com/a/52336553
tagged with: sum
possible better answer: http://stackoverflow.com/a/52336553
has comment: http://stackoverflow.com/comment/91615467
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52334351
favorite count: 0
has comment: http://stackoverflow.com/comment/91615454
tagged with: range
tagged with: python

http://stackoverflow.com/comment/91654907
type: Comment
type: QuestionComment
has text: I'll add that as an answer, then, just wasn't sure it will work - I don't have pylint setup, so I could not try it easily.
comment on: http://stackoverflow.com/q/52354591
score: 0

http://stackoverflow.com/a/52350376
type: Answer
has comment: http://stackoverflow.com/comment/91646236
has comment: http://stackoverflow.com/comment/91646340
has comment: http://stackoverflow.com/comment/91646380
has comment: http://stackoverflow.com/comment/91646385
downvote count: 0
score: 1
has body: Users should have an instance of messages, which allows method get. The scetch for code is: class Messages: ... def get() ... class Users: ... messages = Messages(...) allows users = Users() users.messages.get() The bad thing in this API is plural names, which is a bad sign for class. If done from scratch you would rather have classes User and Message, which make more sense. If you have a closer look at GET/POST calls in the API you link provided, you would notice the urls are like UserId/settings, another hint to implement User class, not Users.
answers question: http://stackoverflow.com/q/52350090
has comment: http://stackoverflow.com/comment/91646282
has comment: http://stackoverflow.com/comment/91646270
upvote count: 1
has comment: http://stackoverflow.com/comment/91646301

http://stackoverflow.com/a/52426574
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91796927
accepted answer of: http://stackoverflow.com/q/52426195
type: Answer
answers question: http://stackoverflow.com/q/52426195
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91799574
has comment: http://stackoverflow.com/comment/91798179
has body: Obviously, if you want more than n numbers to add to n, some of those numbers will have to be zero. Thus, you can not pick distinct numbers as the separators as you do with sample. Instead, just use choice to pick any values as separator, including duplicates, add 0 and n as the start and endpoint, and get the differences. def random_sum_to(n, num_terms = None): num_terms = (num_terms or r.randint(2, n)) - 1 a = sorted([r.randrange(n) for _ in range(num_terms)]) return [y-x for x, y in zip([0]+a, a+[n])] This way, a possible result for random_sum_to(200, 288) might look like this: [0, 2, 1, 0, 0, 0, 1, 0, 2, 2, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 2, 0, 0, 2, 0, 2, 1, 0, 1, 0, 0, 1, 0, 1, 0, 2, 0, 0, 1, 0, 1, 0, 2, 0, 0, 1, 4, 0, 1, 2, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 2, 0, 2, 1, 0, 0, 1, 1, 2, 0, 0, 4, 1, 0, 1, 1, 0, 2, 0, 1, 0, 2, 0, 2, 0, 1, 2, 0, 1, 2, 1, 1, 0, 0, 1, 0, 1, 1, 1, 2, 1, 1, 2, 0, 0, 2, 0, 0, 0, 1, 0, 0, 1, 0, 1, 2, 2, 0, 0, 3, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 3, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 2, 1, 0, 0, 1, 1, 1, 0, 0, 2, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 3, 0, 0, 1, 0, 1, 0, 1, 2, 0, 0, 0, 1, 2, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 2, 0, 1, 0, 0, 0, 4, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 3, 1, 0, 2, 0, 0, 1, 0, 1, 2, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 3, 3, 0, 1, 1, 0, 1, 0, 2, 0, 1, 0, 2, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 2]
upvote count: 2

http://stackoverflow.com/comment/91593682
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52322216
has text: You need to include the full error traceback.

http://stackoverflow.com/comment/91659535
has text: Try opening up an interactive python shell, in the same directory you would normally run your bot from, and running `import discord; print(discord.__file__)`. That should give you some idea of where in your computer Python is getting the discord package from.
type: Comment
comment on: http://stackoverflow.com/q/52356064
type: QuestionComment
score: 0

http://stackoverflow.com/q/52285152
has comment: http://stackoverflow.com/comment/91529927
type: Question
has comment: http://stackoverflow.com/comment/91585087
has comment: http://stackoverflow.com/comment/91597569
tagged with: active-directory
has body: I have a code like this: from ldap3 import Server, Connection uri = 'ldaps://ca1.ad.xxx.com:123' bind_user = 'CN=svc_bind_user,OU=Service Accounts,DC=subdomain1,DC=ad,DC=xxx,DC=com' bind_password = 'svc_bind_p4$$' server = Server(uri) conn = Connection(server, bind_user, bind_password) conn.bind() user_filter = 'objectClass=*' user_name_attr = 'sAMAccountName' search_scope = 'SUBTREE' I can successfully search for user1 user1@subdomain1.ad.xxx.com like this username = 'user1' search_base= 'DC=subdomain1,DC=ad,DC=xxx,DC=com' search_filter = "(&amp;({0})({1}={2}))".format( user_filter, user_name_attr, username ) res = conn.search(search_base, search_filter, search_scope) as well as user2 user2@subdomain2.ad.xxx.com like this username = 'user2' search_base= 'DC=subdomain2,DC=ad,DC=xxx,DC=com' search_filter = "(&amp;({0})({1}={2}))".format( user_filter, user_name_attr, username ) res = conn.search(search_base, search_filter, search_scope) As you can see codes above are tailored for each user to look into different search_base : subdomain1 and subdomain2 accordingly I tired to search for both user1 and user2 in a code like this with a higher level search_base= 'DC=ad,DC=xxx,DC=com' : username = 'user1' search_base= 'DC=ad,DC=xxx,DC=com' search_filter = "(&amp;({0})({1}={2}))".format( user_filter, user_name_attr, username ) res = conn.search(search_base, search_filter, search_scope) but the code above doesn't find the user, only returns a list of subdomains So the question is, if I am not doing anything wrong here, is there a way to search within multiple domains, by having a perhaps search_base with special syntax that combines multiple subdomains? I don't want to do multiple searches and also as I mentioned the SUBTREE/higher level serach_base does not seem to work for me either Thanks
has title: Python LDAP3 Search in multiple search_base at once
tagged with: ldap
tagged with: ldap3
downvote count: 0
has comment: http://stackoverflow.com/comment/107159556
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91519217
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/93177945

http://stackoverflow.com/comment/91787355
comment on: http://stackoverflow.com/a/52408118
type: AnswerComment
has text: Strange that it didnt work. I could reproduce the exact same error (except for the chinese translation) and copying the dll fixed it for me.
score: 0
type: Comment

http://stackoverflow.com/a/52381718
upvote count: 1
answers question: http://stackoverflow.com/q/52381397
score: 1
downvote count: 0
has body: I see at least one error in there. The most obvious one (because you got an error), is in splitting. The third comma at the end is causing the string to be split into four elements &gt;&gt;&gt; l = 'a,b,c,' &gt;&gt;&gt; l.split(',') ['a', 'b', 'c', ''] you can work around that by using: x,y,z,_ = value.split(',') the next problem you'll run into is with your loop for value in content: x, y, z = value.split(',') you are only storing the last of your values, since you overwrite them multiple times. The easiest way to work around this is creating three lists and appending into them: x = [] y = [] z = [] for measurement in content: a,b,c,_ = measurement.split(',') x.append(a) y.append(b) z.append(c) This is not the most efficient way, but I think it should be easier to understand. I recommend using it like this: x = [] y = [] z = [] with open('measurements.txt') as file: for line in file: a,b,c,_ = line.split(',') x.append(a) y.append(b) z.append(c)
type: Answer

http://stackoverflow.com/q/52365838
type: Question
has body: I am trying to build a docker image containing Python 2 on my mac (High Sierra). Here is the docker file. (build command: docker build -t integration_test .) FROM python:2 WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . CMD [ "nosetests" ] Here are the contents of the requirements.txt nose pyhive thrift sasl thrift_sasl python-dateutil future six&gt;=1.7.2 When I try to build the docker image, I get the following error. Failed building wheel for sasl Running setup.py clean for sasl Running setup.py bdist_wheel for thrift-sasl: started Running setup.py bdist_wheel for thrift-sasl: finished with status 'done' Stored in directory: /root/.cache/pip/wheels/c8/3a/34/1d82df3d652788fc211c245d51dde857a58e603695ea41d93d Running setup.py bdist_wheel for future: started Running setup.py bdist_wheel for future: finished with status 'done' Stored in directory: /root/.cache/pip/wheels/bf/c9/a3/c538d90ef17cf7823fa51fc701a7a7a910a80f6a405bf15b1a Successfully built pyhive thrift thrift-sasl future Failed to build sasl Installing collected packages: nose, future, six, python-dateutil, pyhive, thrift, sasl, thrift-sasl Running setup.py install for sasl: started Running setup.py install for sasl: finished with status 'error' Complete output from command /usr/local/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-Dd4Z7v/sasl/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-_rw4YI/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/sasl copying sasl/__init__.py -&gt; build/lib.linux-x86_64-2.7/sasl running egg_info writing requirements to sasl.egg-info/requires.txt writing sasl.egg-info/PKG-INFO writing top-level names to sasl.egg-info/top_level.txt writing…
linked to: http://stackoverflow.com/q/48562383
has comment: http://stackoverflow.com/comment/91676641
tagged with: docker
answer count: 2
has comment: http://stackoverflow.com/comment/91676794
has answer: http://stackoverflow.com/a/71975534
favorite count: 0
has comment: http://stackoverflow.com/comment/91676483
score: 6
tagged with: python
tagged with: macos
has comment: http://stackoverflow.com/comment/91676311
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/71975534
tagged with: pip
has answer: http://stackoverflow.com/a/52366692
accepted answer: http://stackoverflow.com/a/52366692
upvote count: 7
downvote count: 1
has title: Unable to build docker image with sasl python module

http://stackoverflow.com/a/52292981
score: 6
has body: Take a look at PEP3120 which changed the default encoding of python source code to be UTF-8 For python 3.x one therefore finds in the docs: If a comment in the first or second line of the Python script matches the regular expression coding[=:]\s*([-\w.]+), this comment is processed as an encoding declaration [...] The recommended forms of an encoding expression are: # -*- coding: &lt;encoding-name&gt; -*- which is recognized also by GNU Emacs, and # vim:fileencoding=&lt;encoding-name&gt; which is recognized by Bram Moolenaar’s VIM. If no encoding declaration is found, the default encoding is UTF-8 The take home message is therefore: python 3.x does not neccessarily need to have utf-8 specified, since it is the default The way the coding line is written is to some degree personal choice (only a recommendation in the docs), it only has to match the regex.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52292669
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/52292669
downvote count: 0

http://stackoverflow.com/comment/91592128
score: 0
type: Comment
has text: Sounds like overkill, no?
comment on: http://stackoverflow.com/a/52322269
type: AnswerComment

http://stackoverflow.com/a/52338451
score: 6
type: AcceptedAnswer
downvote count: 0
has body: I added negatives just in case you may need them but the overall performance wouldn't change drastically without them either. def reverse_digits1(num): if num &lt; 0: neg = True else: neg = False if neg: num *= -1 reversed_num = 0 while num &gt; 0: reversed_num *= 10 reversed_num += num % 10 num = num // 10 if neg: reversed_num *= -1 return reversed_num def reverse_digits2(num): num = str(num)[::-1] if num.endswith('-'): num = '-' + num[:-1] return int(num) from timeit import timeit as _t timeit = lambda x: print(_t(x, globals=globals())) timeit("reverse_digits1(123456789)") timeit("reverse_digits1(-123456789)") timeit("reverse_digits2(123456789)") timeit("reverse_digits2(-123456789)") This result in 5.207313711074936 6.272431325012982 2.453335871448827 3.285427497418125 So other than being more readable* it actually is also faster. As of the information loss, I can't imagine it being possible with your regular integers, and even if it was floats or some other type of number, strings would be more reliable since as a very basic example, 0.1+02 == 0.300000000000001, in strings however you can manipulate them with certain precision. *Keep in mind, code is written to be read by humans.
accepted answer of: http://stackoverflow.com/q/52337899
has comment: http://stackoverflow.com/comment/91624225
has comment: http://stackoverflow.com/comment/91624202
answers question: http://stackoverflow.com/q/52337899
type: Answer
upvote count: 6

http://stackoverflow.com/comment/91589625
comment on: http://stackoverflow.com/q/52320928
has text: It's reasonable, but in my example the template already has all required formatting information. Moving part of the formatting to the variables doesn't improve readability in my opinion. This question is of course a bit nitpicky already as there are plenty of options to solve the actual problem.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52279315
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52279421
has answer: http://stackoverflow.com/a/52279452
accepted answer: http://stackoverflow.com/a/52279452
type: Question
upvote count: 2
tagged with: time-series
answer count: 2
has title: Counting the number of consecutive binary indicators in a time series
has answer: http://stackoverflow.com/a/52279421
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: python
has body: I have a dataframe that uses binary indicators to reflect whether a customer is live during a particular month. If the customer is live, there is a 1, if not there is a 0. The dataframe looks like the below: Customer A B C D E F G H I J 11/30/2015 1 0 1 0 0 1 1 0 0 0 12/31/2015 0 1 0 1 0 1 1 0 0 1 1/31/2016 0 0 0 0 0 1 1 0 0 1 2/29/2016 1 1 1 1 1 1 0 1 1 1 3/31/2016 1 1 0 1 1 0 1 1 0 1 4/30/2016 0 1 1 1 0 1 1 1 0 1 5/31/2016 1 1 1 1 1 1 0 1 0 1 When a customer is live, they get a 1 for the particular month. Similarly, if they are live in the following month (or any month) they get a 1 for that month also. I want to add a column at the end of the dataframe which counts the number of customers live in the month, who were also live in the previous month. I have calculated this in excel using this method but I am not clear on how to go about this in Python. This is the excel formula I used. COUNTIFS(B1:TE1,1,B2:TE2,1) The resulting dataframe would look like this: Customer A B C D E F G H I J Customers_live_consecutive_months 11/30/2015 1 0 1 0 0 1 1 0 0 0 0 12/31/2015 0 1 0 1 0 1 1 0 0 1 2 1/31/2016 0 0 0 0 0 1 1 0 0 1 3 2/29/2016 1 1 1 1 1 1 0 1 1 1 2 3/31/2016 1 1 0 1 1 0 1 1 0 1 6 4/30/2016 0 1 1 1 0 1 1 1 0 1 5 5/31/2016 1 1 1 1 1 1 0 1 0 1 6

http://stackoverflow.com/q/52279041
has comment: http://stackoverflow.com/comment/91506331
has comment: http://stackoverflow.com/comment/91506496
has comment: http://stackoverflow.com/comment/91506934
has title: why there are .dll or .py files
type: UnansweredQuestion
tagged with: python
has body: I always have a question in my mind. When I look at the installation folder of a program, though the software is claimed to be written in Java, there are some dll / py or exe files in it. This is completely weird to me as I used to believe a Java program should only contain .class files or jars. Can someone explain to me what is the reason behind this kind of setting? I have read some tutorials about java native interface and is this the reason why there are dll and exe files?
has comment: http://stackoverflow.com/comment/91506083
answer count: 0
tagged with: java
has comment: http://stackoverflow.com/comment/91506077
type: Question
tagged with: dll
score: 0

http://stackoverflow.com/a/52316596
accepted answer of: http://stackoverflow.com/q/52314968
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52314968
has body: There are a couple of overlapping errors here, and the one is making the other harder to find. The leap-year test has an error in it. It should be if given_year % 4 == 0: if given_year % 100 != 0 or given_year % 400 == 0:. That is, a year is a leap year if it is divisible by 4; but not if it is divisible by 100, unless it is also divisible by 400. The result of this error is that your original if-test is only True every 400th year and so the loop will run until it has tested 6,000 years. I suspect you were interrupting the program before this happened, so you didn't see the problem inside the if-test. This won't work: list_of_leap_years[i] = given_year. If your code had ever reached that point you would have got the error list assignment index out of range. That is because you can't extend a list simply by assigning elements that aren't there. If you want to add new values to the end of a list, use append: list_of_leap_years.append(given_year). The function returns list_of_leap_years but doesn't define it. The function should start by creating it as an empty list. Fixing these problems, the function will look like this: def find_leap_years(given_year): list_of_leap_years = [] count=0 while count &lt; 15: if given_year % 4 == 0: if given_year % 100 != 0 or given_year % 400 == 0: list_of_leap_years.append(given_year) count += 1 given_year += 1 return list_of_leap_years I've taken out the list index i because you don't need it to keep track of how many elements the leap year list has. If you need to discover it, use len(list_of_leap_years).
has comment: http://stackoverflow.com/comment/91581442

http://stackoverflow.com/q/52336438
linked to: http://stackoverflow.com/q/44144584
tagged with: redis
type: Question
tagged with: python
upvote count: 11
answer count: 2
tagged with: celery
has body: On a Windows 10 system running Python 3.6, when trying to use multiprocessing.Process to create a new rq worker, multiprocessing.Process(target=Worker(qs).work, kwargs={'burst': True}).start() we encounter the error TypeError: can't pickle _thread.lock objects and OSError: [WinError 87] The parameter is incorrect rq.SimpleWorker was used instead of rq.Worker because Windows does not support the fork function used by rq.Worker. Question: What is causing this error? How can we solve it? from rq import SimpleWorker, Connection def needMoreWorkers(): return True if __name__ == '__main__': qs = sys.argv[1:] or ['default'] with Connection(connection=my_redis_conn): if needMoreWorkers(): multiprocessing.Process(target=SimpleWorker(qs).work, kwargs={'burst': True}).start() Error Traceback Traceback (most recent call last): File "WorkerFactory.py", line 53, in &lt;module&gt; main(qs) File "WorkerFactory.py", line 45, in main multiprocessing.Process(target=SimpleWorker(qs)).start() File "C:\Users\x\AppData\Local\Continuum\anaconda3\envs\test\lib\multiprocessing\process.py", line 105, in start self._popen = self._Popen(self) File "C:\Users\x\AppData\Local\Continuum\anaconda3\envs\test\lib\multiprocessing\context.py", line 223, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "C:\Users\x\AppData\Local\Continuum\anaconda3\envs\test\lib\multiprocessing\context.py", line 322, in _Popen return Popen(process_obj) File "C:\Users\x\AppData\Local\Continuum\anaconda3\envs\test\lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__ reduction.dump(process_obj, to_child) File "C:\Users\x\AppData\Local\Continuum\anaconda3\envs\test\lib\multiprocessing\reduction.py", line 60, in dump ForkingPickler(file, protocol).dump(obj) TypeError: can't pickle _thread.lock objects (test) C:\Code\test\source&gt;Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Users\x\AppData\Local\Continuum\anaconda3\envs\test\lib\multipr…
has title: Multiprocessing, Python3, Windows: TypeError: can't pickle _thread.lock objects
linked to: http://stackoverflow.com/q/2121874
score: 11
tagged with: python-multiprocessing
has answer: http://stackoverflow.com/a/64715238
downvote count: 0
has comment: http://stackoverflow.com/comment/126780661
type: UnansweredQuestion
favorite count: 0
has answer: http://stackoverflow.com/a/73473435
tagged with: python-3.x

http://stackoverflow.com/comment/91779818
comment on: http://stackoverflow.com/a/52418047
score: 0
type: Comment
has text: I changed the folder name to use-this but it still error. As I said the image should be found under test1 which are in use-this
type: AnswerComment

http://stackoverflow.com/comment/91775404
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52415926
has text: Hey, I am not getting 3rd message. Just FYI, the between colon separators might be a few characters and contain alphanumeric. EDIT: sorry mixed up, did not know you were using the function to append ':', it works now!
score: 0

http://stackoverflow.com/comment/91744554
has text: this is a nice fix, didnt think of it but the solution posted by jezrael is simple and does what i need. thx!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52400032
score: 1

http://stackoverflow.com/comment/91767862
score: 0
comment on: http://stackoverflow.com/a/52376427
type: AnswerComment
has text: take a look at `FBXExportSplitAnimationIntoTakes` in the FBX exporter docs. You'll have the same syntax issues in (flags turning into quoted arguments) but you should be able to set up takes that way.
type: Comment

http://stackoverflow.com/comment/91685516
has text: @Deep Read the answers anyway, they still show how to efficiently check if the current element is a duplicate or not, then it's easy to change the actual action you do according to that condition
comment on: http://stackoverflow.com/q/52370310
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52354596
answers question: http://stackoverflow.com/q/52354124
has comment: http://stackoverflow.com/comment/91654080
type: Answer
has comment: http://stackoverflow.com/comment/91653974
has comment: http://stackoverflow.com/comment/91653947
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91653923
has body: I also assume that you wish to: (a) Combine consecutive appointments (i.e. one starting immediately after the previous one ends) (b) Format these in the manner shown above (c) Group these by day in flattened lists. If so, you can solve this problem using the following approach: (a) Make a helper function that transforms your day, hour and minute variables into minutes: def get_minute_val(day_val,hour_val,min_val): return (24*60*day_val)+(60*hour_val)+min_val (b) Make a function that takes two appointments, and either combines them to one if they are consecutive, or returns them uncombined if they are not def combine_if_consec(first,second): #Check whether appointments are consecutive if( get_minute_val(first[0],first[3],first[4]) + 1 == get_minute_val(second[0],second[1],second[2])): #If so, return list containing combined appointment return [[first[0],first[1],first[2],second[3],second[4]]] else: #Else return uncombined appointments return [first,second] (c) Iteratively call this on every appointment in the list, comparing vs. the most recently added appointment. I have a slightly hacky method for dealing with the first appointment. def combine_all_appointments(app_list): #Add first appointment to app list output_list = [test[0]] #Loop through remaining appointments for next_app in app_list[1:]: #Remove most recent appointment to output list prev_app = output_list.pop() #Add either 2 combined appointments, or one single appointment to outputlist output_list += combine_if_overlap(prev_app,next_app) return output_list (d) Make a function that does the formatting you want def format_appointments(app_list): return [[x[0],'%d:%02d' % (x[1],x[2]),'%d:%02d' %(x[3],x[4])] for x in app_list] (e) and a separate one to group appointments by days, and flatten by day. def group_by_day(app_list): output = {} #Loop through appointments for app in app_list: #Create new entry if day not yet in output dict if app[0] not in output: output[app[0]] = app[1:] #Add appointment values to …
has comment: http://stackoverflow.com/comment/91654128
upvote count: 1

http://stackoverflow.com/comment/91652617
type: QuestionComment
comment on: http://stackoverflow.com/q/52344889
has text: Because it offers a much easier way of installing packages with complex dependencies like NumPy
score: 0
type: Comment

http://stackoverflow.com/comment/91721002
score: 0
type: Comment
type: AnswerComment
has text: listen addresses was `listen_addresses='*'` by default. And I tried answers https://dba.stackexchange.com/questions/83984/connect-to-postgresql-server-fatal-no-pg-hba-conf-entry-for-host refers but never fixed the error. I think I was successful in configuring db when I didn't install PostgreSQL application.
comment on: http://stackoverflow.com/a/52387747

http://stackoverflow.com/q/52295134
type: UnansweredQuestion
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/52295202
type: Question
has answer: http://stackoverflow.com/a/52295412
answer count: 2
downvote count: 0
has title: How to remove brackets '[]' and comma from my output result?
has body: My Python program is: def remove(duplicate): final_list=[] for num in duplicate: if num not in final_list: final_list.append(num) return final_list duplicate=input() print(remove(duplicate),end="")
favorite count: 0
tagged with: python-3.x
upvote count: 2

http://stackoverflow.com/comment/91504692
comment on: http://stackoverflow.com/q/52278080
score: 0
type: Comment
type: QuestionComment
has text: The pyspark implementation is just a wrapper on the Java version. The [Java docs](https://spark.apache.org/docs/1.4.0/api/java/org/apache/spark/mllib/tree/RandomForest.html) indicate that `featureSubsetStrategy` is a `String`.

http://stackoverflow.com/a/52337379
has comment: http://stackoverflow.com/comment/91626021
score: 2
has comment: http://stackoverflow.com/comment/91626077
has comment: http://stackoverflow.com/comment/91625785
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52336811
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52336811
has body: Let's see with ResNet50 as an example. from keras.models import Model from keras.layers import Input, Dense from keras.applications.resnet50 import ResNet50 res = ResNet50() res.summary() #.... #Total params: 25,636,712 #Trainable params: 25,583,592 #Non-trainable params: 53,120 Resnet model has a lot of parameters to train. Let's put this as a layer of a model. x = Input((224,224,3)) y = res(x) y = Dense(10)(y) model = Model(x, y) model.summary() #..... #Total params: 25,646,722 #Trainable params: 25,593,602 #Non-trainable params: 53,120 Freeze the layers of resnet. for layer in res.layers: layer.trainable = False res.summary() # .... #Total params: 25,636,712 #Trainable params: 0 #Non-trainable params: 25,636,712 This reflects to the model that use resnet as well. model.summary() #..... #Total params: 25,646,722 #Trainable params: 10,010 #Non-trainable params: 25,636,712 So, freezing layers of inner models should reflect to the outer model. EDIT If you compile the model before freezing your model, you need to compile it again.

http://stackoverflow.com/q/52286085
tagged with: loops
type: Question
has answer: http://stackoverflow.com/a/52286134
answer count: 2
tagged with: variables
has comment: http://stackoverflow.com/comment/91520417
score: 0
has body: I have a lot of variables, df_foo_1_100 = 4 df_foo_1_1000 = 5 ... df_foo_1_1000000 = 100 df_foo_2_100 = 9 df_foo_2_1000 = 10 df_foo_2_1000000 = -100 df_foo_4_100 = -1000 and have empty list, temp=[] How can this empty list hold all variables using loop? This is my code, index = [1,2,4,8,16,32,64] index2 = [100, 1000, 10000, 100000, 1000000] for i in index: for j in index2: temp.append(df_foo_{0}_{1}.format(i, j)) but didn't get any luck. How can I fix this loop, so that I can have the output, [df_1_100, df_1_1000... ] (Inside of list is not string, but name of variables) ========== edit ========== dict is fine as well. the result dict will be like, {df_foo_1_100: 4, df_foo_1_1000: 5 ...} Thanks in advance!
has title: python append list incrementing variable name
accepted answer: http://stackoverflow.com/a/52286134
has answer: http://stackoverflow.com/a/52286212
tagged with: python
has comment: http://stackoverflow.com/comment/91520461
possible better answer: http://stackoverflow.com/a/52286212
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91520420

http://stackoverflow.com/comment/91516012
comment on: http://stackoverflow.com/a/52283597
score: 0
type: Comment
has text: Hmm, I've just updated my packages entry to be ["packagename", "packagename.module1", ...] but I still can't seem to import, whether it's "from packagename import module1", "import packagename *" etc. I've also tried "from module1 import Class1" but to no avail. If I go to site-package directory (test project) and find the dir "packagename", I can see the __init__.py containing "name='packagename'" and directories containing the four modules, which in turn have all of their code. The __init__.py in each module has imports for each class in the module (from packagename import Class1...).
type: AnswerComment

http://stackoverflow.com/comment/91624771
type: Comment
has text: use a `virtualenvironment`, and `pip install pdfminer`
comment on: http://stackoverflow.com/q/52303980
score: 0
type: QuestionComment

http://stackoverflow.com/a/59944949
upvote count: 22
downvote count: 0
score: 22
has body: Using pytorch 1.2 or 1.4 arjoonn's answer did not work for me. Instead of torch.stack I have used torch.cat with pytorch 1.2 and 1.4: &gt;&gt;&gt; import torch &gt;&gt;&gt; a = torch.randn([2, 3, 4]) &gt;&gt;&gt; b = torch.randn([2, 3]) &gt;&gt;&gt; b = b.unsqueeze(dim=2) &gt;&gt;&gt; b.shape torch.Size([2, 3, 1]) &gt;&gt;&gt; torch.cat([a, b], dim=2).shape torch.Size([2, 3, 5]) If you want to use torch.stack the dimensions of the tensors have to be the same: &gt;&gt;&gt; a = torch.randn([2, 3, 4]) &gt;&gt;&gt; b = torch.randn([2, 3, 4]) &gt;&gt;&gt; torch.stack([a, b]).shape torch.Size([2, 2, 3, 4]) Here is another example: &gt;&gt;&gt; t = torch.tensor([1, 1, 2]) &gt;&gt;&gt; stacked = torch.stack([t, t, t], dim=0) &gt;&gt;&gt; t.shape, stacked.shape, stacked (torch.Size([3]), torch.Size([3, 3]), tensor([[1, 1, 2], [1, 1, 2], [1, 1, 2]])) With stack you have the dim parameter which lets you specify on which dimension you stack the tensors with equal dimensions.
answers question: http://stackoverflow.com/q/52288635
type: Answer

http://stackoverflow.com/q/52282334
type: Question
score: 0
answer count: 1
tagged with: tk-toolkit
has answer: http://stackoverflow.com/a/52283437
linked to: http://stackoverflow.com/q/16439936
has body: I am using Tkinter's tkFileDialog package in some python code. The following command prompts the user to select a file with the ability to change the filetype between "csv" or "any". tkFileDialog.askopenfilename(filetypes=[('csv files', '*.csv'), ('all files', '*.*')],) On Windows 10, this works as expected, but on OSX10.12.6, the filetype dropdown isn't available. It only allows selection of csv files, with no option to change the file type. How can I get this to work properly? My only idea is that tcl 8.6 on OSX is behaving differently than tcl 8.5 on windows.
accepted answer: http://stackoverflow.com/a/52283437
has title: TkFileDialog does not show File Extension options on OSX10.12.6
tagged with: tcl
type: AnsweredQuestion
tagged with: python
tagged with: tkinter

http://stackoverflow.com/comment/91771174
comment on: http://stackoverflow.com/q/52413563
has text: Read it in as a string. Then it would be almost completely impossible to work with. The fact that JSON translates to python lists and dicts so easily is a _blessing_
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52396066
type: Question
type: AnsweredQuestion
tagged with: urllib
answer count: 1
has answer: http://stackoverflow.com/a/52396093
score: 0
tagged with: python-3.7
tagged with: python
has title: Optimizing speed of python code that tests results of an API
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52396093
tagged with: multithreading
has body: I'm trying to test a publicly available web page that takes a GET request and returns a different JSON file depending on the GET argument. The API looks like https://www.example.com/api/page?type=check&amp;code=[Insert string here] I made a program to check the results of all possible 4-letter strings on this API. My code looks something like this (with the actual URL replaced): import time, urllib.request for a in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": for b in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": for d in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": a,b,c,d = "J","A","K","E" test = urllib.request.urlopen("https://www.example.com/api/page?type=check&amp;code=" + a + b + c + d).read() if test != b'{"result":null}': print(a + b + c + d) f = open("codes", "a") f.write(a + b + c + d + ",") f.close() This code is completely functional and works as expected. However, there is a problem. Because the program can't progress until it receives a responses, this method is very slow. If this ping time is 100ms for the API, then it will take 100ms for each check. When I modified this code so that it could test half of the results in one instance, and half in another, I noticed that the speed doubled. Because of this, I'm led to believe that the ping time of the site is the limiting factor in this script. What I want to do is be able to is basically check each code, and then immediately check the next one without waiting for a response. That would be the equivalent of opening up the page a few thousand times in my browser. It could load many tabs at the same time, since each page is less than a kilobyte. I looked into using threading to do this, but I'm not sure if its relevant or helpful.

http://stackoverflow.com/a/52291185
has body: Fixed! It reshaped the matrix but did not save the changes. It should be: image_matrix = image_matrix.reshape(image_height, image_width, 3)
score: 0
answers question: http://stackoverflow.com/q/52291098
type: Answer

http://stackoverflow.com/q/52338187
has title: my function makes it where i cannot do anything unless i restart the program
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91624025
has comment: http://stackoverflow.com/comment/91623790
has body: from tkinter import * import RPi.GPIO as GPIO import time import sys DHTPIN = 14 GPIO.setmode(GPIO.BCM) GPIO.setup(21, GPIO.OUT) GPIO.output(21, GPIO.LOW) MAX_UNCHANGE_COUNT = 100 STATE_INIT_PULL_DOWN = 1 STATE_INIT_PULL_UP = 2 STATE_DATA_FIRST_PULL_DOWN = 3 STATE_DATA_PULL_UP = 4 STATE_DATA_PULL_DOWN = 5 GPIO.setmode(GPIO.BCM) GPIO.setup(21, GPIO.OUT) GPIO.output(21, GPIO.LOW) root = Tkinter.Tk() root.geometry("700x700") root.title("House Control") cur_temp = 70 counter = Tkinter.IntVar() def toggle29(): if GPIO.input(21): GPIO.output(21, GPIO.LOW) toggleButton29["text"] = "Turn BLUE 29 On" else: GPIO.output(21, GPIO.HIGH) toggleButton29["text"] = "Turn BLUE 29 Off" def system_state(): if on_btn.config('text')[-1] == 'On': on_btn.config(text='Off') else: on_btn.config(text='On') def system_ac_state(): if ac_btn.config('text')[-1] == 'Cooling': ac_btn.config(text='Heating') ac_heating() main() else: ac_btn.config(text='Cooling') ac_cooling() def ac_heating(): print("heating") pass def ac_cooling(): print("cooling") pass def cool_temp(): print ("cooling") def heat_temp(): print ("heating") def onClick1(event=None): counter.set(counter.get() - 1) def onClick(event=None): counter.set(counter.get() + 1) def toggle0(): if GPIO.input(17): GPIO.output(17, GPIO.LOW) toggleButton0["text"] = "Turn RED 0 On" else: GPIO.output(17, GPIO.HIGH) toggleButton0["text"] = "Turn RED 0 Off" def read_dht11_dat(): GPIO.setup(DHTPIN, GPIO.OUT) GPIO.output(DHTPIN, GPIO.HIGH) time.sleep(0.05) GPIO.output(DHTPIN, GPIO.LOW) time.sleep(0.02) GPIO.setup(DHTPIN, GPIO.IN, GPIO.PUD_UP) unchanged_count = 0 last = -1 data = [] while True: current = GPIO.input(DHTPIN) data.append(current) if last != current: unchanged_count = 0 last = current else: unchanged_count += 1 if unchanged_count &gt; MAX_UNCHANGE_COUNT: break state = STATE_INIT_PULL_DOWN lengths = [] current_length = 0 for current in data: current_length += 1 if state == STATE_INIT_PULL_DOWN: if current == GPIO.LOW: state = STATE_INIT_PULL_UP…
has comment: http://stackoverflow.com/comment/91623819
has comment: http://stackoverflow.com/comment/91623644
tagged with: tkinter
answer count: 0
has comment: http://stackoverflow.com/comment/91623778
tagged with: gpio
has comment: http://stackoverflow.com/comment/91623672
has comment: http://stackoverflow.com/comment/91623653
has comment: http://stackoverflow.com/comment/91623893
type: Question
has comment: http://stackoverflow.com/comment/91623879
has comment: http://stackoverflow.com/comment/91623966
score: 0
has comment: http://stackoverflow.com/comment/91623814
has comment: http://stackoverflow.com/comment/91623635

http://stackoverflow.com/q/52379689
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52379714
upvote count: 1
type: Question
tagged with: pandas
answer count: 1
has body: I have to check for blank on multiple column. How can I do that effectively. I am checking for blank on each row of a single column like below - for item, frame in df['Column_1'].notnull().iteritems(): if(frame != False): print item , frame I need to have a dataframe where rows on column_1 , column_2 and column_3 are not blank.
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52379714
favorite count: 0
has title: Checking for multiple blank fields in a row in pandas
tagged with: python

http://stackoverflow.com/comment/91616423
comment on: http://stackoverflow.com/q/52324816
has text: @MikhailBurshteyn! You're a hero! Thanks.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/123700594
has text: The question is still relevant. See for example the recent [Is there a way to serialize a class such that it can be unserialized independent of its original script?](https://stackoverflow.com/questions/69859147/is-there-a-way-to-serialize-a-class-such-that-it-can-be-unserialized-independent)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52410860
type: Comment

http://stackoverflow.com/q/52365811
has answer: http://stackoverflow.com/a/52365950
score: -1
has body: print("Enter the width") a=int(input()) count=0 for i in range(1,a+1): print("*"*i) if i==a: count=1 if count==1: i-=2 I want a pattern like this * ** *** **** ***** **** *** ** * when user inputs 5 as the width. But the output I am getting is just * ** *** **** ***** What am i doing wrong?
answer count: 2
tagged with: for-loop
has comment: http://stackoverflow.com/comment/91675860
has title: Python: For loop pattern
has comment: http://stackoverflow.com/comment/91676048
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52366341
upvote count: 2
downvote count: 3
tagged with: loops
type: Question

http://stackoverflow.com/a/52294623
has comment: http://stackoverflow.com/comment/91578880
answers question: http://stackoverflow.com/q/52291863
score: 1
accepted answer of: http://stackoverflow.com/q/52291863
upvote count: 1
type: AcceptedAnswer
has body: Assuming that the problem is with the line: list = json.loads(msg.payload) in the on_message() callback and the msg.payload is: $GPRP,7F82854A6A62,C3D7EDB7EF28,-65,0201061AFF4C0002158A174208F78D495E8FDA176A3FC0F34D00160019BD Then is will fail because the payload is not a JSON object. json.loads() will have not idea what do with it. It's a basic CSV string, you should be able to use the split() function to break it up into it's components and then you'll have to interpret each component according to what ever the spec is.
type: Answer
has comment: http://stackoverflow.com/comment/91579545
downvote count: 0

http://stackoverflow.com/comment/91733095
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52393499
type: AnswerComment
has text: @Jean-FrançoisFabre to support words of different length, I would use `len(word) == len(w) and sum(a!=b for a,b in zip(word,w)) == 1`. The `and` shortcircuiting might even make it faster if some words have different length

http://stackoverflow.com/comment/91621257
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52333769
score: 0
has text: Curious, doesn't my answer do what you need or at least show you the path forward? What you are trying to do is relatively straightforward. Are you uncomfortable programming in Python? You can do all of this from bash using jq. Please let us know what you want and what language you want it in.

http://stackoverflow.com/comment/91793839
score: 1
has text: Most likely you need to put the line that controls the fn increase under one of the if conditions
type: QuestionComment
comment on: http://stackoverflow.com/q/52425055
type: Comment

http://stackoverflow.com/comment/105095745
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52315164
type: AnswerComment
has text: In addition to setting the PROJ_LIB var, I had to downgrade pyproj to 1.9.6 for it to work, otherwise the epsg file was missing.

http://stackoverflow.com/a/52585008
answers question: http://stackoverflow.com/q/52424172
score: 0
type: AcceptedAnswer
type: Answer
has body: It was a bug in TensorFlow version 1.09. Moving to 1.10 fixed it
accepted answer of: http://stackoverflow.com/q/52424172

http://stackoverflow.com/comment/91674182
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52335195
score: 0
has text: @MarkSetchell unfortunately, that didn't work

http://stackoverflow.com/q/52347763
tagged with: pytest
tagged with: sqlalchemy
has title: Flask pytest testing database
score: 0
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
has comment: http://stackoverflow.com/comment/91644837
has comment: http://stackoverflow.com/comment/91648787
tagged with: python
has body: I am trying to write some test for my application. I can manage to test URLs which does not contain anything related to db. @pytest.fixture def client(): """ Load pytest fixture. :return: test_client() """ # yield application.test_client() db_fd, application.config['DATABASE'] = tempfile.mkstemp() db.create_all() application.config['TESTING'] = True client = application.test_client() yield client os.unlink(application.config['DATABASE']) my test file: def test_membership_register(client): """Test entry point of website.""" rv = client.get('/register') new_user = User( username='test_user_1', email='test_email@test1.com', password='test1_Password', ) db.session.add(new_user) db.session.commit() assert 200 == rv.status_code ERROR: E sqlalchemy.exc.InvalidRequestError: Table 'membership_user' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.
answer count: 0
type: UnansweredQuestion
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/comment/91596164
type: QuestionComment
comment on: http://stackoverflow.com/q/52324538
has text: That said, your approach seems way over the top for an extra credit project. I'd be very surprised if you get all of that to work. Note that a CNN to detect the car within the picture will require lots and lots of training data, meaning you'll be sitting and manually drawing car outlines full-time for weeks. :)
score: 0
type: Comment

http://stackoverflow.com/q/52408841
tagged with: subprocess
answer count: 0
has comment: http://stackoverflow.com/comment/91772314
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91800849
upvote count: 1
has title: python subprocess to capture the stdin and stdout into a variable
has comment: http://stackoverflow.com/comment/91764480
type: Question
has body: Please note: I have a follow up question with reference to updated code here .. Below is Just the one peice of code which i'm looking forward to trim and understand how to do it better .. import subprocess cmd = "rsync -e 'ssh -o StrictHostKeyChecking=no' -auPz --exclude %s %s@%s:%s %s/"%(args.exclude,rsync_user,host,args.source,dest_dir) cmd_content = cmd p = subprocess.Popen(cmd,shell=True) p.wait() print("DONE") return cmd_content + " Rsync process completed." What i'm looking forward to capture the stdout &amp; stderr from my script to be captured into a variable so, i can use and send it as an e-mail attachment. So, refactoring the above piece here i'm importing Popen and PIPE explicitly, However,i have used p.communicate() as i see Popen.communicate() interacts with process and Send data to stdin, reads the data from stdout and stderr, until end-of-file is reached, it also waits for the process to terminate. from subprocess import Popen, PIPE cmd = "rsync -e 'ssh -o StrictHostKeyChecking=no' -auPz --exclude %s %s@%s:%s %s/"%(args.exclude,rsync_user,host,args.source,dest_dir) cmd_content = cmd p = Popen(cmd,stdout=PIPE,shell=True) p.communicate() print("DONE") return cmd_content + " Rsync process completed." I see Python 2.7 onwards it also supports subprocess.check_output() So, we can avoid using Popen object directly and use subprocess.check_output() function to store output of a command in a string as follows but my doubt will it take in my case as i'm using cmd variable to pass as shell=True. &gt;&gt;&gt; from subprocess import check_output &gt;&gt;&gt; out = check_output(cmd) I have looked around the subprocess examples and question around the web and SO but did not get the required information.
has comment: http://stackoverflow.com/comment/91761676
has comment: http://stackoverflow.com/comment/91761737
has comment: http://stackoverflow.com/comment/91763554
tagged with: popen
tagged with: pipe
score: 1
tagged with: python-3.6
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91763510
has comment: http://stackoverflow.com/comment/91763377
has comment: http://stackoverflow.com/comment/91764251
tagged with: python
linked to: http://stackoverflow.com/q/52369810
has comment: http://stackoverflow.com/comment/91764328

http://stackoverflow.com/a/52430084
downvote count: 0
score: 1
has body: First, you're missing a global statement (as you wish to change the global running) and have incorrect == vs. = syntax: def check(): global running if running: if FourInRow: running = False else: print("A") window.after(100, check) Second, you don't need threading as window.after(...) will keep this code repeating as long as running is True and FourInRow isn't True. If you need it to run beyond that, outdent the window.after(...) statement as much as needed. You can initiate this timed event by calling check() at the top level of your code, just before you turn over control to the tkinter event loop.
answers question: http://stackoverflow.com/q/52421142
upvote count: 1
type: Answer

http://stackoverflow.com/comment/91720364
score: 0
comment on: http://stackoverflow.com/q/52372134
type: Comment
type: QuestionComment
has text: Ok, I edited the code so you can copy and paste it. The first section is for Test.py and the second is for Test2.py. Tested and it still has the same issue. Thanks for the help

http://stackoverflow.com/q/52354171
has body: I've a system that i need to use a graph to solve this function. RLC Series - ODE equation I'm trying to use tf.contrib.integrate.odeint(), however, this function can only get first order ODE, so I divided in two Differential equations. Here is what i did: import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import math as mat graph = tf.Graph() with graph.as_default(): R = tf.constant(100.) L = tf.constant(0.002) C = tf.constant(0.000005) E = tf.constant(10.) ''' Inital EDO: dˆ2(vc)/dtˆ2 + R/L * dvc/dt + vc/LC = E/LC dvc/dt=z dvz/dt = (E-vc)/LC - R*z/L ''' #dvz/dt = (E-vc)/LC - R*z/L EDO0 = lambda z, t: (E-vc)/(L*C) - R/L * z #dvc/dt=z EDO1 = lambda vc, t: z #initial value EDO1_init = constant_op.constant(1.0, dtype=dtypes.float64) t = np.linspace(0.0, 1.0, 11) EDO1_solved = tf.contrib.integrate.odeint(EDO0, 0.5, t) with tf.Session() as sess: y_solved = sess.run(EDO1_solved) print(y_solved) tf.summary.FileWriter('/tmp/logs', tf.get_default_graph()).close() But i'm having some problems with the equations The main problem that i couldn't find the solution is that i must use tensorflow package.
upvote count: 1
downvote count: 1
tagged with: tensorflow
tagged with: ode
type: Question
has answer: http://stackoverflow.com/a/52396145
has comment: http://stackoverflow.com/comment/91656868
score: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91657044
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/19779217
tagged with: python
has title: Tensorflow Odeint

http://stackoverflow.com/q/52342233
type: Question
has answer: http://stackoverflow.com/a/52342471
tagged with: typeerror
answer count: 2
has body: I have ran into a problem with a project I'm working on. I've found where in the code this problem is happening, and put it in an isolated, simple environment, and the error persists. Here's the code: def parse(input_var): input_var = input_var.split("[METHOD]") if(len(input_var)&gt;1): input_var[0] = input_var[0].replace("using ","exec(parse(") input_var[0] = input_var[0].replace(";","))") input_var = input_var[0]+input_var[1] else: input_var=input_var[0] exec(input_var) foo=""" using bar; [METHOD] print('Passed foo!') """ bar = """ print('Passed bar!') """ parse(foo) And here is the output from running the code: Passed bar! Traceback (most recent call last): File "python", line 22, in &lt;module&gt; File "python", line 9, in parse File "&lt;string&gt;", line 2, in &lt;module&gt; TypeError: exec() arg 1 must be a string, bytes or code object The "bar" piece of code is causing the problem, even though it obviously is a string. The thing that's so rotten about this is that it never runs the second half of the "foo" code, which in my other program that uses this code, is kind of necessary.
has comment: http://stackoverflow.com/comment/91631008
downvote count: 0
tagged with: exec
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: (Python 3.X) Python exec() function throws TypeError for no reason
score: 1
has answer: http://stackoverflow.com/a/52342465

http://stackoverflow.com/a/52392783
upvote count: 6
has comment: http://stackoverflow.com/comment/91731578
has body: You need to melt (convert to long format) the DataFrame first: data = df.melt(id_vars=['Categories'], var_name='dataset', value_name='values') print(data) Prints: Categories dataset values 0 A data1 2.0 1 A data2 4.0 2 C data1 4.0 3 C data2 5.0 4 B data1 5.0 5 B data2 4.0 6 A data1 10.0 7 A data2 4.2 8 B data1 9.0 9 B data2 3.0 10 C data1 3.0 11 C data2 3.0 Now you just have to use dataset as the hue. Since the plot is quite busy I moved the legend outside it. sns.boxplot(data=data, x='Categories', y='values', hue='dataset') plt.legend(title='dataset', loc='upper left', bbox_to_anchor=(1, 1)) Edit by OP: I implemented this in a function such that it makes the plot with as many columns as desired in an ax and returns it. def box_plot_columns(df,categories_column,list_of_columns,legend_title,y_axis_title,**boxplotkwargs): columns = [categories_column] + list_of_columns newdf = df[columns].copy() data = newdf.melt(id_vars=[categories_column], var_name=legend_title, value_name=y_axis_title) return sns.boxplot(data=data, x=categories_column, y=y_axis_title, hue=legend_title, **boxplotkwargs) Usage Example: fig, ax = plt.subplots(1,1) ax = box_plot_columns(Data,"Categories",["data1","data2"],"dataset","values",ax=ax) ax.set_title("My Plot") plt.show()
has comment: http://stackoverflow.com/comment/91730904
downvote count: 0
answers question: http://stackoverflow.com/q/52392438
accepted answer of: http://stackoverflow.com/q/52392438
type: AcceptedAnswer
type: Answer
score: 6

http://stackoverflow.com/comment/91546286
has text: Possibly. He mentions that his range spans 20 years, so I used that as the index, but he'd need to clarify what the index is supposed to be.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52299133
score: 1

specifications
type: Tag
tag name: specifications
tags question: http://stackoverflow.com/q/52275634

http://stackoverflow.com/comment/91664084
score: 0
type: Comment
type: QuestionComment
has text: Possible dupe of https://stackoverflow.com/questions/1093322/how-do-i-check-what-version-of-python-is-running-my-script
comment on: http://stackoverflow.com/q/52359805

http://stackoverflow.com/comment/91705871
type: AnswerComment
type: Comment
has text: Is it worth mentioning that since the square root is monotonic we can use the einsum directly and not bother with `np.sqrt`?
score: 1
comment on: http://stackoverflow.com/a/52366706

testing
tags question: http://stackoverflow.com/q/52384833
tags question: http://stackoverflow.com/q/52403961
tag name: testing
tags question: http://stackoverflow.com/q/52337611
tags question: http://stackoverflow.com/q/52353962
tags question: http://stackoverflow.com/q/52389183
type: Tag
tags question: http://stackoverflow.com/q/52319116
tags question: http://stackoverflow.com/q/52381301
tags question: http://stackoverflow.com/q/52317352
tags question: http://stackoverflow.com/q/52365106
tags question: http://stackoverflow.com/q/52330369
tags question: http://stackoverflow.com/q/52287624

http://stackoverflow.com/comment/91502077
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52276973
has text: `pandas` has a very flexible file reader [`pd.read_table`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_table.html). In this case, you can probably get by with `df = pd.read_table('birth_life_data.txt', sep = '\s', engine='python')`

http://stackoverflow.com/q/52344137
has comment: http://stackoverflow.com/comment/91634442
has body: Below is an iterator that given a start and a stop values it yields integers incrementing by one: class Iterator: def __init__(self, start, stop): self.start = start self.stop = stop self._start = self.start def __iter__(self): return self def __next__(self): self.current = self._start if self.current &gt;= self.stop: raise StopIteration self._start += 1 return self.current I see the above version used by everyone. Woudln't the following version be more readable? It also avoids the use of the if conditional if that's a good thing. def __next__(self): self.current = self._start while self.current &lt; self.stop: self._start += 1 return self.current raise StopIteration
answer count: 0
has comment: http://stackoverflow.com/comment/91634227
type: UnansweredQuestion
tagged with: python
tagged with: if-statement
type: Question
tagged with: iterator
has title: What's the correct way to define a __next__ iterator method?
score: 0
tagged with: while-loop

http://stackoverflow.com/comment/91778793
score: 0
comment on: http://stackoverflow.com/a/52417803
type: Comment
has text: but if the line contains `line = 'AirPortFamily-1425.9` ,it should not match it...it should only match the lines that contain `:`
type: AnswerComment

http://stackoverflow.com/comment/91661662
comment on: http://stackoverflow.com/q/52358457
has text: @AzatIbrakov I edited the question to try and clarify it better, sorry I'm rather new to this community I just started working with python this semester of college, I'm using it to do astrophysical research. Anyways, I included the code that has brought me up to the point I'm at, I've attempted a couple of different ways at writing the file, if I type ascii.write(Pressure_pa,sys.stdout) it will output just the data in that column, which is the same for the other two columns. I tried writing them all together, but I get an error message: unhashable text: Column
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52342627
tagged with: python
score: -2
has body: I have a very huge data frame with me. I have also a small data frame with me. Both of those data frames will have same columns. The small data frame will have some rows that are already present in the big data frame. I want to append the small data frame to big one such that there will be no duplicates in the big data frame. I can append simply and then remove the duplicates. But this will lead to wastage of memory to keep the duplicated data frame in the memory. Is there any other method that can be used efficiently to solve this.?
downvote count: 2
has answer: http://stackoverflow.com/a/52342837
possible better answer: http://stackoverflow.com/a/52342695
has answer: http://stackoverflow.com/a/52342695
has title: Appending only new values from a dataframe to another dataframe in pandas
accepted answer: http://stackoverflow.com/a/52342837
tagged with: pandas
type: AnsweredQuestion
upvote count: 0
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/q/52293248
has body: I trying to run the following script but encounter this error. array.append([int(h[i:i + 2], 16) for i in (0, 2, 4)]) What is wrong in my code?
has comment: http://stackoverflow.com/comment/91534356
downvote count: 4
type: AnsweredQuestion
upvote count: 0
has title: ValueError: invalid literal for int() with base 16: ''
score: -4
has comment: http://stackoverflow.com/comment/91535211
has comment: http://stackoverflow.com/comment/91534697
favorite count: 0
has answer: http://stackoverflow.com/a/52293861
type: Question
has comment: http://stackoverflow.com/comment/91534491
has comment: http://stackoverflow.com/comment/91534538
has comment: http://stackoverflow.com/comment/91534421
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/52293861
has comment: http://stackoverflow.com/comment/91534338

http://stackoverflow.com/a/76527949
downvote count: 0
score: 1
has body: This was actually solved here https://github.com/pydata/xarray/issues/2417#issuecomment-460298993 (the GitHub Issue appears to be from the Asker here) The solution suggested by @jhamman (again an extremely good profile match) was to set the env var OMP_NUM_THREADS to a desirable thread count (suggesting about 2x the wanted core count, presumably to take advantage of modern Intel/AMD thread technologies)
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52374936

http://stackoverflow.com/q/52414487
has comment: http://stackoverflow.com/comment/91773445
type: Question
has comment: http://stackoverflow.com/comment/91773152
answer count: 2
has body: It is a simple maze game I did for school. I have tried different solutions but still cant figure out how. I don't necessarily need a full solution; any tips would help. x = 1 y = 1 valid_selection = True while True: if x == 1 and y == 1: if valid_selection == True: print("You can travel: (N)orth.") valid_selection = True choice = input("Direction: ") if choice.lower() == "n": y += 1 else: print("Not a valid direction!") valid_selection = False elif x == 1 and y == 2: if valid_selection == True: print("You can travel: (N)orth or (E)ast or (S)outh.") valid_selection = True choice = input("Direction: ") if choice.lower() == "n": y += 1 elif choice.lower() == "e": x += 1 elif choice.lower() == "s": y -= 1 else: print("Not a valid direction!") valid_selection = False elif x == 3 and y == 1: print("Victory!") break
upvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52414714
type: UnansweredQuestion
tagged with: python
score: -2
has title: How can I refactor my code using functions?
has answer: http://stackoverflow.com/a/52414612
downvote count: 2

http://stackoverflow.com/q/52325851
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have a dataframes like that df1 A B C SN 0 10 23 48 456123 1 15 45 98 789456 2 16 62 55 123789 df2 A B C SN 0 10 19 48.0 456123 1 15 45 NaN 789456 2 68 77 55.0 123789 I need something like below SN 123789 456123 789456 A_x 16 10 15 B_x 62 23 45 C_x 55 48 98 A_y 68 10 15 B_y 77 19 45 C_y 55 48 0 I have tried using pandas groupby and pivot but didn't working as I wanted. Any help?
has answer: http://stackoverflow.com/a/52325876
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52325925
score: 0
has comment: http://stackoverflow.com/comment/91599890
tagged with: pandas
upvote count: 1
has title: How to get the pandas columns into rows with custom condition?
downvote count: 1
has comment: http://stackoverflow.com/comment/91599243

http://stackoverflow.com/a/52311087
upvote count: 2
has body: A dictionary does not allow for random access of elements without knowing their key. The only solution is to find all Zero elements, store them in a list, and then taking a random selection from them: import random zeros = [k for k, v in d.items() if v == "Zero"] random.sample(zeros, 1000)
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52310981
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52310981

http://stackoverflow.com/comment/91708012
comment on: http://stackoverflow.com/q/52362195
type: Comment
type: QuestionComment
has text: @MisterMiyagi I got your point, but I have to do this. I know how to use the standard install way, but my boss forced me to do this, because this script will be used by other department, my boss don't want they to do many operation, all they need to do is copy my code, then run it. And I think you not answer the core problem in this questions, why script can't find new module after using system command to install package when the script in the running status.
score: 1

vector
tags question: http://stackoverflow.com/q/52405495
type: Tag
tag name: vector
tags question: http://stackoverflow.com/q/52313685
tags question: http://stackoverflow.com/q/52302458

pca
tag name: pca
type: Tag
tags question: http://stackoverflow.com/q/52321077
tags question: http://stackoverflow.com/q/52290175
tags question: http://stackoverflow.com/q/52284999

http://stackoverflow.com/comment/91609672
type: QuestionComment
has text: in a 3d contourf, you first need a mesh grid of x and y points using `np.meshgrid`. Lets says you have a 2d square grid of 10x10 = 100 points. It means for each x value you have 10 y values and vice versa. Now at each of these 100 points (a pair of x and y) you have a z value. That being said, your Z should be a 10x10 matrix. Now you can print the shape of X, Y and Z and see that is not the case currently and hence the error. Check [this](https://jakevdp.github.io/PythonDataScienceHandbook/04.04-density-and-contour-plots.html) page for a sample on how to use `contourf`
score: 3
comment on: http://stackoverflow.com/q/52331377
type: Comment

http://stackoverflow.com/q/52413568
has body: Im using GSpread trying to pass the content on my JSON file (Google API Service Application credentials) as a python Dictionary on my script. Im trying to not to carry a json file wherever I take my script. I get the following error when I tried to pass a dictionary instead of a json file on the following line: credentials = ServiceAccountCredentials.from_json_keyfile_name(auth_gdrive(), scope) TypeError: expected str, bytes or os.PathLike object, not set ### auth_gdrive() returns a dictionary like this: def auth_gdrive(): dic = { "type": "miauuuuuu", "pass": "miauuuu" } Im not allow to show whats really in the dic.
has answer: http://stackoverflow.com/a/52414229
tagged with: python
has title: GSpread pass credentials from Python not JSON
tagged with: gspread
answer count: 4
has comment: http://stackoverflow.com/comment/91771310
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52435143
type: Question
tagged with: google-sheets-api
upvote count: 5
score: 5
accepted answer: http://stackoverflow.com/a/52435143
downvote count: 0
possible better answer: http://stackoverflow.com/a/63421687
has answer: http://stackoverflow.com/a/66900991
has answer: http://stackoverflow.com/a/63421687
has comment: http://stackoverflow.com/comment/91771099
favorite count: 0

http://stackoverflow.com/comment/91494910
score: 0
type: Comment
type: QuestionComment
has text: `y = ' '`. You are missing the space in this line.
comment on: http://stackoverflow.com/q/52273431

http://stackoverflow.com/q/52415829
answer count: 3
has answer: http://stackoverflow.com/a/52415926
possible better answer: http://stackoverflow.com/a/52415872
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/52415872
accepted answer: http://stackoverflow.com/a/52415926
has comment: http://stackoverflow.com/comment/91775472
has comment: http://stackoverflow.com/comment/91775484
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52415868
type: Question
has title: Finding values between symbols by regex where symbol might be part of value
has body: There is a string which I am trying to extract values from between symbols, but the symbol or delimiter also happens to be part of the string. Assume the string below: message =': :1:1st message:2a:2nd message:x:this is where it fails status: fail :3:3rd message' and the desired results: ['1st message','2nd message','this is where it fails status: fail','3rd message'] Current code and results: import re def trans(text): text = text+':' tag = re.findall(r':(.*?):',text) return [i for i in tag if not i.isspace()] trans(message) &gt;&gt;['1st message', '2nd message', 'this is where it fails status', '3'] Any idea how I can form my regex to also include the pattern to include 'status: fail ' as part of the results?
score: 0

http://stackoverflow.com/a/52327680
downvote count: 0
score: 10
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52327098
upvote count: 10
type: Answer
answers question: http://stackoverflow.com/q/52327098
has body: Try below code to wait for iframe and switch to it to be able to handle inner nodes: from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait as wait from selenium.webdriver.common.by import By driver = webdriver.Chrome() driver.get(URL) wait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it("iframe_name_or_id")) Instead of "iframe_name_or_id" you can pass iframe as WebElement: wait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(driver.find_element_by_xpath('//iframe'))) To wait for presence of element inside frame: wait(driver, 10).until(EC.presence_of_element_located((By.ID, "Element ID"))) You can also use By.NAME, By.CLASS_NAME, By.XPATH, etc... More about ExplicitWait

http://stackoverflow.com/q/52413802
tagged with: python
has comment: http://stackoverflow.com/comment/91771574
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91981886
tagged with: django
score: 2
has comment: http://stackoverflow.com/comment/91771422
has comment: http://stackoverflow.com/comment/91777989
has comment: http://stackoverflow.com/comment/91771579
has title: Object of type <Model> is not JSON serializable
type: Question
has comment: http://stackoverflow.com/comment/91946133
has body: If I have GFK like inheritance models of Assets (Asset.model having an asset_id, asset_name, and an Account, OneType.model, SecondType.model, all inheriting from the Asset model etc... based on this), and I want to provide an API endpoint for all assets in my Account, I could have (not sure if this is convention) a property on the Account model that is a list that extends the different asset types: #Account model @property def assets(self): assets = [] assets.extend(self.onetype_set.all()) assets.extend(self.secondtype_set.all()) … return assets I would need a serializer for the account class AccountSerializer(serializers.ModelSerializer): # filter to assets for the user def get_queryset(self): return Account.objects.filter(organization=self.request.user) class Meta: model = Account fields = ('assets', ) and I assume for each of the asset types class OneTypeSerializer(serializers.ModelSerializer): class Meta: model = OneType fields = ('asset_id', 'asset_name',) class SecondTypeSerializer(serializers.ModelSerializer): … … but I keep getting an error: Object of type 'OneType' is not JSON serializable ( i understand the error means I need to get the model to be serialized into JSON, but I thought the model would call the model’s serializer….) The stack trace doesn’t seem to be helpful because of the internal workings of DRF’s Viewsets, but here it is: /usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py in default else: return list(iterable) # Let the base class default method raise the TypeError return JSONEncoder.default(self, o) """ raise TypeError("Object of type '%s' is not JSON serializable" % o.__class__.__name__) ... def encode(self, o): """Return a JSON string representation of a Python data structure. &gt;&gt;&gt; from json.encoder import JSONEncoder &gt;&gt;&gt; JSONEncoder().encode({"foo": ["bar", "baz"]}) ▼ Local vars Variable Value o &lt;OneType: AssetName - Type 1 : Account 2&gt; self &lt;rest_framework.…
downvote count: 0
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/91965479
favorite count: 0
has comment: http://stackoverflow.com/comment/91779736

http://stackoverflow.com/a/52369715
has body: Inside translate, toplevel is a local variable. You need to make it global if you wish to access it outside of translate and you aren't using classes.
has comment: http://stackoverflow.com/comment/91683898
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52369623
answers question: http://stackoverflow.com/q/52369623
type: Answer
upvote count: 2

http://stackoverflow.com/q/52402837
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1373164
has comment: http://stackoverflow.com/comment/91750118
tagged with: python
has title: How to create Dynamic Dataframe in Pandas
downvote count: 1
type: Question
answer count: 2
upvote count: 0
score: -1
has body: lst = ['SymbolA','SymbolB', 'SymbolC' .... 'SymbolN'] I want to create dynamic Dataframe in Python Pandas. for i in lst: data = SomeFunction(lst[i]) # This will return dataframe of 10 x 100 lst[i]+str(i) = pd.DataFrame(data) pd.Concat(SymbolA1,SymbolB1,SymbolC1,SymbolD1) Anyone can help on how to create the dataframe dynamically to achieve as per the requirements?
tagged with: pandas
has answer: http://stackoverflow.com/a/52405543
favorite count: 0
has comment: http://stackoverflow.com/comment/91750088
has answer: http://stackoverflow.com/a/52403439

http://stackoverflow.com/q/52284137
has comment: http://stackoverflow.com/comment/91516813
upvote count: 1
has comment: http://stackoverflow.com/comment/91516564
type: AnsweredQuestion
tagged with: list
score: 1
has body: I want to initialize empty numpy (E) array and then append selected rows from existing array(D) to the empty array(E). I couldn't initialize an empty array matching the dimension of D.How can i solve this. E = np.array([ [ ] ]) D = np.array([ [20, 23 ], [19, 23],[19,22] ]) for i in np.where(index): ## assume index value is ([0],[2]) E = np.append( E , D[i] , axis = 0) I am trying to achive below result: E = ([ [20, 23 ], [19,22] ]) Error: all the input array dimensions except for the concatenation axis must match exactly
possible better answer: http://stackoverflow.com/a/52284206
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52284206
answer count: 2
has answer: http://stackoverflow.com/a/52284238
tagged with: arrays
downvote count: 0
has title: create an empty numpy array based and append existing array
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/52284238

http://stackoverflow.com/a/52376771
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/52376405
score: -1
upvote count: 0
has body: There's an issue with installing via pip, but if you do you'll want to do this to import resolver (same goes for other classes): from dns import resolver Also, the examples you find online may change slightly. This: import dns.name n = dns.name.from_text('www.dnspython.org') o = dns.name.from_text('dnspython.org') Becomes this: from dns import name n = name.from_text('www.dnspython.org') o = name.from_text('dnspython.org')

http://stackoverflow.com/a/52358688
has comment: http://stackoverflow.com/comment/91661896
has comment: http://stackoverflow.com/comment/91662075
score: 3
has comment: http://stackoverflow.com/comment/91662041
upvote count: 3
has body: As mentioned in the comment above: Create an instance: yobj = Year() and pass the value to be assigned year = 1998 yobj.add_year(year)
answers question: http://stackoverflow.com/q/52358634
has comment: http://stackoverflow.com/comment/91662204
type: Answer
has comment: http://stackoverflow.com/comment/91661880
has comment: http://stackoverflow.com/comment/91662105
downvote count: 0

http://stackoverflow.com/q/52345457
has comment: http://stackoverflow.com/comment/91641388
has body: When I run this code (which I created a module for my qrc file) import sys from PyQt4 import QtCore, QtGui, uic from PyQt4.QtCore import * from PyQt4.QtGui import * mainwindow = uic.loadUiType("mainmenu2.ui")[0] #load the UI class Mainmenu(QtGui.QMainWindow, mainwindow): def __init__(self, parent=None): super(Mainmenu, self).__init__(parent) self.setupUi(self) #self.aboutp.clicked.connect(self.linkabout) app = QtGui.QApplication(sys.argv) mainwindow = Mainmenu #aboutwindow = About_us_page(None) mainwindow.show() app.exec_() I get this error Traceback (most recent call last): File "C:\Users\megan\Desktop\newqt\try1.py", line 7, in &lt;module&gt; mainwindow = uic.loadUiType("mainmenu2.ui")[0] #load the UI File "C:\Python34\lib\site-packages\PyQt4\uic\__init__.py", line 211, in loadUiType exec(code_string.getvalue(), ui_globals) File "&lt;string&gt;", line 202, in &lt;module&gt; File "C:\Users\megan\Desktop\newqt\test_rc.py", line 49680, in &lt;module&gt; qInitResources() File "C:\Users\megan\Desktop\newqt\test_rc.py", line 49675, in qInitResources QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) TypeError: qRegisterResourceData(int, str, str, str): argument 2 has unexpected type 'str`' so I know the problem is in my resource file, and I've looked online and the only help I could find was this comment pyrcc generates Python 2.x code by default. Try regenerating your resource files using pyrcc with flag '-py3' But I don't know how to do that so please if someone could help me solve this problem, thanks
has comment: http://stackoverflow.com/comment/91637332
has comment: http://stackoverflow.com/comment/91637358
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/63682973
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91637426
has title: pyqt4 problems with resorce system (TypeError: qRegisterResourceData)
has comment: http://stackoverflow.com/comment/91637385
score: 1
type: Question
has comment: http://stackoverflow.com/comment/91641290
tagged with: pyqt4
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91641421
has comment: http://stackoverflow.com/comment/91637278
tagged with: pyqt

http://stackoverflow.com/comment/91645608
score: 1
type: AnswerComment
type: Comment
has text: gist can render ipynb files but sometimes it doesn't work for some reason. you can work around this by pasting the gist link into nbviewer as a workaround.
comment on: http://stackoverflow.com/a/52347709

http://stackoverflow.com/comment/91677296
type: QuestionComment
has text: The code as such should work, so I would suspect your system configuration. iptables or packet filter or what your OS uses. But I suspect if you tried (for instance with netcat) you would see not get through.
comment on: http://stackoverflow.com/q/52356224
score: 0
type: Comment

http://stackoverflow.com/comment/91793873
score: 0
has text: But how is the program supposed to know whether it should decode `\u1234` as `\u1234` or `ሴ` then? There is no way to tell without making assumptions about the input data, right?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52425315

http://stackoverflow.com/q/52352448
has comment: http://stackoverflow.com/comment/91686165
has comment: http://stackoverflow.com/comment/91661145
score: 0
tagged with: python
tagged with: pygame
has title: I can't move sprites in pygame
tagged with: python-3.x
type: UnansweredQuestion
has body: It's the first time I create a game with pygame and I find a logical error. This game consist in a sort of puzzle and to play it you have to click to the piece of puzzle then click on the area where you want it to move. When I try to run my code, sprites doesn't move. I tried to modify the function move(), but it didn't change anything. When I run the program and I selected and move the pieces of puzzle of the game they are drawing again by the computer but in the same position. They aren't moving at the coordinates that I write in the code. import pygame from pygame.locals import * import sys import os width = 1100 hight = 700 square1 = (240, 45) square2 = (25, 55) square3 = (25, 245) square4 = (248, 245) coords1 = [800, 50] coords2 = [550, 50] coords3 = [550, 250] coords4 = [810, 250] pygame.init() screen = pygame.display.set_mode((width, hight)) pygame.display.set_caption('Hidden Boys') background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((250, 250, 250)) class Puzzle_piece(pygame.sprite.Sprite): def __init__(self, image_file, location): pygame.sprite.Sprite.__init__(self) self.counter = 0 self.image = pygame.image.load(image_file) self.rect = self.image.get_rect() self.rect.left, self.rect.top = location self.state = "still" self.area = screen.get_rect() self.angle = 0 self.movepos = [0, 0] def updates(self, position): self.rect = position def move(self): screen.blit(self.image, self.rect) def rotate_right(self): self.angle += -90 self.image = pg.transform.rotozoom(self.orig_image, self.angle, 1) self.rect = self.image.get_rect(center = self.rect.center) class Frame(pygame.sprite.Sprite): def __init__(self, image_file = None, location = None, dim = screen, color = (250, 250, 250)): pygame.sprite.Sprite.__init__(self) #call Sprite initializer if image_file and location != None : self.image = pygame.image.load(image_file) self.rect = self.image.get_rect() self.rect.left, self.rect.top = location self.frame = pygame.Surfa…
has answer: http://stackoverflow.com/a/52352588
type: Question
answer count: 1

http://stackoverflow.com/comment/93931759
type: Comment
has text: `array = hdf["Photos/Image 1"][:]`. `h5py` loads datasets as numpy arrays. No need for that `array(list(...)))` dance.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52394397

http://stackoverflow.com/comment/91517845
comment on: http://stackoverflow.com/a/52284448
type: Comment
has text: @abarnert Without a fuller comparison between the two, I think this is good enough.
type: AnswerComment
score: 0

http://stackoverflow.com/q/52282705
tagged with: django
tagged with: python
has title: Django: resize images with different width/height ratios
has comment: http://stackoverflow.com/comment/91513709
type: Question
has comment: http://stackoverflow.com/comment/91513940
score: 0
has answer: http://stackoverflow.com/a/52283318
answer count: 1
has body: For a page showing many pictures I use something like &lt;img src='{{ instance.piece_image.url }}' hspace='40' vspace='40' style='width:16%;height:16%;'/&gt; or &lt;img src='{{ instance.piece_image.url }}' hspace='40' vspace='40' width='250px' height='250px'/&gt; However, my images have different width/height ratios and differ in absolute size (allowing more flexibility for the user uploading the image). Now the first method keeps the aspect ratio while not respecting the absolute size of the image whereas the second method fixes the absolute size but does not accommodate for different aspect ratios. What would be the preferred way to resize my images keeping the aspect ratio and and providing a fixed absolute size (of the greater of width or height)? E.g. it could be achieved by recalculating the width and height with basic math but I did not find a convenient way to do this in a template yet.
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/q/52301197
has answer: http://stackoverflow.com/a/52301579
accepted answer: http://stackoverflow.com/a/52301579
tagged with: recursion
type: AnsweredQuestion
has title: Replacing a for loop with tail recursion in a recursive function
linked to: http://stackoverflow.com/q/41210142
tagged with: computer-science
type: Question
answer count: 2
tagged with: algorithm
has answer: http://stackoverflow.com/a/52303278
tagged with: tail-recursion
score: 0
has comment: http://stackoverflow.com/comment/91554295
has comment: http://stackoverflow.com/comment/91550189
has body: I'm trying to make the following function completely tail recursive, e.g. get that pesky for loop out of there. Reason being is that I'm trying to easily convert the solution to an iterative one involving the use of an explicit stack. Please advise. def permutations(A): P = [] P2 = [] permutations_recursive(A, [], P) permutations_tail_recursive(A, [], P2, 0) print(P2) return P def permutations_recursive(first, last, perms): if len(first) == 0: perms.append(last) else: for i in range(len(first)): permutations_recursive( first[:i] + first[i+1:], last + [first[i]], perms)
tagged with: python
possible better answer: http://stackoverflow.com/a/52303278

http://stackoverflow.com/q/52425055
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52426940
has comment: http://stackoverflow.com/comment/91795121
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91793281
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91792888
tagged with: loops
upvote count: 1
has comment: http://stackoverflow.com/comment/91794220
accepted answer: http://stackoverflow.com/a/52426940
type: Question
has comment: http://stackoverflow.com/comment/91794591
has title: Stop a value from being incremented in each dictionary iteration
has comment: http://stackoverflow.com/comment/91793839
has comment: http://stackoverflow.com/comment/91794783
possible better answer: http://stackoverflow.com/a/52426112
tagged with: python-2.7
has answer: http://stackoverflow.com/a/52426112
answer count: 2
has body: I'm using Python 2.7. I have two tsv data files that I read into two dictionaries that I would like to calculate the recall score of them, so I need to calculate the tp and fn. These how my dictionaries look: gold = {'A11':'cat', 'A22':'cat', 'B3':'mouse'} results = {'A2':'cat', 'B2':'dog'} My code mainly iterates the gold dictionary and removes the digits at the end of the gold dictionary key as well as results key. Then, checks if the keys match in order to find if their values match to calculate the tp. However, my code seems to always increment the fn. Here is my runable code: from __future__ import division import string def eval(): tp=0 #true positives fn=0 #false negatives fp=0#false positives gold = {'A11':'cat', 'A22':'cat', 'B3':'mouse'} results = {'A2':'cat', 'B2':'dog'} #iterate gold dictionary for i,j in gold.items(): #remove the digits off gold keys i_stripped = i.rstrip(string.digits) #iterate results dictionary for k,v in results.items(): #remove the digits off results keys k_stripped = k.rstrip(string.digits) # check if key match! if i_stripped == k_stripped: #check if values match then increment tp if j == v: tp += 1 #delete dictionary entries to avoid counting them again del gold_copy[i] del results_copy[k] #get out of this loop we found a match! break continue # NO match was found in the results, then consider it as fn fn += 1 #&lt;------ wrong calculations caused in this line print 'tp = %.2f fn = %.2f recall = %.2f ' % (tp, fn, float(tp)/(tp+fn)) and this is the output: tp = 1.00 fn = 3.00 recall = 0.25 fn is incorrect, it should be 2 instead of 3. How can I stop fn from being incremented in each iteration? Any guidance will be truly appreciated. Thank you,
downvote count: 0

multithreading
tags question: http://stackoverflow.com/q/52300222
type: Tag
tags question: http://stackoverflow.com/q/52378735
tags question: http://stackoverflow.com/q/52308164
tags question: http://stackoverflow.com/q/52287923
tags question: http://stackoverflow.com/q/52351526
tags question: http://stackoverflow.com/q/52358448
tags question: http://stackoverflow.com/q/52307518
tags question: http://stackoverflow.com/q/52379948
tags question: http://stackoverflow.com/q/52350094
tags question: http://stackoverflow.com/q/52325152
tags question: http://stackoverflow.com/q/52275874
tags question: http://stackoverflow.com/q/52297958
tags question: http://stackoverflow.com/q/52295849
tags question: http://stackoverflow.com/q/52396066
tags question: http://stackoverflow.com/q/52356112
tags question: http://stackoverflow.com/q/52296654
tags question: http://stackoverflow.com/q/52406228
tags question: http://stackoverflow.com/q/52368747
tags question: http://stackoverflow.com/q/52391160
tags question: http://stackoverflow.com/q/52340125
tags question: http://stackoverflow.com/q/52405340
tags question: http://stackoverflow.com/q/52280592
tags question: http://stackoverflow.com/q/52421142
tags question: http://stackoverflow.com/q/52271714
tags question: http://stackoverflow.com/q/52273117
tags question: http://stackoverflow.com/q/52383984
tags question: http://stackoverflow.com/q/52324666
tags question: http://stackoverflow.com/q/52326880
tags question: http://stackoverflow.com/q/52335065
tags question: http://stackoverflow.com/q/52356152
tags question: http://stackoverflow.com/q/52368947
tags question: http://stackoverflow.com/q/52429434
tags question: http://stackoverflow.com/q/52384753
tags question: http://stackoverflow.com/q/52324820
tags question: http://stackoverflow.com/q/52427243
tags question: http://stackoverflow.com/q/52354054
tags question: http://stackoverflow.com/q/52330828
tags question: http://stackoverflow.com/q/52322186
tag name: multithreading
tags question: http://stackoverflow.com/q/52296134
tags question: http://stackoverflow.com/q/52302356
tags question: http://stackoverflow.com/q/52424640
tags question: http://stackoverflow.com/q/52298922
tags question: http://stackoverflow.com/q/52299317

http://stackoverflow.com/a/52415695
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52415663
accepted answer of: http://stackoverflow.com/q/52415663
has body: use try and except userInp = input("YOUR QUESTIONS") try: float(userInp) except ValueError: print("YOUR ERROR")
score: 0

http://stackoverflow.com/comment/91773732
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52414962
has text: so i used try and except, but isn't except used for catching errors not used as an "if-else"?

http://stackoverflow.com/a/52352227
answers question: http://stackoverflow.com/q/52351989
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91653875
has body: After the groupby the resulting dataframe Quantity_sum has only one column: Quantity, while the Country column is the index now. In [66]: Quantity_sum.head() Out[66]: Quantity Country United Kingdom 4263829 Netherlands 200128 EIRE 142637 Germany 117448 France 110480 In order to get list of countries you have to access it through the index attribute of the dataframe, like so: In [67]: Top_10.index.tolist() Out[67]: ['Netherlands', 'EIRE', 'Germany', 'France', 'Australia', 'Sweden', 'Switzerland', 'Spain', 'Japan', 'Belgium'] And for Quantity what you have done seems correct and works for me: In [68]: Top_10['Quantity'].tolist() Out[68]: [200128, 142637, 117448, 110480, 83653, 35637, 30325, 26824, 25218, 23152]

http://stackoverflow.com/q/52354096
accepted answer: http://stackoverflow.com/a/52354748
favorite count: 0
tagged with: data-munging
upvote count: 1
tagged with: python
tagged with: data-processing
has comment: http://stackoverflow.com/comment/91653191
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91653118
tagged with: dataframe
downvote count: 1
type: Question
has body: I have a dataframe and a list of indexes, and I want to get a new dataframe such that for each index (from the given last), I will take the all the preceding rows that matches in the value of the given column at the index. C1 C2 C3 0 1 2 A 1 3 4 A 2 5 4 A 3 7 5 B 4 9 7 C 5 2 3 D 6 1 1 D The column c3 the indexes (row numbers) 2, 4 , 5 my new dataframe will be: C1 C2 C3 0 1 2 A 1 3 4 A 2 5 4 A 4 9 7 C 5 2 3 D Explanation: For index 2, rows 0,1,2 were selected because C3 equals in all of them. For index 4, no preceding row is valid. And for index 5 also no preceding row is valid, and row 6 is irrelevant because it is not preceding. What is the best way to do so?
has comment: http://stackoverflow.com/comment/91653274
score: 0
has title: pandas dataframe take rows before certain indexes
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/52354748

http://stackoverflow.com/comment/91785039
has text: https://wiki.videolan.org/ActiveX/ or https://wiki.videolan.org/Documentation:WebPlugin/
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52420876

http://stackoverflow.com/q/52288632
score: 1
has answer: http://stackoverflow.com/a/56425345
type: Question
tagged with: pyqt
tagged with: pyqt4
downvote count: 0
answer count: 1
favorite count: 0
has body: I can successfully create a new palette and set it to the QApplication at launch. However, once the application is running, I cannot change the colors of the palette anymore. I would like to change the colors of the buttons if the user chooses a particular theme. The current code which works at launch but not later is as follows: palette = QtGui.QPalette() palette.setColor(QtGui.QPalette.Window, QtGui.QColor(3, 18, 14)) palette.setColor(QtGui.QPalette.Base, QtGui.QColor(15, 15, 15)) palette.setColor(QtGui.QPalette.AlternateBase, QtGui.QColor(53, 53, 53)) palette.setColor(QtGui.QPalette.ToolTipBase, QtCore.Qt.white) palette.setColor(QtGui.QPalette.Text, QtCore.Qt.white) palette.setColor(QtGui.QPalette.Button, QtGui.QColor(53, 53, 53)) palette.setColor(QtGui.QPalette.ButtonText, QtCore.Qt.white) palette.setColor(QtGui.QPalette.BrightText, QtCore.Qt.red) palette.setColor(QtGui.QPalette.Highlight, QtGui.QColor(142, 45, 197).lighter()) palette.setColor(QtGui.QPalette.HighlightedText, QtCore.Qt.black) app.setPalette(palette) The same palette object if used in a slot doesnt change the color. Eg code in the slot: palette.setColor(QtGui.QPalette.Button, QtGui.QColor(53, 53, 53)) app.setPalette(palette) Could someone please let me know what I am missing here? Thanks. Edit: I just found out that it modified only some of the areas. For eg, in the slot I have written, it changes the highlight color, but not the QTab color (which was set by setting color to Button). My current slot code: def change_theme(self): pal = QtWidgets.QApplication.palette() #The next line works pal.setColor(QtGui.QPalette.Highlight, QtGui.QColor(0, 0, 128)) #The next line doesnt work. Expected it to change the Tab Widget color #using this line. pal.setColor(QtGui.QPalette.Button, QtGui.QColor(62, 80, 91)) QtWidgets.QApplication.setPalette(pal)
tagged with: python
has title: PyQt5 change app theme/palette dynamically
tagged with: python-3.x
type: UnansweredQuestion
tagged with: pyqt5
upvote count: 1

http://stackoverflow.com/a/52288100
downvote count: 0
has body: Use Series.between for boolean mask and then count Trues by sum, it is processes like 1s: out = df['a'].between(0, 1023).sum() print (out) 8
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52288000
score: 3
answers question: http://stackoverflow.com/q/52288000
type: AcceptedAnswer

http://stackoverflow.com/q/52336432
type: UnansweredQuestion
type: Question
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/91620039
tagged with: flask-sqlalchemy
linked to: http://stackoverflow.com/q/25958963
has title: How to query the attribute(s) from an Association table (SQLalchemy)
has comment: http://stackoverflow.com/comment/91660275
score: 0
has body: I have a self-Referential Association Relationship and I'm trying to figure out how to get the associated attribute(s) from the association table. This is the code from the model (based on this post): class Contact(db.Model): __tablename__ = 'contact' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Unicode(120), nullable=False, unique=False) to_contacts = association_proxy('to_relations', 'to_contact') from_contacts = association_proxy('from_relations', 'from_contact') def __repr__(self): return "User(%r)" % self.name class ContactRelation(db.Model): __tablename__ = 'contactrelation' id = db.Column(db.Integer, primary_key=True) from_contact_id = db.Column(db.Integer, db.ForeignKey('contact.id')) to_contact_id = db.Column(db.Integer, db.ForeignKey('contact.id')) relation_type = db.Column(db.String(100), nullable=True) from_contact = db.relationship(Contact, primaryjoin=(from_contact_id == Contact.id), backref='to_relations') to_contact = db.relationship(Contact, primaryjoin=(to_contact_id == Contact.id), backref='from_relations') What I'm trying to achieve I want to query a contact and get the contacts related to him. That part works. But I also want to get the relation_type between them. My assumption was that the Contact object returned would contain the relation_type but it doesn't. How can I query such attributes for a Contact object from the association table?
tagged with: python
has comment: http://stackoverflow.com/comment/91623566
answer count: 0
has comment: http://stackoverflow.com/comment/91633923

http://stackoverflow.com/comment/91660958
type: Comment
type: QuestionComment
has text: @today yeah. The answer below has already solved that. could you tell me how to access each value separately?
comment on: http://stackoverflow.com/q/52357733
score: 0

http://stackoverflow.com/comment/91707990
type: Comment
type: QuestionComment
has text: @YvesDaoust - this is just an example code to explain the structure of the code Im dealing with.
score: 0
comment on: http://stackoverflow.com/q/52378578

http://stackoverflow.com/q/52316066
has comment: http://stackoverflow.com/comment/91579540
score: 2
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/52324254
linked to: http://stackoverflow.com/q/47256300
tagged with: django
has body: Let's assume that I have following model: class TestModel(models.Model): some_integer = models.IntegerField() and I have 3 instances of this model: TestModel.objects.create(some_integer=100) TestModel.objects.create(some_integer=50) TestModel.objects.create(some_integer=20) and I'd like to annotate queryset somehow to be able to get following results: for obj in TestModel.objects.annotate(difference=...): print(obj.difference) =&gt; 50 # 100 - 50 =&gt; 30 # 50 - 30 =&gt; None # we don't have anything created after this record Any chance of doing this with Django(2.0) querysets or should I do this 'manually' in Python? We can safely assume that objects are ordered by pk or some date so ordering is preserved.
type: Question
has comment: http://stackoverflow.com/comment/91579634
tagged with: django-queryset
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52324254
favorite count: 0
tagged with: python
has title: Difference with previous object in django queryset annotation

http://stackoverflow.com/a/52399191
type: Answer
answers question: http://stackoverflow.com/q/52396708
score: 0
has body: How to get batter's names: just request the player data directly, I found this url when I watch the page load, get player name from this url will very easy: https://d3k2oh6evki4b7.cloudfront.net/short/inc/players_search_list.csv How to speeder your code: First: Using selenium to load the webdriver will cost the most part time in your code. For your grab target, I suggest you use requests directly instead selenium Second: lxml parser will speeder than the html parser, but you should install it if you never use it, just run "pip install lxml" will help you. installing-a-parser and summarizes the advantages and disadvantages of each parser library for example: import requests from bs4 import BeautifulSoup # start requests target_url = 'https://www.baseball-reference.com/leagues/MLB/2018-standard-batting.shtml' headers = {'User-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'} page_source = requests.get(target_url, headers=headers).text #grab html soup = BeautifulSoup(page_source, 'lxml') #parse three stats: rbi's, runs and hits hits = [i.text for i in soup.find_all('td', {'data-stat': 'H'})] runs = [i.text for i in soup.find_all('td', {'data-stat': 'R'})] rbi = [i.text for i in soup.find_all('td', {'data-stat': 'RBI'})] #print data print(hits, runs, rbi)

http://stackoverflow.com/q/52300313
type: Question
linked to: http://stackoverflow.com/q/49231052
linked to: http://stackoverflow.com/q/41812646
has body: This produces a graph of all these stock prices plotted against the date. If you zoom in, all the tiny ticks have labels for the dates. I wanted to reduce the frequency of ticks so that it only displayed tick marks at the month and year. I have tried using locators and formatters, but whenever I add them all of the ticks and tick labels completely disappear. All that's left at the x-axis is the x-axis label. Does any of the issue lie within the fact that I extract the date and use that for the x-axis plot for every new batch of stock prices I want to plot? Any advice would be appreciated. I am a beginner programmer. from iexfinance import get_historical_data import pandas as pd import matplotlib.pyplot as plt def tester(): start_date = '20170828' end_date = '20180828' symbols =['GOOG', 'IBM', 'CRON'] for symbol in symbols: f_temp = get_historical_data(symbol, start_date, end_date, output_format='pandas') df_close = pd.DataFrame(f_temp['close']) df_open = pd.DataFrame(f_temp['open']) df_date_string = pd.to_datetime(f_temp.index).strftime("%Y%m%d").astype(str) df = pd.merge(df_open, df_close, on=df_date_string) df.columns = ['date', 'open', 'close'] plt.legend(symbols) plot_data(df) plt.show() return df def normalize_data(df): return df/df.ix[0, :] def plot_data(df): normalized = normalize_data(df['close']) plt.plot(df['date'], normalized) plt.title("Normalized close stock prices") plt.xlabel("Dates") plt.ylabel("Close prices") plt.tight_layout() if __name__ == "__main__": df = tester()
linked to: http://stackoverflow.com/q/26700598
tagged with: python
answer count: 0
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/91549120
linked to: http://stackoverflow.com/q/13515471
has title: How can I reduce the frequency of x-axis ticks in Python when plotting multiple groups of values on one axis?
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91549187

http://stackoverflow.com/a/52323350
downvote count: 0
has comment: http://stackoverflow.com/comment/91618045
has comment: http://stackoverflow.com/comment/91618547
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52323299
has body: Simple one-liner with readability in mind. def check(num): return True if math.sqrt(num) % 2 == 0 or (math.sqrt(num)+1) % 2 == 0 else False Result &gt;&gt;&gt; check(25) True &gt;&gt;&gt; check(23) False
type: Answer
answers question: http://stackoverflow.com/q/52323299
score: 2

http://stackoverflow.com/comment/91684120
type: Comment
has text: I would definitely go for `descendant-or-self::b` as the expression that's simplest and best expresses the intent. Simplicity in terms of number of constructs is more important than brevity in terms of number of characters. Avoid comparing `name()` against character strings, it's a bad habit which will sometimes cost you dearly in performance.
score: 2
comment on: http://stackoverflow.com/a/52368785
type: AnswerComment

http://stackoverflow.com/q/52285724
linked to: http://stackoverflow.com/q/26089893
has comment: http://stackoverflow.com/comment/91521150
accepted answer: http://stackoverflow.com/a/52285898
tagged with: multidimensional-array
has body: Hi Stack Overflow community, I have a 3D numpy array Rp of shape 4x4x701, where each of the 701 4x4 slices represents a certain quantity at a different point in time. I'm trying to efficiently apply a Givens rotation matrix Q and its Hermitian transpose QH to each of the 701 slices, and am currently doing it iteratively, like so: for idx in np.arange(Rp.shape[-1]): Rp[[j,k],:,idx] = np.dot(Q, Rp[[j,k],:,idx]) Rp[:,[j,k],idx] = np.dot(Rp[:,[j,k],idx], QH) but there must be a way to do this NOT iteratively (for the numpy speedup). I realise I can just use np.dot for the first case, but this won't work for the second without some transposition, which seems like it would slow things down. Any ideas would be greatly appreciated!
has comment: http://stackoverflow.com/comment/91519942
tagged with: python
type: AnsweredQuestion
tagged with: numpy-slicing
has answer: http://stackoverflow.com/a/52285898
has title: Sequentially applying a dot product to slices of 3D numpy array
has comment: http://stackoverflow.com/comment/91519870
type: Question
has comment: http://stackoverflow.com/comment/91519892
tagged with: dot-product
tagged with: numpy
score: 0
answer count: 1

http://stackoverflow.com/comment/91735548
type: Comment
type: QuestionComment
has text: `tbl` may be just a string, not a `Dataframe` object if `uni` is more than 25.
score: 1
comment on: http://stackoverflow.com/q/52395151

http://stackoverflow.com/comment/91856610
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52283464
has text: when you just enter python in the terminal check to which python version it is pointing to or use pip3 to install the pacakge
score: 0

http://stackoverflow.com/comment/91591694
has text: Is SELinux preventing the execution, I wonder?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52322051
score: 0

http://stackoverflow.com/a/52406841
has body: Solved by renaming the kajiki template master "abc.xhtml" to "xyz.xhtml"
score: 0
answers question: http://stackoverflow.com/q/52406775
type: Answer

http://stackoverflow.com/q/52366296
score: 10
possible better answer: http://stackoverflow.com/a/52377974
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/91677153
tagged with: django-filter
answer count: 2
has answer: http://stackoverflow.com/a/52390592
upvote count: 10
has comment: http://stackoverflow.com/comment/91676906
has body: I have been trying to use django-filters but the objects are not getting filtered. Also, the permission is not working for the partial_update views I have a Viewset which has the basic actions like - list(), retrieve(), destroy(), partial_update() and few other actions, and trying to apply filter for the same. After some research I found that since I am creating the queryset via filters I will have to override the get_queryset() method. However, that also doesn't seem to be working. Does the filter works only with ModelViewSet or ListApiView? ViewSet - class PostViewSet(viewsets.ViewSet): """ The Endpoint to list, retrieve, create and delete Posts. """ filter_backends = (DjangoFilterBackend, ) # filterset_class = PostFilter filter_fields = ('pet_age', 'pet_gender', 'breed') def get_permissions(self): if self.action == 'partial_update' or self.action == 'update': permission_classes = [IsPostAuthor, ] elif self.action == 'create' or self.action == 'destroy': permission_classes = [IsAuthenticated, ] else: permission_classes = [AllowAny, ] return[permission() for permission in permission_classes] def get_queryset(self): return Post.objects.active() # This is implemented via custom Manager def list(self, request, *args, **kwargs): """ Method for Post listing. It can be accessed by anyone. """ serializer = PostListSerializer(self.get_queryset(), many=True, context={"request": request}) return Response(serializer.data) # REST CODE TRUNCATED Permission - class IsPostAuthor(permissions.BasePermission): """ Object-level permission to only allow owners of an object to edit it. """ def has_object_permission(self, request, view, obj): if request.user.is_authenticated: if view.action in ['partial_update', 'update']: return obj.user.id == request.user.id return False return False PostFilter - class PostFilter(filters.FilterSet): class Meta: model = Post fields = ('pet_age', 'pet_gender', 'breed', ) Manager - class PostManager(models.Manager): def active(self): return self.filter(p…
favorite count: 0
has title: Django-filters does not work with the Viewset
has answer: http://stackoverflow.com/a/52377974
tagged with: django
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: django-rest-viewsets
type: Question
accepted answer: http://stackoverflow.com/a/52390592

http://stackoverflow.com/comment/91709858
type: Comment
has text: What you are really looking for is an extrapolation technique. Most of the interpolation techniques you can find around are good at extrapolation in a limited set of cases, and yours does not seem to be one of those. Since you mentioned that you already have some idea on what your data may look like, the fitting solution proposed by @gehbiszumeis seems to be a better alternative.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52378090

http://stackoverflow.com/comment/91770225
comment on: http://stackoverflow.com/a/52413217
type: Comment
score: 0
type: AnswerComment
has text: The question specifically says that he doesn't want to write records that are missing any of the "superset" of strings

http://stackoverflow.com/q/52364306
has body: I want to draw a graphic with using datas in datetime format as xaxis, but the process lasts very, very, extremly long, over 30 mins there is still no graphic. But once I apply datas in another column, the graphic will occur very soon. All the datas' formats are 'list'. I'm confused about that, since they are all in the same format, why I can't draw the graphic out using the datetime formate as xaxis?? here is my code, I cherish all your time and help! from matplotlib import pyplot as plt import csv names = [] x = [] y = [] names=[] with open('all.csv','r') as csvfile: #this csv file contains over 16000 datas plots= csv.reader(csvfile,delimiter=',') for row in plots: x.append(row[1]) #row1 is the datetime format data y.append(row[2]) print(x,y) plt.plot(x,y) plt.show() Lines of my csv file look something like: 2016/05/02 10:47:45,14.1,20.1,N.C.,170.7,518.3,-1259,-12.61,375.8,44.92,13.76,92.74,132.6,38.86,165.3,170.9,311.5,252.3,501.2,447.2,378.4,35.48,7.868,181.2, I want the first column as xaxis and the following colums as yaxis... and the y axis doesn't change, no matter how I change the y axis limit. import matplotlib.pyplot as plt import numpy as np import pandas as pd df = pd.read_csv('all.csv') x = df.iloc[:,1] y = df.iloc[:,3] x = pd.to_datetime(x) plt.figure(num=3, figsize=(15, 5)) plt.plot(x,y) my_y_ticks = np.arange(0, 40, 10) plt.xticks(rotation = 90) plt.show()
score: 0
has title: Problem when using datetime data to draw graphic
answer count: 1
has comment: http://stackoverflow.com/comment/91674170
accepted answer: http://stackoverflow.com/a/52364626
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/52364626
type: AnsweredQuestion
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91674676
type: Question
tagged with: graphics

http://stackoverflow.com/q/52311611
type: AnsweredQuestion
upvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52311803
type: Question
has body: I am trying to add my function value into my dataset column. I have eight columns which are: 'DATE','Max_R','Total_R','Avg_R','MAX_T','TOTAL_T','AVG_T' Then I divided my DATE column into three columns as Day, Month and year respectively. Here is my code in python: import pandas as pd import numpy as np df=pd.read_csv('moving_average_calculation.csv', sep=',') #df = pd.DataFrame(columns=['DATE','Max_R','Total_R','Avg_R','MAX_T','TOTAL_T','AVG_T']) df = pd.DataFrame(pd.date_range('1-Jan-08', periods=2558),columns=['DATE']) def f(df): df = df.copy() df['Day'] = pd.DatetimeIndex(df['DATE']).day df['Month'] =pd.DatetimeIndex(df['DATE']).month df['Year'] = pd.DatetimeIndex(df['DATE']).year return df print(f(df).head(10)) Now I want to get my columns which would have these columns: 'Day','Month','Year','Max_R','Total_R','Avg_R','MAX_T','TOTAL_T','AVG_T' How can I do this? Thank you.
has title: add my function data column into original data in python
score: -1
tagged with: python-3.x
tagged with: python
tagged with: data-processing
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52311803
tagged with: numpy

http://stackoverflow.com/comment/91801007
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52428301
score: 1
has text: @rahlf23 A `Journey` cannot span multiple days and has to end in the same day just like `Journey2` ended even if its conditions were always ON.

http://stackoverflow.com/comment/91687399
type: Comment
comment on: http://stackoverflow.com/q/52365440
score: 0
has text: I meant that just for test purpose break the query and pass it to read_sql_query part by part..if it returns the result for say first part then execute next until you get the part because of which read_sql_query is returning nothing
type: QuestionComment

http://stackoverflow.com/q/52362703
favorite count: 0
type: Question
tagged with: python
tagged with: python-3.x
upvote count: 1
tagged with: internet-explorer
has body: I'm working on detecting a case in Internet Explorer where the header frame is repeated multiple times in a webpage. Normally it won't render the header frame multiple times. But sometimes it will. I'm not sure when it does. How do I detect when such case occurs in python. I'm new to it. I can get the source code of the page and check if the header's code is repeated multiple times. But that may not be the case here. I can use selenium to check if the element is present multiple times or not. But that may not be the case if it is problem with rendering in IE. The only solution I can think of is checking if a particular image exists multiple times in another image. I can take the screenshot of image at the time of testing and I can have the screenshot of only header. But how do I check if the header exists multiple times? Any solution to tackle such problem?
has title: How to spot multiple occurances of an element in Python
tagged with: render
type: UnansweredQuestion
tagged with: image
answer count: 0
downvote count: 0
score: 1

http://stackoverflow.com/comment/91724441
comment on: http://stackoverflow.com/q/52387192
score: 0
type: Comment
type: QuestionComment
has text: @Mitiku can you tell me why is it taking the target as train label?

python-imaging-library
tags question: http://stackoverflow.com/q/52273313
tags question: http://stackoverflow.com/q/52342101
tags question: http://stackoverflow.com/q/52307290
tags question: http://stackoverflow.com/q/52417927
tags question: http://stackoverflow.com/q/52411503
tags question: http://stackoverflow.com/q/52410807
tags question: http://stackoverflow.com/q/52376476
tags question: http://stackoverflow.com/q/52295414
tag name: python-imaging-library
tags question: http://stackoverflow.com/q/52317966
type: Tag
tags question: http://stackoverflow.com/q/52399546
tags question: http://stackoverflow.com/q/52375035
tags question: http://stackoverflow.com/q/52309134
tags question: http://stackoverflow.com/q/52289366
tags question: http://stackoverflow.com/q/52395121
tags question: http://stackoverflow.com/q/52331867
tags question: http://stackoverflow.com/q/52398468

http://stackoverflow.com/comment/91518005
comment on: http://stackoverflow.com/q/52281398
type: Comment
type: QuestionComment
has text: Have you actually configure the broker with PSK TLS? Why can't you use normal TLS certs and Username/password or client certificates to identify the clients?
score: 0

http://stackoverflow.com/comment/91728141
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52391512
type: Comment
has text: To position an element on a plane you need two coordinates, usually called x and y. You need to supply those two coordinates as a tuple or list to the `annotate`'s `xy` argument. Here you only supply a single number.

http://stackoverflow.com/q/52311576
favorite count: 0
tagged with: python-3.x
tagged with: qgraphicsview
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/52315372
tagged with: pyside2
has body: I want to move my SimpleItem object if I move mouse pressing left button. I have successed getting the position of mouse cursor if I press the object. but I have no idea how to move the item to that position. Could you help me? import sys from PySide2 import QtGui, QtWidgets, QtCore class SimpleItem(QtWidgets.QGraphicsItem): def __init__(self): QtWidgets.QGraphicsItem.__init__(self) self.location = 1.0 def boundingRect(self): penWidth = 1.0 return QtCore.QRectF(-10 - penWidth / 2, -10 - penWidth / 2, 20 + penWidth, 20 + penWidth) def paint(self, painter, option, widget): rect = self.boundingRect() painter.drawRect(rect) def mousePressEvent(self, event): print("hello") def mouseMoveEvent(self, event): print(event.pos()) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) scene = QtWidgets.QGraphicsScene() item = SimpleItem() scene.addItem(item) view = QtWidgets.QGraphicsView(scene) view.show() sys.exit(app.exec_())
answer count: 1
downvote count: 1
tagged with: qgraphicsitem
has title: Pyside2 How can i move box?
has answer: http://stackoverflow.com/a/52315372
upvote count: 4
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/52349921
has title: Problem with Speech Recognition and Shutil in a Try Clause
has comment: http://stackoverflow.com/comment/91645231
score: 0
tagged with: try-except
answer count: 1
tagged with: speech-recognition
has body: I am trying to use speech recognition to walk through folders and name all the files based on the spoken voice content. This code currently works as long as the audio files are inside of folders which are inside of the parent folder, Audio Files (line 13). If there is an audio file inside of the 'Audio Files' folder, I get a Name Error because the 'text' variable (last line) is not defined. This makes sense, but what is odd is that this code works in the former situation. The main problem I'm having is in the 'try' clause. When the shutil.move() function is not commented out, instead of renaming the audio files, it makes a duplicate and then renames that one, whereas when this function is outside of the 'try' clause (last line), it renames the files without being duplicated. After executing the first two lines of the 'try' clause, instead of executing the third, it executes the expect clause instead. I'm not sure why this happens. My goal is simply to have all audio files renamed in any folder without there being duplicates. import speech_recognition as sr import sys, os, shutil, time #folder_name = sys.argv[1] #filename = sys.argv[1] os.chdir(r'C:\Users\Sonorityscape\Desktop') r = sr.Recognizer() for root, dirs, files in os.walk('c:\\users\\sonorityscape\\desktop\\Audio Files'): for file in files: audio_file = os.path.join(root, file) parent_folder = os.path.basename(root) if os.path.isfile(audio_file): with sr.AudioFile(audio_file) as source: audio = r.listen(source) try: text = r.recognize_google(audio) #shutil.move(audio_file, root + '\\' + parent_folder + ' - ' + text.capitalize() + '.wav') print(file + ' ---&gt; {} - {}'.format(parent_folder, text.capitalize()) + '.wav') except: print(file + ' ---&gt; Sorry, could not recongnize anything.') shutil.move(audio_file, root + '\\' + parent_folder + ' - ' + text.capitalize() + '.wav')
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91646620
has comment: http://stackoverflow.com/comment/91645261
has comment: http://stackoverflow.com/comment/91645833
tagged with: audio
has comment: http://stackoverflow.com/comment/91645199
tagged with: file
has comment: http://stackoverflow.com/comment/91646090
type: Question
has answer: http://stackoverflow.com/a/52350683

http://stackoverflow.com/q/52393334
linked to: http://stackoverflow.com/q/31485361
tagged with: python
tagged with: distribution
has title: An algorithm for mapping one categorical distribution onto another?
answer count: 0
type: UnansweredQuestion
has body: I ran into what I thought was a simple problem the other day: given a population of entities (companies, in this case), I want to project the distribution of one category onto another. For example, here are two categories: 60% 40% |----A1----|---A2---| |---B1---|----B2----| 40% 60% In the above, category A represents 'number of employees' and category B represents 'annual sales'. Each category is a different way of slicing/bucketing the same population, so the total number of companies in 'A' categories equals the total in all 'B' categories. Because category A1 is greater than category B1, my thinking is to get a weighted average, something like: "take 2/3 (40%/60%) of B1 and 1/3 (the remainder) of B2". In the above example, if B1 is a revenue of $1,500 and B2 of $3,000, then the average for category A1 would be $2,000 (i.e. (2/3)*$1,500 + (1/3)*$3,000). And for category A2, the revenue would simply be $3,000. Darned if I can figure out how to code this in a way that will scale to 'n' categories and cover all situations, though. The approach I ended up using was to inflate each dataframe by the 'counts' (a solution I found here, btw), join using the row-index, and then take the average there. I know this boils down to a weighted-average problem, but I couldn't sort it out. Here's my example Python/Pandas code: import pandas as pd d_A = {'Cat_A_Name': ['A1', 'A2'], 'Cat_A_Empl': [2, 5], 'Cat_A_Counts': [60, 40]} d_B = {'Cat_B_Name': ['B1', 'B2'], 'Cat_B_Rev': [1500, 3000], 'Cat_B_Counts': [40, 60]} df_A = pd.DataFrame(data=d_A) df_B = pd.DataFrame(data=d_B) # For each dataframe, do a row-expansion by count (and then drop that count column) df_A = df_A.loc[df_A.index.repeat(df_A['Cat_A_Counts'].astype('int'))].reset_index(drop=True) df_A.drop({'Cat_A_Counts'}, axis=1, inplace=True) df_B = df_B.loc[df_B.index.repeat(df_B['Cat_B_Counts'].astype('int'))].reset_index(drop=True) df_B.drop({'Cat_B_Counts'}, axis=1, inplace=True) # Then join by index, take the average by Ca…
has comment: http://stackoverflow.com/comment/91732330
type: Question
has comment: http://stackoverflow.com/comment/91733155
tagged with: logic
score: 0
tagged with: pandas-groupby
tagged with: pandas

http://stackoverflow.com/q/52285109
has answer: http://stackoverflow.com/a/52285140
downvote count: 0
tagged with: multivariate-testing
has comment: http://stackoverflow.com/comment/91542511
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: regression
tagged with: python
score: 1
upvote count: 1
has body: I am trying to do a multivariate polynomial regression on my data in python. I have 4 independent and 1 dependent variable. I'm unsure even where to begin. I've gone through a lot of blogs in the last few days, but didn't get a lot of clarity. Most of the blogs are for univariate data. Is there a good post anywhere that anyone could direct me to, that explains the concept and has a sample code? Any help is much appreciated. Thank you!
type: Question
has title: Multivariate polynomial regression

pika
tags question: http://stackoverflow.com/q/52331614
tag name: pika
type: Tag

http://stackoverflow.com/a/52503971
has body: Eventually I was able to figure out the answer to my own question. Posting this for later users. Updated snippet is below. Short version of the story: requests.status_code was sending back a integer but I made the faulty assumption that it would be a string, thus my internal comparison was no good. for row in csvin: try: uuidUrl = row[0] xip_file = row[1] response = requests.get(uuidUrl, headers=headers) status = response.status_code print(status) if status == 401: print(xip_file, "may have failed, loggin back in") login(url, payload) headers = login(url, payload) response = requests.get(uuidUrl, headers=headers) with open(xip_file, 'wb') as fd: for chunk in response.iter_content(chunk_size=128): fd.write(chunk) fd.close() else: with open(xip_file, 'wb') as fd: for chunk in response.iter_content(chunk_size=128): fd.write(chunk) fd.close() except requests.exceptions.RequestException: print(xip_file,"may have failed") headers = login(url, payload) continue
score: 2
downvote count: 0
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52428898
answers question: http://stackoverflow.com/q/52428898
type: Answer

http://stackoverflow.com/a/52396261
downvote count: 0
type: AcceptedAnswer
has body: The reason that the outputs are different is that the first example checks whether the strings "a+", "A", or "a" are true, NOT whether GPA is equal to them. For example, if you wrote: if "a": print("Success") "Success" would be printed because "a" is "technically true" (more correctly, it's "truthy"). Contrastingly, if you wrote: if "": print("Success") Nothing would be printed because the empty string is "falsy." Other things that are falsy include 0 and [] (empty list). In your first example: GPA = input('Enter GPA Grade: ') if GPA == 'A+' or 'a+' or 'A' or 'a': print('5.0') 5.0 is always printed because the interpreter simplifies the if code like this: if (GPA == 'A+') or ('a+') or ('A') or ('a') This way, the expression will always evaluate to True because of the truthy strings: if (GPA == 'A+') or True or True or True So no matter what the GPA is, the ors will simplify to just True. The second example works as expected because you are testing each equality case separately. Another shorter solution uses the in operator, which tests if an element is in a list: GPA = input('Enter GPA Grade: ') if GPA in ['a', 'A', 'a+', 'A+']: print('5.0') Even better, using the str.lower() method: GPA = input('Enter GPA Grade: ') if GPA.lower() in ['a', 'a+']: print('5.0')
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52396169
type: Answer
answers question: http://stackoverflow.com/q/52396169
score: 2

http://stackoverflow.com/comment/91573658
comment on: http://stackoverflow.com/a/52312554
score: 0
type: Comment
has text: I get a "keyerror" on the last line. Any suggestions?
type: AnswerComment

http://stackoverflow.com/q/52344305
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91634748
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91641475
answer count: 0
score: 1
tagged with: web-scraping
type: Question
has comment: http://stackoverflow.com/comment/91635418
has title: Trying to encode/decode locations when scraping a website
has comment: http://stackoverflow.com/comment/91635206
has comment: http://stackoverflow.com/comment/91635173
has body: Im trying to scrape a website, and in the url it gets parameters as city and neighborhood. These parameters show in the following encoding: city for example - %E7%E9%F4%E4 neighborhood for example - %E1%FA+%E2%EC%E9%ED I tried looking for what this format is and could not find an answer. Any idea of tools to help me decode/encode this type or what this encoding name even is will be helpful. Note: Im scraping using python Edit &amp; more info: This seems to be because the locations are in hebrew, and a url library is parsig it to make it a valid url. Trying to use python to replicate this action I did: &gt;&gt;&gt; import urllib.parse &gt;&gt;&gt; diction = {"City": "חיפה"} &gt;&gt;&gt; urllib.parse.urlencode(diction) The output was: 'City=%D7%97%D7%99%D7%A4%D7%94' Which seems like a step in the right direction but still not the same encoding that the website itself uses.
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91635623

http://stackoverflow.com/q/52332258
score: 1
has comment: http://stackoverflow.com/comment/91611411
accepted answer: http://stackoverflow.com/a/52332707
upvote count: 1
type: Question
tagged with: database
has comment: http://stackoverflow.com/comment/91611934
has comment: http://stackoverflow.com/comment/91611171
has comment: http://stackoverflow.com/comment/91611272
has comment: http://stackoverflow.com/comment/91612140
has comment: http://stackoverflow.com/comment/91611434
tagged with: sqlite
answer count: 1
tagged with: dataset
has body: So basically, I have two databases. One for "student" and one for "teacher". The teacher database is already saved on the server and the students database will be created by user input. this is for the teacher (also saved separately in a teacher.db file) c.execute(“””CREATE TABLE teacher( ID varchar, name text age integer interest1 varchar interest2 varchar )”””) conn.commit() conn.close() example: c.execute(“INSERT INTO student VALUES (‘Lisa’, ‘35’, ‘spanish’, ‘productivity’) This is the table for the students and the data will be saved in a separate file called student.db c.execute(“””CREATE TABLE student( ID varchar, name text age integer interest1 varchar interest2 varchar )”””) conn.commit() conn.close() And an example of a person looks like this: c.execute(“INSERT INTO student VALUES (‘Max’, ‘23’, ‘spanish’, ‘programming’)” Now, I want to compare the user input, which created the second database. We can see that the value "spanish" is used by both parties. Now I want to create an algorithm that is like this: if the keyword used from the student is equal to one of the datasets in the database of the teachers, I want to print out their name. I tried to work with if then but nothing really worked. It's my second day in learning python please be nice even if this all sounds pretty dumb.
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52332707
tagged with: compare
tagged with: python
has title: How can I compare two SQLlite dataset in Python and search for similarities?
type: AnsweredQuestion

http://stackoverflow.com/comment/91787540
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52390693
has text: The syntax : $ `pip install -U -pre spyder` , replies as `no such option: -p` in the terminal.
score: 0

http://stackoverflow.com/comment/91574371
type: Comment
comment on: http://stackoverflow.com/a/52310062
has text: I am pretty sure that the standard Python implementation with CPython compiles your .py files into .pyc, which then gets interpreted. I do also remember that Java works exactly this way, so since you two know what the other really meant, you can try to share this knowledge
score: 0
type: AnswerComment

http://stackoverflow.com/q/52286114
tagged with: dataframe
tagged with: loops
has answer: http://stackoverflow.com/a/52286622
possible better answer: http://stackoverflow.com/a/52286610
type: AnsweredQuestion
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/52286704
favorite count: 0
type: Question
tagged with: pandas
tagged with: python
has body: I feel like this should be simple but I'm still a bit new to Python and am struggling to figure out what I should do. I'm scraping historical stock data and would like to put them into one excel spreadsheet. It currently only writes out the last stock data. I know it is essentially writing over the dataframe each time it goes through the loop but I'm not sure how to fix it to append dataframes, or write to the end of the excel sheet each time it gets to that spot. Any help would be appreciated. Here is my code: import numpy as np from bs4 import BeautifulSoup import requests import pandas as pd import time symbols = ['WYNN', 'FL', 'TTWO'] myColumnHeaders = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume'] for c in range(len(symbols)): url = 'https://www.nasdaq.com/symbol/'+symbols[c]+'/historical' r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') historicaldata = soup.find('div', {'id': 'quotes_content_left_pnlAJAX'}) data_rows = historicaldata.findAll('tr')[2:] stock_data = [[td.getText().strip() for td in data_rows[a].findAll('td')] for a in range(len(data_rows))] df = pd.DataFrame(stock_data, columns=myColumnHeaders) df.set_index('Date') df['Volume'].str.replace(',','').astype(int) for i in range(5): if i == 0: df[myColumnHeaders[i]] = pd.to_datetime(df[myColumnHeaders[i]], 'coerce') else: df[myColumnHeaders[i]] = pd.to_numeric(df[myColumnHeaders[i]], errors='coerce') df.to_excel('stock data.xlsx',index=False)
tagged with: append
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/52286704
has title: Append Dataframes together in for loop
has answer: http://stackoverflow.com/a/52286610

http://stackoverflow.com/comment/91732527
type: QuestionComment
comment on: http://stackoverflow.com/q/52393542
has text: [This is the closest I could find](https://stackoverflow.com/questions/51499616/how-to-find-channel-name-in-discord-py-async/51499787#51499787) which actually isn't a very good duplicate. I'll write up a proper answer.
score: 0
type: Comment

http://stackoverflow.com/comment/91631347
type: QuestionComment
type: Comment
score: 0
has text: @ShadowRanger The question is open for answer, if you add your comment as an answer, I will accept it.
comment on: http://stackoverflow.com/q/52333540

http://stackoverflow.com/comment/91676192
has text: Thanks for the answer. Isn't numpy written in Python? I see it's all .py files in my installation directory.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52365859
type: Comment

http://stackoverflow.com/q/52421166
has comment: http://stackoverflow.com/comment/91786077
has answer: http://stackoverflow.com/a/52421265
duplicate of: http://stackoverflow.com/q/7207309
upvote count: 2
tagged with: python-2.7
answer count: 2
downvote count: 1
has body: How to run two commands on click on one button ? Example: def commend1(): print "hi" def commend2(): print "hello" #TKinter button = Button(root, commend= ?) I want them to run at the same time
has title: python tkinter, how run two commands on click on one button?
has answer: http://stackoverflow.com/a/52421320
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/5767228
tagged with: python
linked to: http://stackoverflow.com/q/13865009
tagged with: tkinter
score: 1
type: Question
linked to: http://stackoverflow.com/q/7207309
has comment: http://stackoverflow.com/comment/91790072

http://stackoverflow.com/a/52284726
accepted answer of: http://stackoverflow.com/q/52284685
has comment: http://stackoverflow.com/comment/91528060
answers question: http://stackoverflow.com/q/52284685
score: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91517774
downvote count: 0
has body: You're on the right track. I've tried to improve your code. Just use "Type" to determine and assign the sign using np.where, perform groupby and sum, and then re-compute the "Type" column based on the result. v = (df.assign(Quantity=np.where(df.TYPE == '+', df.Quantity, -df.Quantity)) .groupby('Material', as_index=False)'Quantity' .sum()) v.insert(1, 'Type', np.where(np.sign(v.Quantity) == 1, '+', '-')) print (v) Material Type Quantity 0 ABC + 2 1 H4-LAMPE - -7 2 M-12 + 9 Alternatively, you can do this with two groupby calls: i = df.query('TYPE == "+"').groupby('Material').Quantity.sum() j = df.query('TYPE == "-"').groupby('Material').Quantity.sum() # Find the union of the indexes. idx = i.index.union(j.index) # Reindex and subtract. v = i.reindex(idx).fillna(0).sub(j.reindex(idx).fillna(0)).reset_index() # Insert the Type column back into the result. v.insert(1, 'Type', np.where(np.sign(v.Quantity) == 1, '+', '-')) print(v) Material Type Quantity 0 ABC + 2.0 1 H4-LAMPE - -7.0 2 M-12 + 9.0
upvote count: 5
type: Answer

http://stackoverflow.com/comment/91645147
type: AnswerComment
has text: I don’t see df.notna().idxmax() == df.idxmax()
type: Comment
comment on: http://stackoverflow.com/a/52349533
score: 1

http://stackoverflow.com/a/52384556
score: 1
has body: You could also just do: 10. ** np.arange(3,16) that decimal point is important, as without it you will overflow the default int32 dtype for integers
upvote count: 1
answers question: http://stackoverflow.com/q/52383129
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91736768
has text: first occurrence
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52390137

http://stackoverflow.com/a/52294538
score: 12
has comment: http://stackoverflow.com/comment/91544348
type: AcceptedAnswer
has body: list[...] is using indexing, or more accurate subscription syntax, and [start:stop:step] is a slicing. Python 3 passes a slice() object to the subscription call for such cases, there is no :: in the CPython source code as that's not how the language parser would threat that part. Slicing notation allows for defaults, an empty slot between in the start:stop:step parts means that a default is picked, and list[::-1] leaves start and stop at defaults (represented by None, and the step value is set to -1. All this just means you need to remember to separate syntax from operations. You could analyse the syntax by parsing it into an abstract syntax tree, or by disassembling the bytecode generated for it. When you generate an abstract syntax tree for list[::-1] you'll see that the parser separates out the slice part: &gt;&gt;&gt; import ast &gt;&gt;&gt; ast.dump(ast.parse('list[::-1]', '', 'eval').body) # expression body only "Subscript(value=Name(id='list', ctx=Load()), slice=Slice(lower=None, upper=None, step=UnaryOp(op=USub(), operand=Num(n=1))), ctx=Load())" So the Subscript() syntax node operates on the name list, passing in a slice. Producing a disassembly for this operation shows the bytecode used: &gt;&gt;&gt; dis.dis('list[::-1]') 1 0 LOAD_NAME 0 (list) 2 LOAD_CONST 0 (None) 4 LOAD_CONST 0 (None) 6 LOAD_CONST 1 (-1) 8 BUILD_SLICE 3 10 BINARY_SUBSCR 12 RETURN_VALUE Here the BUILD_SLICE() bytecode operation takes the top-three elements from the stack (put there by LOAD_CONST operations at indices 2, 4 and 6) to build a slice() object, which is then passed to the list object (next on the stack) with BINARY_SUBSCR. That last bytecode is the Subscript() operation in the AST, and the bytecodes 2-8 are the Slice() object in the AST. With the bytecode in hand, you can then head over to the Python bytecode evaluation loop to see what those bytecodes actually do. I'll skip BUILD_SLICE, that's just creating a simple slice() object to hold the start, stop and step values. Focu…
has comment: http://stackoverflow.com/comment/91536791
has comment: http://stackoverflow.com/comment/91546124
type: Answer
has comment: http://stackoverflow.com/comment/91543913
upvote count: 12
accepted answer of: http://stackoverflow.com/q/52294373
downvote count: 0
answers question: http://stackoverflow.com/q/52294373
has comment: http://stackoverflow.com/comment/91544431
has comment: http://stackoverflow.com/comment/91538309

http://stackoverflow.com/a/52363018
has comment: http://stackoverflow.com/comment/91670779
type: Answer
accepted answer of: http://stackoverflow.com/q/52360924
has comment: http://stackoverflow.com/comment/91670401
answers question: http://stackoverflow.com/q/52360924
has comment: http://stackoverflow.com/comment/91670427
has comment: http://stackoverflow.com/comment/91670678
has comment: http://stackoverflow.com/comment/91670824
upvote count: 1
has comment: http://stackoverflow.com/comment/91780289
has comment: http://stackoverflow.com/comment/92592924
has comment: http://stackoverflow.com/comment/91670631
has comment: http://stackoverflow.com/comment/91670569
has comment: http://stackoverflow.com/comment/91679944
has comment: http://stackoverflow.com/comment/91779959
has comment: http://stackoverflow.com/comment/91791867
type: AcceptedAnswer
downvote count: 0
has body: You need to deconstruct the array first. Try doing this: mycol.aggregate([ {'$unwind':'$tags'}, {'$match': { 'tags.tag.name':'A A', }}, {'$project': { 'tags.tag.name': 1, '_id': 0 }}, ])
score: 1
has comment: http://stackoverflow.com/comment/91670729

http://stackoverflow.com/comment/91637926
comment on: http://stackoverflow.com/q/52341877
has text: @AzatIbrakov because this code is unnecessarily raise the length of my function.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91517220
type: QuestionComment
has text: First thing to try would be running the command with its full path and extension, and see if the behavior remains the same. Also, are the Python versions identical on both systems?
comment on: http://stackoverflow.com/q/52282630
score: 1
type: Comment

http://stackoverflow.com/comment/91566729
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52309816
type: Comment
has text: @Can'tTell If you need one liner, this will work: `if len(a) > len(b) :(x,y) = (b,a)`. No two lines ;)

http://stackoverflow.com/a/52281061
upvote count: 8
type: Answer
has body: Using drop_duplicates and head: df.drop_duplicates(['id', 'name']).groupby('name').head(3) col1 col2 id name 0 1 2 1 harry 2 3 4 2 harry 3 4 5 3 harry 5 1 9 6 jane 7 3 11 7 jane 9 5 12 8 jane
downvote count: 0
answers question: http://stackoverflow.com/q/52281025
score: 8

http://stackoverflow.com/q/52394620
tagged with: python
has answer: http://stackoverflow.com/a/52435674
type: AnsweredQuestion
type: Question
tagged with: outlook
has body: I am trying to create a script that pulls emails from a certain folder after a certain date. I have a text document, dateLastRan.txt in which the date the last time this script was ran is stored. The data in there will be akin to 2018-09-18. I grab the date from the document and I grab the date of the messages. I was hoping to only output emails that were past the dateLastRan, but my comparison is complaining. And yeah, I am new to python. Thanks for any advice! if(msgDate&gt;dateLastRan): TypeError: unorderable types: datetime.date() &gt; str() I respect the error, but how to get around it? Relevant code below: import win32com.client import datetime import re badUrl = [] outlook = win32com.client.Dispatch("Outlook.Application") namespace = outlook.GetNamespace("MAPI") your_folder = namespace.Folders.Item(1) folder = 'ANY' #change this entry to match a folder found within Inbox inbox = your_folder.Folders['Inbox'].Folders[folder] dateLastRan = '1991-01-01' #used to initialize datelastran todaysDate = (datetime.date.today()) #used to determine where to pick back up startDate = '1991-01-01'#used to initialize startDate #Grab Last Date Ran from file try: with open('lastDateRan.txt', 'r') as infile: for date in infile: dateLastRan = date except Exception as err: print ("lastDateRan.txt not found", '\n') print("Date Last Ran = ", dateLastRan, '\n') all_messages = inbox.Items print("Pulling URLs from folder:",folder,'\n') for message in all_messages: msgDate = message.senton.date() #get date of message print("msg date: ", msgDate) print("datelastran: ",dateLastRan) if(msgDate&gt;dateLastRan): #&lt;&lt;&lt;&lt;&lt;Comparison here print("woot") #do stuff
accepted answer: http://stackoverflow.com/a/52435674
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/52396781
has answer: http://stackoverflow.com/a/52396781
has title: Python3 pull emails past a certain date using MAPI

http://stackoverflow.com/comment/91916566
has text: @SDS sorry my bad, forgot to add import statement here.
type: AnswerComment
comment on: http://stackoverflow.com/a/52424005
type: Comment
score: 1

http://stackoverflow.com/comment/91680667
type: AnswerComment
type: Comment
has text: I think I can also use it for the latter representation in an even easier way, so thanks a lot!! ;)
comment on: http://stackoverflow.com/a/52367330
score: 0

unc
tags question: http://stackoverflow.com/q/52301862
tag name: unc
type: Tag

http://stackoverflow.com/q/52276339
answer count: 1
accepted answer: http://stackoverflow.com/a/52276870
has body: So I have a script that trains on video files, and so have a dataset.py file to work on it. Whenever I am trying to run the script it throws an SyntaxError: invalid syntax error even though I have 1) set the path correctly 2) gave the whole path My folder structure is /home/Videos/project_folder_name/data/train and my script is class Dataset: def __init__(self, folder:/data/train, resize:(int, int), batch_size:int, timesteps:int, windowsteps:int, shift:int, train:bool): self.folder = folder self.resize = resize self.batch_size = batch_size self.timesteps = timesteps self.train = train self.images = sorted(os.listdir(folder + 'images/')) self.labels = open(folder + 'labels.txt').readlines() self.data = self._sliding_window(self.images, shift, windowsteps) This error has been troubling a lot.
favorite count: 0
tagged with: python
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91500655
score: -1
has title: Invalid Syntax while importing dataset
type: Question
has answer: http://stackoverflow.com/a/52276870
has comment: http://stackoverflow.com/comment/91501098
upvote count: 0
has comment: http://stackoverflow.com/comment/91500718
has comment: http://stackoverflow.com/comment/91500261
has comment: http://stackoverflow.com/comment/91500258
has comment: http://stackoverflow.com/comment/91501314
has comment: http://stackoverflow.com/comment/91500229
has comment: http://stackoverflow.com/comment/91500415

http://stackoverflow.com/q/52350171
tagged with: python
type: UnansweredQuestion
score: 0
has title: Python Module 'Requests' and 'Messages Framework'
has body: within a Django web app, I am using the aforementioned modules: Requests to handle HTTP and Messages Framework to collect and render messages Now, when I am calling the following method of the Messages Framework: messages.add_message(request, messages.INFO, 'Hello world.') it gives me an error saying it requires an HTTPRequest... however, 'Requests' does not match. Any ideas? The full error message is: add_message() argument must be an HttpRequest object, not 'module'. The preceding method call for a post is: import requests &lt;some code...&gt; response = requests.post(url=dest, data=self.settings, headers=headers)
tagged with: django
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/91646433
has answer: http://stackoverflow.com/a/52351724
answer count: 1

http://stackoverflow.com/comment/91516232
has text: Also you could flip your conditional around to say if 'False' in row:
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52283830

http://stackoverflow.com/comment/91535138
comment on: http://stackoverflow.com/q/52293611
score: 0
type: Comment
has text: What exactly is your input?
type: QuestionComment

http://stackoverflow.com/q/52360438
has comment: http://stackoverflow.com/comment/91678740
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91666040
favorite count: 0
tagged with: google-cloud-firestore
has body: I'm using python for trying to add a field to more than 750 documents in a firestore collection, but when trying to do this, only my first 55 documents get updated. I'm assuming this happens because of the firestore write limits but don't really get why. COLLECTION STRUCTURE Note: actividades is an array with a size around of 20 elements and each element has only 3 properties. CODE import firebase_admin from firebase_admin import credentials, firestore cred = credentials.Certificate('avancesAccountKey.json') default_app = firebase_admin.initialize_app(cred) db = firestore.client() count = 0 avances = db.collection('avances').get() for e in avances: db.collection('avances').document(e.id).update({ 'vigente': False }) count += 1 print(count) # count is 55 when trying to update, 757 otherwise What is exactly happening and how I can solve this?
accepted answer: http://stackoverflow.com/a/52414780
tagged with: python
type: AnsweredQuestion
upvote count: 1
type: Question
tagged with: firebase
score: 1
tagged with: firebase-admin
linked to: http://stackoverflow.com/q/6260089
has answer: http://stackoverflow.com/a/52414780
has title: Why aren't all my documents updated in Firestore?

http://stackoverflow.com/q/52386915
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52387141
has title: How to get the difference between two csv by Index using Pandas
type: Question
accepted answer: http://stackoverflow.com/a/52390547
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/91718714
has body: Need to get the difference between 2 csv files, kill duplicates and Nan fields. I am trying this one but it adds them together instead of subtracting. df1 = pd.concat([df,cite_id]).drop_duplicates(keep=False)'id','website' df is main dataframe cite_id is dataframe that has to be subtracted.
answer count: 3
has answer: http://stackoverflow.com/a/52390547
tagged with: python
possible better answer: http://stackoverflow.com/a/52387970
has answer: http://stackoverflow.com/a/52387970

virtualenv
tags question: http://stackoverflow.com/q/52346958
tags question: http://stackoverflow.com/q/52325639
tags question: http://stackoverflow.com/q/52337838
tags question: http://stackoverflow.com/q/52428467
tag name: virtualenv
tags question: http://stackoverflow.com/q/52378890
tags question: http://stackoverflow.com/q/52370988
tags question: http://stackoverflow.com/q/52404529
type: Tag

http://stackoverflow.com/q/52308646
upvote count: 1
tagged with: mlxtend
type: Question
has title: Passing parameters to the fit method of underlying classifiers via StackingCVClassifier in mlxtend package
has body: I'm using StackingCVClassifier (from the mlxtend package) in Python and one of my classifiers is an XGBoostClassifier instance and I'm trying to pass a parameter (early_stopping_rounds or simply verbose) to its fit method via the fit method of the StackingCVClassifier object. The fit method does not seem to support this. The fit_transform method has a fit_params argument. But when I pass my parameter (e.g. **{'XGB_clf__early_stopping_rounds': 20}) it throw the following error: fit() got an unexpected keyword argument 'XGB_clf__early_stopping_rounds. Is this not supported? Or did I miss something? Here is a sketch of what I'm trying to do: XGB_clf = XGBClassifier() other_clf = LogisticRegression() stacked_clf = StackingCVClassifier(classifiers = [XGB_clf, other_clf], meta_classifier = LogisticRegression(), cv=2) # trying to pass early_stopping_rounds to XGB_clf.fit stacked_clf.fit(X_train, y_train, **{XGB_clf__early_stopping_rounds = 50})
downvote count: 0
answer count: 1
score: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52379642

http://stackoverflow.com/a/53721930
score: 1
has body: I think I found the best solution (at least for my application but probably for other people as well) which is to create a package (module) of the class or set of functions that is used by different project. Then just install the package (module) that you have built. I simply followed this guide which works great. https://packaging.python.org/tutorials/packaging-projects/ Please note: You do not have to upload the code to github, it is also possible to just have an offline version of your package. Cheers!
answers question: http://stackoverflow.com/q/52424811
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52424811
upvote count: 1

http://stackoverflow.com/comment/91620017
comment on: http://stackoverflow.com/q/52335995
type: Comment
type: QuestionComment
has text: No, the true parent folder is `aws-sfn-tutorial` --> `aws-sfn-tutorial/rkstr8/....`
score: 0

http://stackoverflow.com/q/52378813
has answer: http://stackoverflow.com/a/52378983
tagged with: python
has comment: http://stackoverflow.com/comment/91702194
has comment: http://stackoverflow.com/comment/91702231
type: UnansweredQuestion
score: 0
tagged with: loops
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91702081
has body: Here are my two nested loops in Python. But why is it printing 4 times? links=["/wordpress/wp-admin/install.php", "/wp-admin/install.php"] f=open('list.txt', 'r').read().split('\n') for sub_link in range(len(links)): sub_link= links[sub_link] for line in f: line = line.split('/') print(line[2]+sub_link) While I only want it printing lenth of my "List.txt" file and List.txt has only two lines.
tagged with: nested-loops
answer count: 2
has title: Why It Is Printing 4 Times?
favorite count: 0
has comment: http://stackoverflow.com/comment/91702044
has answer: http://stackoverflow.com/a/52378986

http://stackoverflow.com/a/52426822
type: Answer
answers question: http://stackoverflow.com/q/52426777
has body: def f(input1,input2): return input2[:2]+input1[2:]+' '+input1[:2]+input2[2:]
has comment: http://stackoverflow.com/comment/91797164
has comment: http://stackoverflow.com/comment/91796876
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52426777

http://stackoverflow.com/a/52424823
downvote count: 0
answers question: http://stackoverflow.com/q/52424527
type: Answer
has comment: http://stackoverflow.com/comment/91792694
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91799493
has comment: http://stackoverflow.com/comment/91799471
has body: Are you trying to run the code exactly as it is in your question? If so, some problems that come to mind: Indentation: Every line after "def..." should be indented, if you want it to be part of the function. Multiple values in df: You start with it being a filename, but then you change its value in the middle of your loop, so that it would be different when it goes back to the top of the loop. Using df as multiple types of values. Creating it once, as an empty list, and appending it iteratively, would seem to better serve your purpose. Try something like this: def show(file_name): start = time() c=0 df = [] for chuck in pd.read_csv('../input/{}.csv'.format(file_name), chunksize=50000): df.append(chuck, ignore_index=True) c+=1 print (c) print('used {:.2f} s'.format(time()-start)) print(df.shape) df.head()

http://stackoverflow.com/comment/91583785
type: Comment
has text: thanks! now it works!
comment on: http://stackoverflow.com/a/52318223
type: AnswerComment
score: 0

http://stackoverflow.com/a/52277740
type: Answer
answers question: http://stackoverflow.com/q/52277564
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52277564
type: AcceptedAnswer
has body: You are not resetting your counter when you encounter a y character, and you should only append to total_char_list if there was at least one x character counted by the time you find a y character (y characters could be duplicated too): total = 0 while i &lt; len(string): if string[i] == "x": total += 1 if string[i] == "y": if total: total_char_list.append(total) total = 0 i = i + 1 Next, when the loop ends and total is not zero, you need to append that value too, or you won't be counting 'x' characters at the end of the sequence: while ...: # ... if total: # x characters at the end total_char_list.append(total) Next, you really want to use a for loop to loop over a sequence. You are given the individual characters that way: total = 0 for char in string: if char == 'x': total += 1 if char == 'y': if total: total_charlist.append(total) total = 0 if total: # x characters at the end total_char_list.append(total) You can make this faster with itertools.groupby(): from itertools import groupby def count_squences(string): return [sum(1 for _ in group) for char, group in groupby(string) if char == 'x'] groupby() divides up an iterable input (such as a string) into separate iterators per group, where a group is defined as any consecutive value with the same key(value) result. The default key() function just returns the value, so groupby(string) gives you groups of consecutive characters that are the same. char is the repeated character, and sum(1 for _ in group) takes the length of an iterator. You can then make it more generic, and count all groups: def count_all_sequences(string): counts = {} for char, group in groupby(string): counts.setdefault(char, []).append(sum(1 for _ in group)) return counts The same can be done with a regular expression: import re def count_all_sequences(string): counts = {} # (.)(\1*) finds repeated characters; (.) matching one, \1 matching the same # This gives us (first, rest) tuples, so len(rest) + 1 is the total length for char, group in re.fi…
downvote count: 0
score: 3

xattr
tags question: http://stackoverflow.com/q/52403922
type: Tag
tag name: xattr

http://stackoverflow.com/q/52305689
has comment: http://stackoverflow.com/comment/91558718
tagged with: scrapy
type: Question
has answer: http://stackoverflow.com/a/52305768
linked to: http://stackoverflow.com/q/34618340
downvote count: 0
has title: Terminate scrapy and keep output file
answer count: 1
score: 1
has body: Made a coding mistake, and my spdier is likely running in a loop. How can I terminate the spider and save the output json file. My experience was forced termination will lead to no output file being saved. Any suggestion? Can pkill save the output file? https://stackoverflow.com/a/46727707/7870384
favorite count: 0
has comment: http://stackoverflow.com/comment/91558756
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/91694024
has text: Your question is very broad, For a start, in one example you have 1 object and the other you have 2.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52374488
score: 0

http://stackoverflow.com/a/52420399
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92309362
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52419831
answers question: http://stackoverflow.com/q/52419831
has comment: http://stackoverflow.com/comment/92333910
has body: I would do something like this : new_data = [] for row in data: if 'contents' in row: for content in row['contents']: new_dict = dict(row) del new_dict['contents'] for key, value in content.items(): new_dict['content_{}'.format(key)] = value new_data.append(new_dict) else: new_data.append(row) Be aware that I create one line of dataframe per element in 'contents'. So you will have 9 lines corresponding to the elements in data[0]. pd.DataFrame.from_dict(new_data) Basically you have two ways to convert a nested dict to a 2D dataframe : you can keep one line per element of your list but you will need to add a lot of columns (one for each element of dicts contained in 'contents', numbers of columns may vary a lot and become a pain in the neck) or by adding one line per element in 'contents'. I think the last one suits well for your case.
score: 1

http://stackoverflow.com/a/52411312
has comment: http://stackoverflow.com/comment/91766367
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52411230
has body: You can do like this, list(itertools.chain.from_iterable((i for i in range(j+1)) for j in range(3))) # [0, 0, 1, 0, 1, 2] range(j) is not won't give your desired output. You have to use range(j+1) You could be done like this without using the iterator. In [58]: list(i for j in range(3) for i in range(j+1)) Out[58]: [0, 0, 1, 0, 1, 2]
type: Answer
downvote count: 0

http://stackoverflow.com/q/52324464
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52324643
has answer: http://stackoverflow.com/a/52324998
tagged with: python
has body: New to stackoverflow and also programming, I'm from statistics background below is the implementation of KNN algorithm. Getting an error TypeError: unsupported operand type(s) for -: 'str' and 'str'. These are the other errors I got. Thank you in advance for answering. File "knn.py", line 78, in main() File "knn.py", line 71, in main neighbors = getNeighbors(trainingSet, testSet[x], k) File "knn.py", line 33, in getNeighbors dist = euclideanDistance(testInstance, trainingSet[x], length) File "knn.py", line 26, in euclideanDistance distance += pow((instance1[x] - instance2[x]), 2) import csv import random import math import pandas import numpy def loadDataset(filename, split, trainingSet=[] , testSet=[]): filename = 'data1.csv' raw_data = open(filename, 'rt') reader = csv.reader(raw_data, delimiter=',', quoting=csv.QUOTE_NONE) dataset = list(reader) for x in range(len(dataset)-1): for y in range(4): dataset[x][y] = float(dataset[x][y]) if random.random() &lt; split: trainingSet.append(dataset[x]) else: testSet.append(dataset[x]) def euclideanDistance(instance1, instance2, length): distance = 0 for x in range(length): distance += pow((instance1[x] - instance2[x]), 2) return math.sqrt(distance) def getNeighbors(trainingSet, testInstance, k): distances = [] length = len(testInstance)-1 for x in range(len(trainingSet)): dist = euclideanDistance(testInstance, trainingSet[x], length) distances.append((trainingSet[x], dist)) distances.sort(key=operator.itemgetter(1)) neighbors = [] for x in range(k): neighbors.append(distances[x][0]) return neighbors def getResponse(neighbors): classVotes = {} for x in range(len(neighbors)): response = neighbors[x][-1] if response in classVotes: classVotes[response] += 1 else: classVotes[response] = 1 sortedVotes = sorted(classVotes.iteritems(), key=operator.itemgetter(1), reverse=True) return sortedVotes[0][0] def getAccuracy(testSet, predictions): correct = 0 for x in range(len(testSet)): if testSet[x][-1] == predictions[x]: correct += 1 …
score: 1
has comment: http://stackoverflow.com/comment/91596205
upvote count: 1
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/91596293
has title: Getting error while implementing KNN algorithm
tagged with: numpy
answer count: 2
tagged with: pandas

http://stackoverflow.com/a/52354748
has comment: http://stackoverflow.com/comment/91654865
downvote count: 0
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52354096
answers question: http://stackoverflow.com/q/52354096
upvote count: 1
has body: you can make conditions to filter data,if you want just preceding rows match to condition. ind= 2 col ='C3' # ".loc[np.arange(ind+1)]" creates indexes till preceding row, so rest of matching conditions can be ignored df.loc[df.loc[ind][col] == df[col]].loc[np.arange(ind+1)].dropna() Out: C1 C2 C3 0 1 2 A 1 3 4 A 2 5 4 A appying on other column ind= 2 col ='C2' df.loc[df.loc[ind][col] == df[col]].loc[np.arange(ind+1)].dropna() Out: C1 C2 C3 1 3.0 4.0 A 2 5.0 4.0 A
type: Answer
has comment: http://stackoverflow.com/comment/91654757

http://stackoverflow.com/a/52340666
answers question: http://stackoverflow.com/q/52277797
type: AcceptedAnswer
upvote count: 2
type: Answer
has body: You could subclass LogFormatterExponent to format the ticks with "10\textsuperscript{x}" where x is the exponent. This would not use math mode tex, i.e. no $ signs around the text, and therefore would use the textfont specified in the preamble (in this case the font without serifs). import matplotlib as mpl from matplotlib.ticker import LogFormatterExponent mpl.use('pgf') pgf_with_latex = { "pgf.texsystem": "pdflatex", "font.family": "sans-serif", "text.usetex": False, "pgf.preamble": [ r"\usepackage[utf8x]{inputenc}", r"\usepackage{tgheros}", # TeX Gyre Heros sans serif r"\usepackage[T1]{fontenc}" ] } mpl.rcParams.update(pgf_with_latex) import matplotlib.pyplot as plt class LogFormatterTexTextMode(LogFormatterExponent): def __call__(self, x, pos=None): x = LogFormatterExponent.__call__(self, x,pos) s = r"10\textsuperscript{{{}}}".format(x) return s fig = plt.figure(figsize=[3, 2]) ax = fig.add_subplot(111) ax.set_yscale("log") ax.yaxis.set_major_formatter(LogFormatterTexTextMode()) ax.minorticks_off() ax.set_xlabel("sans-serif font label") ax.set_ylabel("text mode tex label") plt.gca().set_ylim([0.01, 20000]) plt.gcf().tight_layout() plt.savefig('{}.pdf'.format("test"))
score: 2
has comment: http://stackoverflow.com/comment/91650381
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52277797

http://stackoverflow.com/comment/91708433
score: 0
type: AnswerComment
has text: Converting to `list` is a clever "hack" to prevent `tuple` from just returning the input, but you might add _why_ tuple behaves like this in the first place.
type: Comment
comment on: http://stackoverflow.com/a/52382045

http://stackoverflow.com/comment/91680432
has text: You mean you want to be notified when your Python process is having trouble allocating memory? Or you want the actual iOS-specific memory pressure warning which is system-wide?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52367674

http://stackoverflow.com/comment/91682564
type: AnswerComment
comment on: http://stackoverflow.com/a/52368668
type: Comment
score: 1
has text: Apologies, I misunderstood and have amended my answer with the correct answer.

http://stackoverflow.com/a/52390689
has comment: http://stackoverflow.com/comment/91729376
has comment: http://stackoverflow.com/comment/91729468
accepted answer of: http://stackoverflow.com/q/52390450
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52390450
has comment: http://stackoverflow.com/comment/91726568
type: Answer
has comment: http://stackoverflow.com/comment/91729418
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91727051
has body: Python is not a statically typed language, so the answer to: How can I enforce var2 to be of type TypeX? is you don't. Of course, you can type-check something, but the Python interpreter won't do it for you, you'll need to explicitly write this rule on your code programatically. As to the question of how the following: public class ClassA { public byte var1; public TypeX var2; } public class TypeX { public UInt16 num1; public UInt32 num2; } translates to Python, the answer is as simple as: # You need to explicitly initialize the variables to their correspondent default values class ClassA(object): def __init__(self): self.var1 = bytes() # or b'' self.var2 = None class TypeX(object): def __init__(self): self.num1 = int() # or 0 self.num2 = int() # or 0

http://stackoverflow.com/q/52401252
tagged with: pymssql
possible better answer: http://stackoverflow.com/a/60295789
type: Question
has answer: http://stackoverflow.com/a/60295789
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/52401546
downvote count: 0
has body: I had been working with pyodbcfor database connection in windows envirnment and it is working fine but now I want to switch to pymssql so that it is easier to be deployed to Linux machine as well. But I am getting this error: (20009, b'DB-Lib error message 20009, severity 9:\nUnable to connect: Adaptive Server is unavailable or does not exist (localhost:1433)\nNet-Lib error during Unknown error (10060)\n') My connection code for using both pyodbc and pymssql is: import pyodbc import pymssql def connectODSDB_1(): conn_str = ( r"Driver={SQL Server};" r"Server=(local);" r"Database=populatedSandbox;" r"Trusted_Connection=yes;" ) return pyodbc.connect(conn_str) def connectODSDB_2(): server = '(local)' database = 'populatedSandbox' conn = pymssql.connect(server=server, database=database) return conn What could be the problem? And solution?
tagged with: python
has title: Database connection failed for local MSSQL server with pymssql
favorite count: 0
accepted answer: http://stackoverflow.com/a/52401546
tagged with: database-connection
type: AnsweredQuestion
upvote count: 5

http://stackoverflow.com/comment/91531953
has text: Try this one http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVR.html
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52291971

http://stackoverflow.com/q/52419009
has answer: http://stackoverflow.com/a/52419034
score: -1
has comment: http://stackoverflow.com/comment/91781299
has comment: http://stackoverflow.com/comment/91781336
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: invalid character in identifier for inputting values and getting an equation
has comment: http://stackoverflow.com/comment/91781357
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/43595699
downvote count: 2
upvote count: 1
type: Question
duplicate of: http://stackoverflow.com/q/43595699
has body: I am trying to solve the equation of circle in Python. I am running the code below using package cmath. I am getting the error that there is an invalid character in the equation y = k + cmath.sqrt(r − (x−h)k) ^ SyntaxError: invalid character in identifier import cmath print('Solve the circle equation: y= sqrt(- h*x - k*y - r - x**2)') r = float(input('Please enter r : ')) h = float(input('Please enter h : ')) k = float(input('Please enter k : ')) y = k + cmath.sqrt(r − (x−h)k) print('The circle equation is "y = k + cmath.sqrt(r − (x−h)k)"'.format(y))

http://stackoverflow.com/comment/91785118
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52420899
has text: I simulated them with time.sleep() function because this is not the important part of the question.

http://stackoverflow.com/a/52306831
answers question: http://stackoverflow.com/q/52306344
score: 1
has body: I think python time module can help import time a = "00:00:00 1971" a = time.mktime(time.strptime(a,"%H:%M:%S %Y")) ClockTime1 = input('Enter clock two timie (in military time) in the format HH:MM:SS , it has to be in this format in order to function correctly :') ClockTime2= input('Enter clock one time (in military time) in the format HH:MM:SS , it has to be in this format in order to function correctly :') ClockTime1+=" 1971" ClockTime2+=" 1971" ClockTime1 = time.mktime(time.strptime(ClockTime1,"%H:%M:%S %Y")) ClockTime2 = time.mktime(time.strptime(ClockTime2,"%H:%M:%S %Y")) print(time.strftime("%H:%M:%S", time.localtime(ClockTime1-a+ClockTime2-a+a)))
has comment: http://stackoverflow.com/comment/91577311
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91588365
downvote count: 0

http://stackoverflow.com/q/52313836
answer count: 0
has comment: http://stackoverflow.com/comment/91578861
has body: I am learning to code CNN with keras. The tutorial I am following is based on this tutorial, and everything works pretty well. But, I played a bit with this CNN, tried to optimize it, and try to find it's limit. It appears that when I present a picture of something that is not a cat or a dog, let's say a chair, the CNN still tells me the picture is a dog. Since the model is trained only on dogs and cats images, it can only tell me if if the image is a dog or cat. Thus I decided to use model.predict_proba in order to get an accurate probability, so I wanted the model to tell me, in the case of a picture of chair, "There is 7% probabilty this is a dog". But the model gives me [[0.]], in other words, the model is 100% sure a chair is a dog. Then, I started modifying the CNN, and I put 2 output neurones in the fully connected layers, in order to have the probabilty that it's a cat, and the probabilty that it's a dog. I used class_mode='categorical' instead of class_mode='binary' in the data preparation, to be sure it works with the 2 output neurones, and I didn't use softmax, to be sure that I don't have probaDog + probaCat = 1, because, if the input is a picture of something else than a dog or a cat, I don't want to obtain false probabilities... What I wanted to see, when I typed model.predict_proba("iamge_path"), was something like that [[0.213 0.639]]. Then I wanted to be able to define some conditions and use them like that: if result[0][0] &lt; 0.5 AND result[0][1] &lt; 0.5: print("This is neither a dog nor a cat!") elif result[0][0] &gt; result[0][1] + 0.5: print("This is a dog!") elif result[0][1] &gt; result[0][0] + 0.5: print("This is a cat!") else: print("This is neither a dog nor a cat!") But instead, every single answer I get is [[0. 1.]] or [[1. 0.]]. I tried training my CNN on only 1 epoch. I presented 13 pictures of cat to that CNN, and it told me 7 times it was dogs. But it was 100% percent sure it was dogs... So, how do we get true probabilty? Here is m…
has comment: http://stackoverflow.com/comment/91580606
type: Question
has comment: http://stackoverflow.com/comment/91581465
score: 0
tagged with: deep-learning
tagged with: image-recognition
has comment: http://stackoverflow.com/comment/91592281
tagged with: keras
has title: Python Keras Image Recognition obtain accurate probabiliy(Not [[0.]] or [[1.]])
type: UnansweredQuestion
tagged with: python
tagged with: conv-neural-network

http://stackoverflow.com/a/52354052
type: AcceptedAnswer
downvote count: 0
has body: We can leverage np.lib.stride_tricks.as_strided based scikit-image's view_as_windows to get sliding windows. More info on use of as_strided based view_as_windows. from skimage.util.shape import view_as_windows # Get sliding windows as views w = view_as_windows(image_array,(1,size,size))[...,0,:,:] # Index with advanced-indexing into windows array and # assign into it, thus reassigning into input array directly being views w[np.arange(len(x_array)),x_array,y_array] = 0 Sample run Setup inputs - In [60]: image_array # input array Out[60]: array([[[54, 57, 74, 77, 77], [19, 93, 31, 46, 97], [80, 98, 98, 22, 68], [75, 49, 97, 56, 98]], [[91, 47, 35, 87, 82], [19, 30, 90, 79, 89], [57, 74, 92, 98, 59], [39, 29, 29, 24, 49]], [[42, 75, 19, 67, 42], [41, 84, 33, 45, 85], [65, 38, 44, 10, 10], [46, 63, 15, 48, 27]]]) In [68]: size Out[68]: 2 # x and y starting indices for 0s assignments In [65]: x_array Out[65]: array([1, 0, 1]) In [66]: y_array Out[66]: array([2, 2, 0]) Use proposed solution - In [62]: w = view_as_windows(a,(1,size,size))[...,0,:,:] In [63]: w[np.arange(len(x_array)),x_array,y_array] = 0 In [64]: image_array # verify Out[64]: array([[[54, 57, 74, 77, 77], # start at (1,2) [19, 93, 0, 0, 97], [80, 98, 0, 0, 68], [75, 49, 97, 56, 98]], [[91, 47, 0, 0, 82], # start at (0,2) [19, 30, 0, 0, 89], [57, 74, 92, 98, 59], [39, 29, 29, 24, 49]], [[42, 75, 19, 67, 42], # start at (1,0) [ 0, 0, 33, 45, 85], [ 0, 0, 44, 10, 10], [46, 63, 15, 48, 27]]])
type: Answer
accepted answer of: http://stackoverflow.com/q/52353944
upvote count: 1
answers question: http://stackoverflow.com/q/52353944
score: 1

http://stackoverflow.com/a/52355480
has body: You can rank the time column and then reshape a['time1'] = a.groupby('user').time.rank(method = 'dense', ascending = False).map({1.0 : 'top1_app', 2.0 : 'top2_app'}) a = a.dropna().pivot('user', 'time1', 'app') a.columns.name = None a.reset_index(inplace = True) user top1_app top2_app 0 1 s p 1 2 k p
accepted answer of: http://stackoverflow.com/q/52354832
has comment: http://stackoverflow.com/comment/91670343
score: 3
answers question: http://stackoverflow.com/q/52354832
upvote count: 3
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/a/52334736
type: Answer
accepted answer of: http://stackoverflow.com/q/52326369
answers question: http://stackoverflow.com/q/52326369
score: 0
has body: When I first read the question, I immediately thought piping the output would work. Check this link out to get a better idea: Linux Questions Piping If this doesn't work, I do think writing your output to a file and reading it with your python script would get the job done.
type: AcceptedAnswer

http://stackoverflow.com/comment/126201885
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52302468
has text: It worked. Should be marked as a solution.

http://stackoverflow.com/comment/91660150
type: AnswerComment
has text: Not sure this is necessarily true, but ok I'll add the timing. It is still gonna be way faster
type: Comment
comment on: http://stackoverflow.com/a/52357688
score: 0

http://stackoverflow.com/a/53790964
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52413000
has body: I have reproduced the bug where Win10 and Python 3.7.0 cause problems. FWIW, if you completely uninstall Python 3.7.0 (including manually deleting your Windows installation directory tree), then install Python 3.7.1, you should not have this problem with Windows 10.

extrapolation
tags question: http://stackoverflow.com/q/52378090
tag name: extrapolation
type: Tag

http://stackoverflow.com/comment/91770816
has text: Oh you are right, it will always have 3 characters at the end, I was thinking your index was based off the width of the numbers but yes it will always be that index
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52413457
type: AnswerComment

http://stackoverflow.com/q/52349625
favorite count: 0
has body: The PDF I have is: $$ P(\varepsilon) = \frac{1}{4k} \mathrm{sech}^2 \frac{\varepsilon}{2k}$$ CDF: $$ CDF(\varepsilon) = \frac{\tanh(\frac{\varepsilon}{2k})}{2} $$ and Inverse CDF: $$ CDF^{-1}(c) = \frac{c}{2\tanh^{-1}(2k_BT)} $$ Now what should I do to generate N samples, with my PDF P(\varepsilon) of given k? Here is what I have so far: import numpy as np def sampleConduction(N, kT): for i in range(N): c = np.random.random() list = [c] print('list=',list) g = np.column_stack(list) print('g=',g) d = np.arctanh(2*list)+2*kT return d sampleConduction(3,0.1) The result of this code is: list= [0.7687170402304889] list= [0.24759083266582882] list= [0.18334770166799108] g= [[0.1833477]] array([0.38544466, 0.38544466]) # d I wanted to combine the 3 lists into one, but failed by using np.column_stack(). What should I try next? Thanks a lot!
has comment: http://stackoverflow.com/comment/91645014
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: How to generate samples using Inverse Transform Sampling with a given customized PDF in Python?
score: 1
has comment: http://stackoverflow.com/comment/91647067
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91646098
tagged with: cdf
has comment: http://stackoverflow.com/comment/91647091
downvote count: 0
has comment: http://stackoverflow.com/comment/91647839
linked to: http://stackoverflow.com/q/22447797
tagged with: data-science
has comment: http://stackoverflow.com/comment/91645227
tagged with: http://stackoverflow.com/tag/pdf

http://stackoverflow.com/q/52396477
linked to: http://stackoverflow.com/q/24644656
downvote count: 0
has body: Using the following code: predictions = pd.DataFrame([x6,x5,x4,x3,x2,x1]) print(predictions) Prints the following in the console: 0 0 782.367392 1 783.314159 2 726.904744 3 772.089101 4 728.797342 5 753.678877 How do I print predictions without row (0-5) or column (0) indexes? In R the code would look like: print(predictions, row.names = FALSE)
has comment: http://stackoverflow.com/comment/91737777
duplicate of: http://stackoverflow.com/q/24644656
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/91737805
has comment: http://stackoverflow.com/comment/91737734
score: 10
favorite count: 0
has comment: http://stackoverflow.com/comment/91737773
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91737721
has answer: http://stackoverflow.com/a/52396487
has answer: http://stackoverflow.com/a/52396506
has answer: http://stackoverflow.com/a/52396530
has title: Printing a pandas dataframe without row number/index
upvote count: 10
linked to: http://stackoverflow.com/q/52396315
type: Question

http://stackoverflow.com/comment/91506132
type: AnswerComment
comment on: http://stackoverflow.com/a/52278988
type: Comment
score: 0
has text: You implicitly create an object when using print, but if you keep the line `a.sort()` no object is being created not even a none object. If you don't try to name or somewhat use the result of `sort()` no object is created.

http://stackoverflow.com/comment/115229896
comment on: http://stackoverflow.com/q/52281840
score: 0
type: Comment
type: QuestionComment
has text: I see the same issue on macOS 10.15.7. `brew install adoptopenjdk11` gives `Error: adoptopenjdk/openjdk/adoptopenjdk11: /Users/xxx/Library/Caches/Homebrew/downloads/46eb376eab731542b0487be7fb6281dd11b32cf1ef7f5d8b0e092c99416c66b0--OpenJDK11U-jdk_x64_mac_hotspot_11.0.9.1_1.pkg was not quarantined properly.`

http://stackoverflow.com/q/52409641
score: 0
has answer: http://stackoverflow.com/a/52435565
upvote count: 1
answer count: 1
downvote count: 1
has body: When I set the hoverinfo of a Plotly object to "x+text", I can modify what is shown in the hover tooltip using the hovertext attribute. I haven't found a way to modify the hover text along the x-axis though. I would like to modify it to be more than the default x-axis value at that location.
favorite count: 0
tagged with: python
type: UnansweredQuestion
has title: Is it possible to customize Plotly x-axis hoverinfo in Python?
type: Question
tagged with: plotly

http://stackoverflow.com/a/52293234
has comment: http://stackoverflow.com/comment/91536709
has comment: http://stackoverflow.com/comment/91542836
has comment: http://stackoverflow.com/comment/91535419
has comment: http://stackoverflow.com/comment/91540980
has comment: http://stackoverflow.com/comment/91599943
has body: Updated tested solution: import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders import time import os msg = MIMEMultipart() msg['From'] = EMAIL_FROM msg['To'] = ", ".join(RECIPIENT_LIST) msg['Subject'] = 'Louisiana Contractors List' #email content message = """&lt;html&gt; &lt;body&gt; Attached is the Louisiana Contractors Spreadsheet. &lt;br&gt;&lt;br&gt; Let me know if you have any questions &lt;/body&gt; &lt;/html&gt; """ msg.attach(MIMEText(message, 'html')) files = [ 'C:/Users/rkrouse/Downloads/search-results.csv', 'C:/Users/rkrouse/Downloads/search-results(1).csv', 'C:/Users/rkrouse/Downloads/search-results(2).csv'] for a_file in files: attachment = open(a_file, 'rb') file_name = os.path.basename(a_file) part = MIMEBase('application','octet-stream') part.set_payload(attachment.read()) part.add_header('Content-Disposition', 'attachment', filename=file_name) encoders.encode_base64(part) msg.attach(part) #sends email smtpserver = smtplib.SMTP(EMAIL_SERVER, EMAIL_PORT) smtpserver.sendmail(EMAIL_FROM, RECIPIENT_LIST, msg.as_string()) smtpserver.quit() As you can see you need to specify the filename in the base64 encoding. Also you are iterating the files three time. A for loop is used to go through a list, set, array, etc. One for loop (as all attachments are in one list) should be enough.
accepted answer of: http://stackoverflow.com/q/52292971
has comment: http://stackoverflow.com/comment/91538660
has comment: http://stackoverflow.com/comment/91536263
has comment: http://stackoverflow.com/comment/91538085
upvote count: 5
has comment: http://stackoverflow.com/comment/91564369
has comment: http://stackoverflow.com/comment/91588135
has comment: http://stackoverflow.com/comment/91540945
score: 5
has comment: http://stackoverflow.com/comment/91536420
answers question: http://stackoverflow.com/q/52292971
has comment: http://stackoverflow.com/comment/91544236
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/52364601
has comment: http://stackoverflow.com/comment/91673554
favorite count: 0
has comment: http://stackoverflow.com/comment/91674127
has comment: http://stackoverflow.com/comment/91673643
tagged with: bash
type: Question
tagged with: python-3.x
tagged with: subprocess
score: 5
tagged with: python
has comment: http://stackoverflow.com/comment/91673632
has comment: http://stackoverflow.com/comment/91673646
answer count: 1
has comment: http://stackoverflow.com/comment/91673810
has answer: http://stackoverflow.com/a/52364965
upvote count: 5
has title: Passing List to subprocess.run
has body: i've got a script, that contains a list - the list is just some args that I want to pass to subprocess.run like this commands = ["bash command 1", "bash command 2",..] here is my code commands = ["bash command 1", "bash command 2",..] process = subprocess.run([commands], stdout = subprocess.PIPE, shell = True) how can I pass a list to my subprocess.run? this is the Traceback Traceback (most recent call last): File "./retesting.py", line 18, in &lt;module&gt; process = subprocess.run([commands], stdout = subprocess.PIPE, shell = True) File "/usr/lib/python3.5/subprocess.py", line 383, in run with Popen(*popenargs, **kwargs) as process: File "/usr/lib/python3.5/subprocess.py", line 676, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.5/subprocess.py", line 1221, in _execute_child restore_signals, start_new_session, preexec_fn) TypeError: Can't convert 'list' object to str implicitly I Have no idea what I'm doing wrong and I tried all sorts of things, so I'd appreciate really any help
has comment: http://stackoverflow.com/comment/91673686
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91673852

http://stackoverflow.com/q/52287168
has body: I need to develop a simple interface for Stroop test using Python, but I don't know how to start it in Python. The interface would be like: 10 seconds in a blank screen, the 10 seconds with a colored word on the center of the screen. This would repeat like 10 times, then finish the application. The problem is: I don't know if I have to use Tkinter + anothe lib (timed events), or if Tkinter provides the methods to use timed events. Could anyone enlight me,please? Thank you very much!
downvote count: 1
tagged with: python
has title: Sequentially timed events using Python/Tkinter
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/52287392
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52287392
type: Question
upvote count: 1
tagged with: user-interface
answer count: 1
favorite count: 0
score: 0

http://stackoverflow.com/comment/91744069
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/180329/discussion-between-cloc-and-smit-kamal).
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52398250

http://stackoverflow.com/a/52284165
has comment: http://stackoverflow.com/comment/91517560
has comment: http://stackoverflow.com/comment/91517876
answers question: http://stackoverflow.com/q/52284076
has comment: http://stackoverflow.com/comment/91516930
accepted answer of: http://stackoverflow.com/q/52284076
has comment: http://stackoverflow.com/comment/91516889
score: 0
has comment: http://stackoverflow.com/comment/91516761
has comment: http://stackoverflow.com/comment/91516796
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/91516912
has body: The problem is that you are putting the plot command outside the for loop and so the 4 curves will not be plotted. Moreover some of your variables needed to be redefined. Following is the working solution (without the if else statements): import numpy as np import matplotlib.pyplot as plt # r, a, 5 gamma values and kt here fig = plt.figure(figsize=(8, 6)) for n in a: i = 0 E=[] B=[] alpha=n*(np.pi/180) while i&lt;360: # Code here . . . Energy= (gamma_sa*A_sa)+(gamma_pa*A_pa)+(gamma_sw*A_sw)+(gamma_pw*A_pw)-(np.pi*r**2*gamma_aw*np.sin(alpha)**2) orientation=i # Mind the indent. Should be outside elif i=i+0.1 E.append(Energy/kt) B.append(orientation) plt.plot(B,E, label='$%d^o$'%n) # Mind the indentation here. Should be outside the while loop plt.title('Change of surface energy with rotation') plt.grid (axis='both') plt.xlabel(r'$90^0 $ - $\beta $') plt.ylabel(r'E($\alpha $)/kT') plt.legend() plt.tight_layout() Output

for-loop
tags question: http://stackoverflow.com/q/52364612
tags question: http://stackoverflow.com/q/52381969
tags question: http://stackoverflow.com/q/52423525
tags question: http://stackoverflow.com/q/52391303
tags question: http://stackoverflow.com/q/52395637
tags question: http://stackoverflow.com/q/52365811
tags question: http://stackoverflow.com/q/52395750
tags question: http://stackoverflow.com/q/52327740
tags question: http://stackoverflow.com/q/52357831
tags question: http://stackoverflow.com/q/52328134
tags question: http://stackoverflow.com/q/52406175
tags question: http://stackoverflow.com/q/52370112
tags question: http://stackoverflow.com/q/52406466
tags question: http://stackoverflow.com/q/52400904
tags question: http://stackoverflow.com/q/52417929
tags question: http://stackoverflow.com/q/52363433
tags question: http://stackoverflow.com/q/52275277
tag name: for-loop
tags question: http://stackoverflow.com/q/52345349
tags question: http://stackoverflow.com/q/52281785
tags question: http://stackoverflow.com/q/52341165
tags question: http://stackoverflow.com/q/52353982
tags question: http://stackoverflow.com/q/52300481
tags question: http://stackoverflow.com/q/52356132
tags question: http://stackoverflow.com/q/52404565
tags question: http://stackoverflow.com/q/52322847
tags question: http://stackoverflow.com/q/52414111
tags question: http://stackoverflow.com/q/52310348
tags question: http://stackoverflow.com/q/52412964
tags question: http://stackoverflow.com/q/52337094
tags question: http://stackoverflow.com/q/52293079
tags question: http://stackoverflow.com/q/52303613
tags question: http://stackoverflow.com/q/52421289
tags question: http://stackoverflow.com/q/52310755
tags question: http://stackoverflow.com/q/52341439
tags question: http://stackoverflow.com/q/52323676
type: Tag
tags question: http://stackoverflow.com/q/52408488
tags question: http://stackoverflow.com/q/52350313
tags question: http://stackoverflow.com/q/52295349
tags question: http://stackoverflow.com/q/52289146
tags question: http://stackoverflow.com/q/52384648
tags question: http://stackoverflow.com/q/52378615
tags question: http://stackoverflow.com/q/52420704
tags question: http://stackoverflow.com/q/52423549
tags question: http://stackoverflow.com/q/52342741
tags question: http://stackoverflow.com/q/52302233
tags question: http://stackoverflow.com/q/52364934
tags question: http://stackoverflow.com/q/52425038
tags question: http://stackoverflow.com/q/52372930
tags question: http://stackoverflow.com/q/52276345
tags question: http://stackoverflow.com/q/52345705
tags question: http://stackoverflow.com/q/52377346

http://stackoverflow.com/q/52377159
has body: i´m with some problems when i try to use Scrapy. I am following the Scrapy Tutorial (here) and i can´t create a project. They asked me to use scrapy startproject tutorial to create a project and use Scrapy (As this image shows) I was using the Spider IDE (found in Anaconda Navigator) but the instructions doesn´t work there, even the code (and i was importing scrapy). So i go to the Anaconda Prompt and got the following error: (base) C:\Users\wid&gt;scrapy startproject tutorial Traceback (most recent call last): File "E:\Anaconda3\Scripts\scrapy-script.py", line 10, in &lt;module&gt; sys.exit(execute()) File "E:\Anaconda3\lib\site-packages\scrapy\cmdline.py", line 149, in execute cmd.crawler_process = CrawlerProcess(settings) File "E:\Anaconda3\lib\site-packages\scrapy\crawler.py", line 252, in __init__ log_scrapy_info(self.settings) File "E:\Anaconda3\lib\site-packages\scrapy\utils\log.py", line 149, in log_sc rapy_info for name, version in scrapy_components_versions() File "E:\Anaconda3\lib\site-packages\scrapy\utils\versions.py", line 35, in sc rapy_components_versions ("pyOpenSSL", _get_openssl_version()), File "E:\Anaconda3\lib\site-packages\scrapy\utils\versions.py", line 43, in _g et_openssl_version import OpenSSL File "E:\Anaconda3\lib\site-packages\OpenSSL\__init__.py", line 8, in &lt;module&gt; from OpenSSL import crypto, SSL File "E:\Anaconda3\lib\site-packages\OpenSSL\crypto.py", line 16, in &lt;module&gt; from OpenSSL._util import ( File "E:\Anaconda3\lib\site-packages\OpenSSL\_util.py", line 6, in &lt;module&gt; from cryptography.hazmat.bindings.openssl.binding import Binding File "E:\Anaconda3\lib\site-packages\cryptography\hazmat\bindings\openssl\bind ing.py", line 13, in &lt;module&gt; from cryptography.hazmat.bindings._openssl import ffi, lib ImportError: DLL load failed: O sistema operacional não pode executar %1. (base) C:\Users\wid&gt; Error on Anaconda Prompt When i activate my Environment i still got the same error. PS: There was another topic …
has comment: http://stackoverflow.com/comment/91699135
answer count: 0
type: Question
has title: How to Use Scrapy on Anaconda
tagged with: python
tagged with: web
score: 0
has comment: http://stackoverflow.com/comment/91698930
tagged with: scrapy
tagged with: anaconda
type: UnansweredQuestion
tagged with: web-crawler

http://stackoverflow.com/comment/91713949
comment on: http://stackoverflow.com/q/52384645
score: 0
type: Comment
type: QuestionComment
has text: Yes specifically I would like to output them from my nested dictionary structure to a text file in the following format: document_key1, nested_key:nested_value, nested_key:nested_value\n document_key2, nested_key:nested_value, nested_key:nested_value\n

http://stackoverflow.com/a/57872570
score: 2
has comment: http://stackoverflow.com/comment/105517413
answers question: http://stackoverflow.com/q/52336902
downvote count: 2
type: Answer
has body: As per the documentation in https://boto3.amazonaws.com/v1/documentation/api/1.9.185/guide/s3-uploading-files.html "The upload_file and upload_fileobj methods are provided by the S3 Client, Bucket, and Object classes. The method functionality provided by each class is identical. No benefits are gained by calling one class's method over another's. Use whichever class is most convenient." The answers above seems to be false
upvote count: 4

http://stackoverflow.com/q/52400236
upvote count: 4
has comment: http://stackoverflow.com/comment/91744595
has title: Calculate mean for all the columns every 12 hours
has comment: http://stackoverflow.com/comment/91744492
has body: I have a dataframe and i want to calculate every 12 hours mean for all the columns. dataframe has more than 200k rows. DateTime Speed TRQ ... PtoP3 RMS3 Crest3 0 2016-07-01 00:00 994 35.4 ... NA NA NA 1 2016-07-01 00:01 995 34.6 ... NA NA NA 2 2016-07-01 00:02 995 34 ... NA NA NA i wrote this Present_data.to_datetime(Present_data['DateTime']) Total_12hravg_all = Present_data.groupby(pd.Grouper(freq='12H', key='DateTime')).mean() print(Total_12hravg_all) and got this error TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'
type: AnsweredQuestion
tagged with: dataframe
linked to: http://stackoverflow.com/q/13411544
score: 4
type: Question
tagged with: pandas
tagged with: mean
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52400726
accepted answer: http://stackoverflow.com/a/52400726
favorite count: 0
tagged with: python

http://stackoverflow.com/q/52318845
has body: Okay, so I have been going at this for a while and it doesn't seem like I am getting anywhere. I am running a Django app with Nginx and uwsgi. I have an http.post and I am trying to even read the items which I keep getting errors for. This is what my JS code looks like : $scope.receipt_pay_update = function(items) { response = confirm("Do you want to continue with the changes?"); if(!response){ return; } var data = { 'items': items, 'time_now': moment().format("YYYY-MM-DD") }; items.showmessage = true; console.log(data) $http.post("/foodhub/dashboard/receipt_pay_modal_update", data,{ data: JSON }). success(function(data,status,headers,config){ $scope.alertclass = 'alert-success'; $scope.save_message_farmer = "Succcessfully update payment" console.log("SAVED!") }). error(function(data,status,headers,config){ $scope.alertclass = 'alert-danger'; $scope.save_message_farmer= "Failed to update inventory, please try again" }) } This is what my views.py looks like: @login_required def receipt_pay_modal_update(request): import sys reload(sys) sys.setdefaultencoding('utf8') data = json.loads(request.body)['items'] print data rec = ReceiverActions.objets.get(identifier = data[0]['identifier']) rec['paid_check'] = data[0]['paid_status'] rec['date_paid'] = data[0]['paid_date'] rec.save() return HttpResponse(status=status.HTTP_200_OK) I got an error of unable to decode JSON. So I tried data = request.body[0] which also didn't work. Is there any other way I could be testing small changes on my server without having to do the Git push, Git Pull, Python -m compileall ., etc? The reason I ask is because I was taught to do it this way by practice and I feel there is a better way. Where can I check my print data? Any help would be highly appreciated.
tagged with: javascript
tagged with: ubuntu
has title: Troubleshooting HTTP request and JSON message on Django
has comment: http://stackoverflow.com/comment/91586325
has comment: http://stackoverflow.com/comment/91585599
score: 0
has comment: http://stackoverflow.com/comment/91586143
has comment: http://stackoverflow.com/comment/91586188
answer count: 1
has answer: http://stackoverflow.com/a/52322937
tagged with: django
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/25968752
tagged with: http
type: Question
has comment: http://stackoverflow.com/comment/91586313

http://stackoverflow.com/comment/91804043
type: AnswerComment
type: Comment
score: 1
has text: @martineau I thought of that originally, but I wanted to also print the offending arguments. I suppose one could just loop through and raise an error on the first bad argument as well.
comment on: http://stackoverflow.com/a/52429908

http://stackoverflow.com/a/52301348
downvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/52301276
upvote count: 5
answers question: http://stackoverflow.com/q/52301276
has comment: http://stackoverflow.com/comment/91550978
has body: Python int and numpy int are not the same... Python supports arbitrary length, whereas numpy is fixed by the type: numpy.array([1]) &lt;&lt; 70 &gt;&gt;&gt; array([64], dtype=int32) One solution is to use the object dtype: numpy.array([1], dtype=numpy.object) &lt;&lt; 70 &gt;&gt;&gt; array([1180591620717411303424], dtype=object) And the following will work as expected: a = numpy.array([1], dtype=numpy.object) &lt;&lt; numpy.arange(70) Looking at the type of the last element, we see that it is a Python int: type(a[-1]) &gt;&gt;&gt; &lt;class 'int'&gt;
has comment: http://stackoverflow.com/comment/91551805
type: AcceptedAnswer
score: 4

http://stackoverflow.com/a/52389312
has comment: http://stackoverflow.com/comment/91743125
accepted answer of: http://stackoverflow.com/q/52389105
upvote count: 54
answers question: http://stackoverflow.com/q/52389105
type: AcceptedAnswer
has body: Airflow represents workflows as directed acyclic graphs. A workflow is any number of tasks that have to be executed, either in parallel or sequentially. The ">>" is Airflow syntax for setting a task downstream of another. Diving into the incubator-airflow project repo, models.py in the airflow directory defines the behavior of much of the high level abstractions of Airflow. You can dig into the other classes if you'd like there, but the one that answers your question is the BaseOperator class. All operators in Airflow inherit from the BaseOperator. The __rshift__ method of the BaseOperator class implements the Python right shift logical operator in the context of setting a task or a DAG downstream of another. See implementation here.
score: 54
type: Answer
downvote count: 0

http://stackoverflow.com/comment/91550959
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52286811
type: AnswerComment
has text: @robinsax Good point. Consecutive spaces can be taken into account. I don't know what whitespace tokens are though.

http://stackoverflow.com/comment/91604996
has text: data = [[2, 0], [5, 7], [5, 0], [2, 7], [2, 2], [3, 3], [3, 2], [2, 3], [3, 5], [4, 7], [4, 5], [3, 7]] i found that if i change the position of [2,2] with [2,3] like data above, this function not correct, because in the "return [current] if start[v] == current[v] else []" command you don't have rule for current [h]. It can be solve to add condition current[h] is minimum.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52311625
type: AnswerComment

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/52285755
tags question: http://stackoverflow.com/q/52354470
tags question: http://stackoverflow.com/q/52429033
tags question: http://stackoverflow.com/q/52354640
tags question: http://stackoverflow.com/q/52311063
tags question: http://stackoverflow.com/q/52397507
tags question: http://stackoverflow.com/q/52333868
tags question: http://stackoverflow.com/q/52358593
tags question: http://stackoverflow.com/q/52414568
tags question: http://stackoverflow.com/q/52336057
tags question: http://stackoverflow.com/q/52360924
tags question: http://stackoverflow.com/q/52375978
tags question: http://stackoverflow.com/q/52390968
tags question: http://stackoverflow.com/q/52349416
tags question: http://stackoverflow.com/q/52351237
type: Tag
tags question: http://stackoverflow.com/q/52286525
tags question: http://stackoverflow.com/q/52289234
tags question: http://stackoverflow.com/q/52394976
tags question: http://stackoverflow.com/q/52284621
tags question: http://stackoverflow.com/q/52358406
tags question: http://stackoverflow.com/q/52342507
tags question: http://stackoverflow.com/q/52274902
tags question: http://stackoverflow.com/q/52412717
tags question: http://stackoverflow.com/q/52357358
tags question: http://stackoverflow.com/q/52373526
tags question: http://stackoverflow.com/q/52360080
tags question: http://stackoverflow.com/q/52385309
tags question: http://stackoverflow.com/q/52314747
tags question: http://stackoverflow.com/q/52282705
tags question: http://stackoverflow.com/q/52346159
tags question: http://stackoverflow.com/q/52341739
tags question: http://stackoverflow.com/q/52396215
tags question: http://stackoverflow.com/q/52319896
tags question: http://stackoverflow.com/q/52306563
tags question: http://stackoverflow.com/q/52339284
tags question: http://stackoverflow.com/q/52345587
tags question: http://stackoverflow.com/q/52276651
tag name: html
tags question: http://stackoverflow.com/q/52278318
tags question: http://stackoverflow.com/q/52343735
tags question: http://stackoverflow.com/q/52341186
tags question: http://stackoverflow.com/q/52365584
tags question: http://stackoverflow.com/q/52336190
tags question: http://stackoverflow.com/q/52342017
tags question: http://stackoverflow.com/q/52322609
tags question: http://stackoverflow.com/q/52355596

http://stackoverflow.com/comment/91696654
type: QuestionComment
comment on: http://stackoverflow.com/q/52375784
has text: Can you clarify your output? You want to split into 15 minute chunks then drop duplicates, but keep the original Dates?
score: 0
type: Comment

http://stackoverflow.com/q/52423903
has title: Update dataframe in for loop
has comment: http://stackoverflow.com/comment/91791362
tagged with: dataframe
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91790629
has answer: http://stackoverflow.com/a/52429211
possible better answer: http://stackoverflow.com/a/52424105
accepted answer: http://stackoverflow.com/a/52429211
score: 0
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/52424105
type: AnsweredQuestion
has body: I am trying to create a dataframe from values in a for loop: d1 = {} d = {} for i in range(4000): try: shape_json = json.loads(region_shape[i]) file_name = file_name_nuclei[i] x_val = shape_json["x"] y_val = shape_json["y"] width_val = shape_json["width"] height_val = shape_json["height"] path = '/home/values/' + str(file_name) x1 = x_val y1 = y_val x2 = x_val + width_val y2 = y_val + height_val df = pd.DataFrame(data=d1) d = {'col1': [path], 'col2': [x1], 'col3': [y1], 'col4': [x2], 'col5': [y2], 'col5': ['nucleus']} df2 = pd.DataFrame(data=d1) df.update(df2) except: pass I, however, can't get the dataframe to update with each iteration. Can anyone help? I am trying to get output: 0 col1 col2 col3 col4 col5 '/home/values/image.png' 23 55 30 62 'nucleus' '/home/values/image2.png' 40 72 37 92 'nucleus' . . . . .

http://stackoverflow.com/q/52420912
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/52421550
downvote count: 2
tagged with: pandas-groupby
tagged with: pandas
favorite count: 0
has body: everyone, I'm new to python I have a dataset like ROLLNO G1 G2 G3 G4 1 12 14 14 20 1 10 12 11 12 2 14 02 16 18 2 18 16 12 14 I want to merge them as ROLLNO G1 G2 G3 G4 G5 G6 G7 G8 1 12 14 14 20 10 12 11 12 2 14 02 16 18 18 16 12 14 This is the code I have written but it is giving me the wrong result. print (CseStudents_ds.groupby('ROLLNO').apply(' '.join).reset_index()) I have searched a lot and thought of using group by but unable to figure out what should be done next. Any help
has comment: http://stackoverflow.com/comment/91785117
tagged with: python
type: AnsweredQuestion
has title: Append several rows as a single row python based on Group by
type: Question
has answer: http://stackoverflow.com/a/52422822
accepted answer: http://stackoverflow.com/a/52422822
has answer: http://stackoverflow.com/a/52421550
upvote count: 2

http://stackoverflow.com/comment/91758183
type: AnswerComment
comment on: http://stackoverflow.com/a/52407042
score: 0
type: Comment
has text: Well... To put te elements of speed in a list you only need to do df['speed'].tolist()

http://stackoverflow.com/comment/91788271
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52422660
has text: May I ask where exactly you found this `sys.path` hackery so I can downvote it?
score: 2

http://stackoverflow.com/comment/91587517
comment on: http://stackoverflow.com/q/52320080
type: QuestionComment
score: 1
has text: Furthermore I find the logic rather strange. `post_delete` means that at *that* moment, the `Order` is already removed, so then the count is zero (given there are no other orders).
type: Comment

http://stackoverflow.com/comment/91583848
type: Comment
has text: Sorry its read_clipboard
comment on: http://stackoverflow.com/q/52317636
score: 0
type: QuestionComment

http://stackoverflow.com/a/57731053
has comment: http://stackoverflow.com/comment/121292966
has body: First run your IDE or CMD as Administrator and run the following commands: pip install pipwin pipwin install pyaudio
has comment: http://stackoverflow.com/comment/128258627
downvote count: 1
has comment: http://stackoverflow.com/comment/125833478
has comment: http://stackoverflow.com/comment/124944977
has comment: http://stackoverflow.com/comment/119337268
answers question: http://stackoverflow.com/q/52283840
has comment: http://stackoverflow.com/comment/110762962
has comment: http://stackoverflow.com/comment/123680051
has comment: http://stackoverflow.com/comment/125806680
score: 160
has comment: http://stackoverflow.com/comment/128481811
upvote count: 161
type: Answer

http://stackoverflow.com/q/52323614
possible better answer: http://stackoverflow.com/a/68950075
has answer: http://stackoverflow.com/a/68950075
answer count: 3
has answer: http://stackoverflow.com/a/52323709
has answer: http://stackoverflow.com/a/52323752
type: AnsweredQuestion
has title: Python Using Recursion to Traverse Through a Nested List With Conditions
type: Question
has body: Suppose I have the following: def foo(lst): current = 0 if(len(lst) == 0): return current first = bar(lst[0]) rest = foo(lst[1:]) if(first &gt; current): current = first return current if __name__ == "__main__": lst1 = [2,4,6] lst2 = [0,2,5,6,12] lst3 = [] lst4 = [1] lst5 = [2] full_lst = [lst1, lst2, lst3, lst4, lst5] print(foo(full_lst)) This function takes a nested list in the above structure as a parameter. The goal of the function is to traverse through this nested list structure recursively and apply a computation to each list. The function is also to keep track of each computation and eventually return the largest of these values obtained from the computations. I believe I have some the basic structure complete, but I fail to see how I could use the function call on the smaller sub list and compare the value obtained from that with the one obtained from the previous function call. Thanks.
score: 0
tagged with: python
tagged with: recursion
accepted answer: http://stackoverflow.com/a/52323752

http://stackoverflow.com/q/52416558
has answer: http://stackoverflow.com/a/52416570
answer count: 2
favorite count: 0
has body: I can't seem to figure out how to fix my error. Pretty new to Python so if you can be as specific as possible, it helps. print ('HStartX: ') + str(HSX) print ('LStartX: ') + str(LSX) print ('HStartY: ') + str(HSY) print ('LStartY: ') + str(LSY) print ('HendX: ') + str(HEX) print ('LendX: ') + str(LEX) print ('HendY: ') + str(HEY) print ('LendY: ') + str(LEY) Here is where the error occurred.. TypeError unsupported operand type(s) for +: NoneType and 'str'
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/52416596
downvote count: 1
has comment: http://stackoverflow.com/comment/91776566
type: Question
has comment: http://stackoverflow.com/comment/91776982
has title: Unable to add string when printing

http://stackoverflow.com/a/52375534
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52374143
has comment: http://stackoverflow.com/comment/91696872
type: Answer
has body: Here's your problem def latest_posts(request): latests = Post.objects.filter(published_date__lte=timezone.now()).reverse()[:3] return render(request, 'blog/post_list.html', {'latest': latest}) You've defined latests on line 2 but passed latest on line 3. And then in your template you've reverted to latests so you want: def latest_posts(request): latests = Post.objects.filter(published_date__lte=timezone.now()).reverse()[:3] return render(request, 'blog/post_list.html', {'latests': latests})
upvote count: 1

http://stackoverflow.com/q/52396636
has answer: http://stackoverflow.com/a/52396697
score: 0
has title: Why is Python's Logger Returning Errors When There Isn't An Error?
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52396674
tagged with: python
has body: I think I am not understanding how Python's logging library works. I have a simple function: def all_caps(_string): logging.debug("debug") logging.info("info") logging.warning("warning") logging.error("error") logging.critical("critical") return _string.upper() From what I understand from tutorials, if I run this function with an input that produces no errors (e.g. all_caps("hello")), I should see the output: DEBUG:root:debug INFO:root:info However, I see the exact opposite: WARNING:root:warning ERROR:root:error CRITICAL:root:critical HELLO Am I crazy? Am I using logging fundamentally wrong?
has comment: http://stackoverflow.com/comment/91738327
tagged with: logging
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52396674
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/52396697

http://stackoverflow.com/a/52424541
answers question: http://stackoverflow.com/q/52423945
type: Answer
has comment: http://stackoverflow.com/comment/91793694
has body: If the test in in the if clause is false for the first iteration, then temp is not defined, but you nonetheless try to unconditionnaly append it to TDIF_score. Also, if the test is true for the first iteration (in which case you don't have a NameError), if it evals to false on a next iteration, you'll be appending the temp from the previous iteration again. Obviously you want to indent the TFIDF_score.append(temp) line so that it's within the if block: for j in IDF_score: for i in TF_score: if j['key'] == i['key'] and j['doc_id'] == i['doc_id']: temp= {'doc_id': j['doc_id'], 'TFIDF_score': j['IDF_score']*i['TF_score'], 'key': i['key']} TFIDF_score.append(temp)
has comment: http://stackoverflow.com/comment/91793231
score: 0

http://stackoverflow.com/comment/91690069
comment on: http://stackoverflow.com/q/52372650
score: 0
type: QuestionComment
type: Comment
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. You've posted your entire program, rather than the minimum needed to illustrate the problem.

flask-sqlalchemy
tags question: http://stackoverflow.com/q/52414291
tags question: http://stackoverflow.com/q/52399907
type: Tag
tags question: http://stackoverflow.com/q/52306960
tags question: http://stackoverflow.com/q/52347763
tags question: http://stackoverflow.com/q/52336432
tags question: http://stackoverflow.com/q/52378183
tags question: http://stackoverflow.com/q/52303043
tags question: http://stackoverflow.com/q/52328299
tags question: http://stackoverflow.com/q/52411968
tag name: flask-sqlalchemy
tags question: http://stackoverflow.com/q/52344228
tags question: http://stackoverflow.com/q/52293162
tags question: http://stackoverflow.com/q/52293195
tags question: http://stackoverflow.com/q/52330033
tags question: http://stackoverflow.com/q/52298269
tags question: http://stackoverflow.com/q/52414329
tags question: http://stackoverflow.com/q/52312593
tags question: http://stackoverflow.com/q/52283411

azure
tags question: http://stackoverflow.com/q/52338155
tags question: http://stackoverflow.com/q/52278469
tags question: http://stackoverflow.com/q/52346114
tags question: http://stackoverflow.com/q/52292879
tags question: http://stackoverflow.com/q/52373092
tags question: http://stackoverflow.com/q/52354643
tags question: http://stackoverflow.com/q/52388039
tags question: http://stackoverflow.com/q/52333749
tags question: http://stackoverflow.com/q/52317458
type: Tag
tags question: http://stackoverflow.com/q/52428088
tags question: http://stackoverflow.com/q/52415096
tags question: http://stackoverflow.com/q/52295063
tags question: http://stackoverflow.com/q/52409379
tag name: azure

http://stackoverflow.com/q/52380078
has title: how to open an url and return data from there in odoo 10?
type: Question
has comment: http://stackoverflow.com/comment/91704454
score: 0
tagged with: odoo-view
tagged with: odoo-10
has comment: http://stackoverflow.com/comment/91710735
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: odoo-11
tagged with: odoo
has body: I have developed simple custom odoo module. on button click action I wrote a simple method that should simply display data on the odoo screen. Module is getting installed successfully, but not performing required action so please help me. Thanks in advance. my button code in header tags *&lt;header&gt; &lt;button name="get_data" type="object" string="Click" class="oe_highlight" /&gt; &lt;/header&gt;* my python method inside model.py *from odoo import models, fields, api import requests class gabzilAi(models.Model): _name = 'ai.gabzil' _description = 'Gabzil Odoo Module' fileName = fields.Text("File content") @api.one def get_data(self): myreq = requests.get("http://cake.gabzil.com/api/customers") textdata = myreq.text return textdata* I am new to Odoo so not that much familiar with the things where i am making silly mistake...
has comment: http://stackoverflow.com/comment/91705657

http://stackoverflow.com/comment/91795439
has text: Brilliant. Dependent file with newer timestamp. `touch`ing the downloaded files solved the issue! @JeeYeem, if you post your comment as an answer I'll be happy to give you credit!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52411496

http://stackoverflow.com/comment/91494337
score: 0
type: Comment
has text: The whole code is too long, but I added the imports and the particular page the button belongs to.
type: AnswerComment
comment on: http://stackoverflow.com/a/52273058

http://stackoverflow.com/comment/91624465
score: 0
type: AnswerComment
type: Comment
has text: Thank you very much for your help. Really helpful!!! It only takes less than 2 minutes to run!!! But I made a small revision about the df_lst.loc[(oZ_hZ) & (ps_2)]['d'] = 'A' . Because it doesn't assign any value for column d. So I changed the code to df_lst.loc[((oZ_hZ) & (ps_2)),'d'] = 'A'. I am not really sure about the difference of the two codes. But the latter one works.
comment on: http://stackoverflow.com/a/52334668

http://stackoverflow.com/comment/91543546
type: AnswerComment
type: Comment
has text: Thanks for your suggestion. But here I am passing only file path as argument in the function so slave_list is not iterable thing. Actually both slave_list and static_ip_list are file path. I tried passing slave_list instead of f in apply_async function and I see there are multiple process running but I believe all the processes are doing operation in the same data. So, it's kind of repeated task. Any suggestion? Thanks.
comment on: http://stackoverflow.com/a/52296286
score: 0

http://stackoverflow.com/a/52384347
has comment: http://stackoverflow.com/comment/91712969
score: 0
has body: Maybe something like this: &gt;A = np.zeros((5, 5)) &gt;B = np.ones((5, 5)) &gt;B[2, :] = 0 &gt;print(A) 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., 0.]]) &gt;print(B) array([[1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [0., 0., 0., 0., 0.], [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.]]) &gt;(A == B).all(axis=1) array([False, False, True, False, False])
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91713017
answers question: http://stackoverflow.com/q/52384149
type: Answer

http://stackoverflow.com/comment/91637661
has text: Do you mean you just want to reverse the merge order? `dummy.merge(df...)` ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52345987
score: 2

http://stackoverflow.com/comment/91799692
type: Comment
has text: (which also makes `z = [[]]*d` (and the whole `n` variable, really) kind of silly)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52428168

http://stackoverflow.com/a/52336898
type: AcceptedAnswer
type: Answer
score: 8
downvote count: 0
has body: So, all my searching didn't yield a short solution. The answer to the question seems to be: no, there is no buit-in way to get the current date (or datetime) as a variable in the template. In case others are searching for this topic, I'll try to give a summary of the possible workarounds that I can up with and that were suggested by other users. I could pass a context variable to the template from my view. In class-based views that could look like this (it is even an example in the docs): # file 'my_app/views.py' from django.utils import timezone as tz from django.views.generic import ListView class MyView(ListView) ... def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) now = tz.now() ctx['now'] = now ctx['today'] = tz.localtime(now).date() return ctx I could create a custom context processor that loads that variable to every template. In class-based views that could look like this: # file 'context_processors.py' from django.utils import timezone as tz def now_and_today(request): now = tz.now() return { 'now': now, 'today': tz.localtime(now).date(), } # file 'settings.py' ... TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'context_processors.now_and_today', ], }, }, ] ... I could create a custom template tag, like this: # file 'my_app/custom_template_tags/custom_time_tags.py' from django.utils import timezone as tz from django import template register = template.Library() @register.simple_tag def get_now(request): return tz.now() @register.simple_tag def get_today(request): return tz.localtime(tz.now()).date() To be used like this: {% load 'custom_time_tags' %} {% get_today as today %} {% for per in person_list %} {% if per.brith_date &gt; today %} &lt;p&gt;{{ per.name }} is from the future!!&lt;p&gt; {% endif %} {% endfor %} I could also add a property (or even a cached_property) to the model: # file 'models.py' from django.db import models from django.utils import timezone as tz from django.utils.functional import cached_p…
upvote count: 8
accepted answer of: http://stackoverflow.com/q/52296306
answers question: http://stackoverflow.com/q/52296306

http://stackoverflow.com/comment/92101958
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52279810
has text: Wish I saw the updates to this, a very good effort in trying all these different approaches. I have some ideas, but you haven't provided some starting images. If you're still working on this, could you comment with a few images to start with? Your original `thresh` image from the watershed approach actually looks pretty good, barring that there's some little holes. Fill them up! Do some morphological closing first, which should give you (mostly) all white circles. Alternatively, use `floodFill()` to close the holes. See [here](https://stackoverflow.com/a/45971386/5087436).

http://stackoverflow.com/q/52344126
tagged with: python-2.7
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52344791
has title: Python tree datatype add child operation results in recursive children
tagged with: python
has body: I have a tree generated at python and I just simply want to append a new child to a parent however, Although the children of the child no is empty, it seems to happend that child node becomes child of both parent and itself. def __init__(self): self.child_nodes = [] self.data = None ... self.parent = None def init_tree(self, data, child_nodes=[], ...): self.child_nodes = child_nodes self.data = data ... def add_child_node(self, node): ancestors = self.get_ancestors() if node is not self and node not in ancestors: self.child_nodes.append(node) node.parent = self def get_ancestors(self): ancestor = self.parent ancestors = [ancestor] try: while ancestor.parent != None: ancestors.append(ancestor) parent = self.parent ancestor = parent.get_parent() return ancestors # Node is root. Root's parent is None except AttributeError: return [] def my_funct(self): ... child_node = RandomWalkTree() child_node.init_tree(data=data) self.add_child_node(child_node) my_funct results in a childnode with a child_nodes containing itself recursively. Which points am I missing?
tagged with: tree
tagged with: recursion
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52344791
type: Question
tagged with: data-structures

http://stackoverflow.com/comment/91537572
comment on: http://stackoverflow.com/q/52294939
type: QuestionComment
has text: The installed package is a distribution, it may have several modules to import with different names than the package itself. Can you include the directory tree of the package sources?
score: 1
type: Comment

http://stackoverflow.com/q/52313432
has title: Testing function that interacts with Django Rest Framework API using python mock library
favorite count: 0
has body: I want to unit test a module that interacts with an API built with Django Rest Framework. To do that I'm using python mock library. As I'm not experienced using mocks to test interaction with an API, I'm having problems. The function that sends an object to an API endpoint is this (in short): def send_experiment_to_portal(experiment: Experiment): rest = RestApiClient() if not rest.active: return None # general params params = {"nes_id": str(experiment.id), "title": experiment.title, "description": experiment.description, "data_acquisition_done": str(experiment.data_acquisition_is_concluded), "project_url": experiment.source_code_url, "ethics_committee_url": experiment.ethics_committee_project_url } action_keys = ['experiments', 'create'] portal_experiment = rest.client.action( rest.schema, action_keys, params=params, ) return portal_experiment The RestAPIClient is the class that authenticates to the API: class RestApiClient(object): client = None schema = None active = False def __init__(self): auth = coreapi.auth.BasicAuthentication( username=settings.PORTAL_API['USER'], password=settings.PORTAL_API['PASSWORD'] ) self.client = coreapi.Client(auth=auth) try: url = settings.PORTAL_API['URL'] + \ ( ':' + settings.PORTAL_API['PORT'] if settings.PORTAL_API['PORT'] else '' ) \ + '/api/schema/' self.schema = self.client.get(url) self.active = True except: self.active = False The RestApiClient class is using the coreapi client module to connect to the API. So, at the end, I'm starting from test if the params argument in rest.client.action has the keys/values that are foreseen by the API using python mock library. I'm starting writing the initial test like: class PortalAPITest(TestCase): @patch('experiment.portal.RestApiClient') def test_send_experiment_to_portal(self, mockRestApiClientClass): research_project = ObjectsFactory.create_research_project() experiment = ObjectsFactory.create_experiment(research_project) result = send_experiment_to_portal(experiment) So when I de…
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/52330512
tagged with: python
upvote count: 1
tagged with: unit-testing
type: Question
tagged with: mocking
answer count: 1
downvote count: 0
score: 1

http://stackoverflow.com/q/52424085
accepted answer: http://stackoverflow.com/a/52424572
upvote count: 1
type: Question
tagged with: pandas
answer count: 1
tagged with: bar-chart
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52424572
has title: Overlapping a line plot to a horizontal bar plot in pandas
has body: I'm trying to overlap a line plot to a horizontal bar plot in pandas. Having a dataframe like this data = pd.DataFrame(np.random.randint(0,100,size=(10, 4)), columns=list('ABCD')) I can overlap a plot to a bar plot, like this: ax = data'A','B','C'.plot(kind='bar', stacked=True) data['D'].plot(color='k',ax=ax) with this result Plot on a bar plot But when I try to use a horizontal barplot ax = data['D'].plot(color='k') data'A','B','C'.plot(kind='barh', stacked=True, ax=ax) I have this result Plot on a barh plot How can I flip the line plot so to have it coherent with the barh plot= Thank you for any hint!
tagged with: python
tagged with: plot
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/91607763
comment on: http://stackoverflow.com/a/52312166
type: Comment
has text: does your object inherit from `nn.Module`?
score: 0
type: AnswerComment

http://stackoverflow.com/a/52352077
accepted answer of: http://stackoverflow.com/q/52344287
has comment: http://stackoverflow.com/comment/106764520
has body: There are several hurdles to overcome to achieve what you are looking for. First, the pyopenssl binding itself is limited when it comes to its crypto module, where you desired functionality resides. In fact, the pyopenssl crypto documentation states: The pyca/cryptography module mentioned is exposed via two internal attributes of the pyopenssl crypto module, with the names _lib and _ffi, which need to be used to get to the required functionality. Then the CMS_verify() function that would be your logical choice for this is not included in the pyca/cryptography bindings either. However, for your purpose it is probably good enough to use PKCS7_verify() -- you can read all about that in a StackExchange question OpenSSL PKCS#7 vs. S/MIME. The function crypto.load_pkcs7_data() comes in handy. All that said, the following code snippet might do it for you -- although from your description it is not clear to me whether the certificate of the signer is included in the .p7s file (in that case you do not have to give -signer as an argument to openssl cms -verify like you did). It worked for me, so give it a try: from OpenSSL import crypto from OpenSSL._util import ( ffi as _ffi, lib as _lib, ) # Or, alternatively: # from cryptography.hazmat.bindings.openssl.binding import Binding # _lib = Binding.lib # _ffi = Binding.ffi with open('message_der.p7s', 'rb') as f: p7data = f.read() p7 = crypto.load_pkcs7_data(crypto.FILETYPE_ASN1, p7data) bio_out =crypto._new_mem_buf() res = _lib.PKCS7_verify(p7._pkcs7, _ffi.NULL, _ffi.NULL, _ffi.NULL, bio_out, _lib.PKCS7_NOVERIFY) if res == 1: databytes = crypto._bio_to_string(bio_out) print(databytes) else: errno = _lib.ERR_get_error() errstrlib = _ffi.string(_lib.ERR_lib_error_string(errno)) errstrfunc = _ffi.string(_lib.ERR_func_error_string(errno)) errstrreason = _ffi.string(_lib.ERR_reason_error_string(errno)) In case you decide to use this approach, here is a caveat about using this OpenSSL bindings module directly:
has comment: http://stackoverflow.com/comment/106763846
has comment: http://stackoverflow.com/comment/106807671
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/106794219
answers question: http://stackoverflow.com/q/52344287
has comment: http://stackoverflow.com/comment/106765075
score: 6
type: Answer
has comment: http://stackoverflow.com/comment/106763885
has comment: http://stackoverflow.com/comment/106763162
has comment: http://stackoverflow.com/comment/106763419
upvote count: 6

http://stackoverflow.com/q/52386793
type: Question
tagged with: dataframe
upvote count: 3
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/52387051
accepted answer: http://stackoverflow.com/a/52387051
has answer: http://stackoverflow.com/a/66812787
favorite count: 0
has body: CSV file: (sample1.csv) Location_City, Location_State, Name, hobbies Los Angeles, CA, John, "['Music', 'Running']" Texas, TX, Jack, "['Swimming', 'Trekking']" I want to convert hobbies column of CSV into following output Location_City, Location_State, Name, hobbies Los Angeles, CA, John, Music Los Angeles, CA, John, Running Texas, TX, Jack, Swimming Texas, TX, Jack, Trekking I have read csv into dataframe but I don't know how to convert it? data = pd.read_csv("sample1.csv") df=pd.DataFrame(data) df
possible better answer: http://stackoverflow.com/a/66812787
has comment: http://stackoverflow.com/comment/91718513
tagged with: python
has title: converting list like column values into multiple rows using Pandas DataFrame
type: AnsweredQuestion
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/91718013

http://stackoverflow.com/q/52396804
favorite count: 0
has title: How To Random Crop (Specific Area And Specific Probability) Rectangle From Image
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: probability
type: Question
linked to: http://stackoverflow.com/q/3679694
score: 2
has body: This is my now code (it could crop image to 25 piece jpg from one image) # -*- coding:utf-8 -*- from PIL import Image def cut(id,vx,vy): # 打開圖片(open image) name1 = "C:\\Users\\admin\\Desktop\\normal_random_crop\\test.png" name2 = "C:\\Users\\admin\\Desktop\\normal_random_crop\\test_" + id + "_crop.jpg" im =Image.open(name1) #偏移量(offset) dx = 100 dy = 100 n = 1 #左上角切割(Left Top Poit) x1 = 0 y1 = 0 x2 = vx y2 = vy #縱向(Vertical) while x2 &lt;= 512: #橫向切(Horizontal) while y2 &lt;= 512: name3 = name2 + str(n) + ".jpg" im2 = im.crop((y1, x1, y2, x2)) im2.save(name3) y1 = y1 + dy y2 = y1 + vy n = n + 1 x1 = x1 + dx x2 = x1 + vx y1 = 0 y2 = vy return n-1 if __name__=="__main__": id = "1" #切割圖片的面積 vx,vy (Crop Area) res = cut(id,100,100) print(res) i hope to make generate amount random crop and specific every area specific probability for example : random crop 100 piece (from 512x512 image) total 104% ( =====1%+2%+1%===== 1%+10%+10%+10%+1%+ 1%+10%+10%+10%+1%+ 1%+10%+10%+10%+1%+ =====1%+2%+1%===== ) yellow area delete(don't need)
downvote count: 0
tagged with: crop
tagged with: random
has answer: http://stackoverflow.com/a/52396931
answer count: 1

http://stackoverflow.com/q/52362938
type: AnsweredQuestion
has body: My scrapy test code is the following. I tested it via scrapy shell and it worked. But now if I finally started to write a script no output appears. Is there something wrong? Thanks. my code so far: import scrapy class CryptohunterSpider(scrapy.Spider): name = "cryptohunter" start_urls=["https://www.coingecko.com/de"] def parse(self, response): for x in response.xpath('//div[@class="coin-content center"]/a/span/text()'): print (x.extract()) Output: Sorry I couldn't input the shell, so I started a screenshot. So I'm not sure if it's the error or not. If it should be an error, how show I handle it? How to get the full number out of this? It's always rounded by 2. Output: 0,07 instead of 0.0688852511227967
tagged with: web-crawler
tagged with: scrapy
type: Question
has title: Scrapy crawler what tells me this output?
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52363880
accepted answer: http://stackoverflow.com/a/52363880
tagged with: python

http://stackoverflow.com/q/52283810
has comment: http://stackoverflow.com/comment/91533234
type: Question
linked to: http://stackoverflow.com/q/40222050
tagged with: automation
has body: I am trying to loop between applications at a certain interval, for now, I came up with this just wanting to see it work, but I am not able to "focus" on the Chrome application. Note: multiple applications could be running (Chrome, Notepad, PyCharm, Skype) but I only want to switch between Notepad and Chrome So far I came up with this: from pywinauto import application from time import sleep notepad = application.Application() chrome = application.Application() chrome.start("chrome.exe") notepad.start("notepad.exe") def loopApps(): while True: chrome.connect(title_re="Google Chrome") chrome_dialog = chrome.top_window_() chrome_dialog.Minimize() print("[+] Sleeping 10 seconds") sleep(10) notepad.connect() notepad_dialog = notepad.top_window_() loopApps() I am not sure that this could be done using pyautogui as I've looked into the docs... This is not useful(and it's outdated) how to switch between two application using pywinauto 0.5.4
has title: Switch between applications - pywinauto
tagged with: pywinauto
has comment: http://stackoverflow.com/comment/91531181
score: 0
has comment: http://stackoverflow.com/comment/91526419
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52308782
linked to: http://stackoverflow.com/q/30200381
has comment: http://stackoverflow.com/comment/91525281
has answer: http://stackoverflow.com/a/52308782
type: AnsweredQuestion

http://stackoverflow.com/q/52274265
type: UnansweredQuestion
has title: Split series in segments larger than a threshold and apply statistics to segments
has comment: http://stackoverflow.com/comment/91495976
type: Question
has comment: http://stackoverflow.com/comment/91495796
tagged with: pandas
has comment: http://stackoverflow.com/comment/91496030
score: 1
favorite count: 0
has body: I have a series x with values y and z. I would like to get a collection of segments of x during which y is larger than 0.5. Over this segment I would like to compute two statistics: the length of the segment in units of x and the mean value of z over the segment. I want to discard all data for which y is 0.5 or less. What is the most elegant way to this with pandas? import numpy as np import pandas as pd x = np.arange(0, 100, 0.1) y = np.sin(x) + 0.5*np.sin(0.5*x) z = np.random.rand(x.size) df = pd.DataFrame(data=np.stack((x,y), axis=-1), index=x, columns=['y','z']) # Fetch all x segments for which y is larger than 0.5. Discard others. # Calculate segment length in units of x. # Compute mean of z per segment.
upvote count: 1
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/52274392
has comment: http://stackoverflow.com/comment/91496105
downvote count: 0

http://stackoverflow.com/a/52279861
has comment: http://stackoverflow.com/comment/91509037
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/52279662
has comment: http://stackoverflow.com/comment/91509331
answers question: http://stackoverflow.com/q/52279662
has comment: http://stackoverflow.com/comment/91508846
has body: I see two options. First, you want to generalize that all problem functions return something of the form {'question': format_dict, 'answer': answer_dict}. You can represent this as a namedtuple, or if you have Python 3.7, a data class. Named tuple example: from collections import namedtuple ProblemData = namedtuple('ProblemData', ['question', 'answer']) def q_n(): # ... return ProblemData(format_dict, answer_dict) This solves the problem of the generalizing the structure somewhat, but you still have the return. A much more general and more difficult approach would be to store each question in a configuration file. Of course, you would have to write some small language and parser to have the dynamic sort of data that you want, but I imagine if you scale up to thousands of questions it would be worth the effort.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91509673
downvote count: 0
type: Answer

http://stackoverflow.com/a/52294034
accepted answer of: http://stackoverflow.com/q/52293426
score: 0
type: AcceptedAnswer
has body: You can use the code mentioned below, import os def read_files(file): file_input1 = open(file, 'r') f1 = file_input1.read() return f1 files = ['sample.py', 'Amazon_Indi_Seller.py'] data = list() for file in files: data.append(read_files(file)) print(data) The above code will used to read the files mentioned in the list import os def read_files(file): file_input1 = open(file, 'r') f1 = file_input1.read() return f1 src = r'DIRECTORY PATH' data = list() for file in os.listdir(src): data.append(read_files(file)) print(data) And the above code will read all the files from the directory mentioned
type: Answer
answers question: http://stackoverflow.com/q/52293426

http://stackoverflow.com/comment/91754965
score: 0
type: Comment
type: QuestionComment
has text: There is file1 which have chromosome_ID (chr) and a position (pos). So here I am trying to find this position from file2 in range of position_start - position_end and chromosome_ID (chr). Each entry in file1 (chr and pos) need to be compare once in file2.
comment on: http://stackoverflow.com/q/52404173

http://stackoverflow.com/q/52338577
upvote count: 1
accepted answer: http://stackoverflow.com/a/52339176
downvote count: 1
type: Question
score: 0
answer count: 2
favorite count: 0
has answer: http://stackoverflow.com/a/52339176
has title: arttribute error with dict not finding object even though its in the dict
has body: when i run the code and i get to the question its gets and error claiming that the object i am calling on is not in the dict even though it what i want to do is add 5 to the social point as seen in the class player. is there anyway to solve this or rewrite it? thanks in advance. where the values of the player are stored ##### player setup ##### class player(): def __init__(self): self.name = '' self.gender = '' self.classyear4 = '' self.sociaal = 25 self.educatie = 25 self.emoties = 25 self.location = 'c16' self.game_over = False myPlayer = player() the code that gets the error myPlayer2 = {} question5 ={"ga je naar de stad met vrienden of ga je naar huis?\n":["ja", "nee"]} for question5, valid_answers in question5.items(): correct = False error_msg ="" if valid_answers == None: answer = input(question5 + '\n&gt;') myPlayer[question5] = answer else: while correct == False: answer = input(error_msg+question5+'\n&gt;') if answer.strip().lower() == "ja" in valid_answers: ###the prbleem is that the code cant tell the diffrence between the two anwsers because in its eyes there both valid anwsers so it just runs the first one and not the one were you say no### print("je gaat mee, thuis heb ik toch niks te doen.\n") myPlayer[question5] = answer correct = True myPlayer.sociaal += 5 print("je hebt 5 sociale punten gekregen") print(myPlayer.sociaal) elif answer.strip().lower() == "nee" in valid_answers: ###so fix it so that its able to tell the diffrence between the two anwsers and so that it works after that you add that you get point for the action and that those point are shown good luck### print("je gaat naar huis lekker netflixen.\n") myPlayer[question5] = answer correct = True else: error_msg = ("probeer het opnieuw \n") for key, value in myPlayer.items(): print("{}:{}".format(key, value)) the error message Traceback (most recent call last): File "C:\Users\Sekou\Documents\school simulator game\aloysiusgame.py", line 382, in &lt;module&gt; myPlayer.sociaal += 5 Attribute…
tagged with: python
possible better answer: http://stackoverflow.com/a/52338835
has answer: http://stackoverflow.com/a/52338835
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91624408

http://stackoverflow.com/comment/91827683
score: 0
has text: When I have exact `05:00:00` it puts in `05:00:01-05:00:00` bucket which is weird.
comment on: http://stackoverflow.com/a/52412583
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52344325
has comment: http://stackoverflow.com/comment/91634730
has comment: http://stackoverflow.com/comment/91634795
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/91635367
answers question: http://stackoverflow.com/q/52344228
has body: Try this as Name1 pw1 and Email1 are variables. db.execute("INSERT INTO users (name,pw,email) VALUES ("+Name1+","+pw1+","+Email1+")")
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/91634609

http://stackoverflow.com/comment/91497077
score: 0
type: Comment
type: QuestionComment
has text: P.S:I have started coding in python recently, which is why I am still trying to figure all of this out :-)
comment on: http://stackoverflow.com/q/52274857

http://stackoverflow.com/q/52357618
tagged with: series
has title: How to get a substring pandas series using slice() while there is no pattern to determine the stop argument
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52357688
has answer: http://stackoverflow.com/a/52357652
tagged with: python
has comment: http://stackoverflow.com/comment/91659716
type: Question
has answer: http://stackoverflow.com/a/52357932
tagged with: slice
score: 0
answer count: 3
tagged with: pandas
has body: From this pandas series : Full_Name : Braund, Mr. Owen Harris Cumings, Mrs. John Bradley (Florence Briggs Th... Heikkinen, Miss. Laina Futrelle, Mrs. Jacques Heath (Lily May Peel) Allen, Mr. William Henry How to get this series: Last_Name : Braund Cumings Heikkinen Futrelle Allen I thought this code might work but it didnt, it returns a NaN column: last_name = df['Name'].str.slice(start=0,stop= col.str.find(','))

http://stackoverflow.com/a/52588926
has body: This paper addresses your problem and explains, why it exists: https://dl.acm.org/citation.cfm?id=3132847.3132872 If you can't access it, here are some cites / a summary: There are 2 problems: padding and normalization. Padding: When doing a convolution, the net needs to fill in missing pixel values on the border of the image. That is because the kernel of the first couple of border-pixel lay outside of the provided image. Normalization: In convolution network, batch normalization technique is applied to speed up the convergence and reduce the internal covariate shift. Now, suppose we split the image into two sub-images. We get two small batches. If they go through the CNN independently, we will obtain two normalization results which only apply sub-images’ local means and variances in the computations. Therefore, even if we merge those pieces back to one image, we will end up with a result that is visually different from the one generated for the whole image. They propose the following solutions: Padding: For internal border, we use a novel padding technique, dictionary padding. This means they use the corresponding pixel values of the neighbouring sub-image. For external border, we use circular paddings... This means you pad on the right with the pixels from the left of the image, as if you had concatenated the image on the right (and vice versa). (Same with top-bottom) Normalization: This is a bit more complex. In the end, they normalize the sub-images share the normalization values (mean and variance) between the images and combine them together. The padding may be easy to implement, but I don't know how to do the normalization part with tensorflow. If someone figure it out and sends some code of that I would be very grateful.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52375305
downvote count: 0
has comment: http://stackoverflow.com/comment/100357991
type: Answer

http://stackoverflow.com/comment/91756510
type: AnswerComment
has text: @JohnE, that's really cool! Thank you so much, I learnt a lot from you today!!
type: Comment
comment on: http://stackoverflow.com/a/52405491
score: 0

http://stackoverflow.com/comment/91790126
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52421855
has text: This is the duplicate of [this question](https://stackoverflow.com/questions/28154448/efficiently-grouping-the-rows-of-a-pandas-dataframe-by-the-value-of-a-column)
score: 0

http://stackoverflow.com/comment/91526964
has text: I think question is about performance, so reopened.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52289488
score: 1

http://stackoverflow.com/a/52361944
type: Answer
accepted answer of: http://stackoverflow.com/q/52361751
has comment: http://stackoverflow.com/comment/91668142
score: 2
answers question: http://stackoverflow.com/q/52361751
upvote count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/91668191
type: AcceptedAnswer
has body: The ?/? at the end of the first regex makes the email optional. I don't know what you have in the urls list, but I suggest you try your regex here https://regex101.com/ so you can debug easily any url.

http://stackoverflow.com/q/52298277
has body: http://finance.daum.net/item/main.daum?code=052400 ** This is a Korean finance web portal, which shows stock information for a Korean company named "Kona i" I'm a beginner, just started learning web scraping with Python. I was trying to scrape the price of this stock using BS. In the web page, the tag and the class of the stock price was em, "curPrice up" respectively. So I put "em.curPrice up" in the selector part. And when I printed it, only to come up with an empty list. What is the problem with it? price = requests.get("http://finance.daum.net/item/main.daum?code=052400") html = bs(price.text, "lxml") current_price = html.select("em.curPrice up")
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52298364
type: UnansweredQuestion
tagged with: web-scraping
tagged with: python
has title: Some classes are not scraped in Python web scraping
tagged with: web-crawler
has comment: http://stackoverflow.com/comment/91584592
type: Question

http://stackoverflow.com/comment/91658468
has text: If you're already in Excel, why don't you use [Excel solver](https://support.office.com/en-us/article/define-and-solve-a-problem-by-using-solver-5d1a388f-079d-43ac-a7eb-f63e45925040) right away?
comment on: http://stackoverflow.com/q/52355463
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91668283
score: 0
type: AnswerComment
type: Comment
has text: Too bad, but thanks. However, i remember in previous versions of Django (and maybe with different DB) it was not the case, Cascade was not there (by default).
comment on: http://stackoverflow.com/a/52361731

http://stackoverflow.com/q/52391118
has title: python to print item in list from a json post
score: -1
has body: I'm running Python 3.7 Flask RestFul I have data being post in json format to my api Flask app. the data i receive looks like the below: {'username': 'admin', 'password': 'mypassword', 'host': [{'address': '192.168.2.5', 'config': 'set system host-name device01', 'address': '192.168.2.2', 'config': 'set system host-name device02'}]} the List 'host': can be up to several hundred devices / ip address I need to parse thru the list and print out only the IP address and Config so I need to get it to be: 192.168.2.5 192.168.2.2 and so on.... so I can loop thru the IP address list and connect to the device and apply the config that will be different per device. The Structure I would need in return so I can loop thru and connect to device IP address then apply the config would be... 192.168.2.5 set system host-name device01 192.168.2.2 set system host-name device02 were the ip address would = ips and the config would = config my python code is below... app = Flask(__name__) api = Api(app) class build(Resource): def post(self): data = request.get_json(force=True) print(data) jobname = data['jobname'] username = data['username'] password = data['password'] configs = [] ips = [] for x in data['host']: if 'address' in x: ips.append(x['address']) elif 'config' in x: configs.append(x['config']) commands = zip(ips, configs) for command in commands: iplist = '{}'.format(command[0]) print(iplist) conf = '{}'.format(command[1]) print(conf) # Connect to Device and load config dev = Device(host=iplist, user=username, passwd=password) dev.open() print("connect to %s " % iplist) dev.timeout = 600 #print(dev.cli("show version")) dev.bind(cfg=Config) dev.cfg.load(conf, format='set', merge=True) dev.cfg.commit() dev.close() api.add_resource(build, '/build') if __name__ == '__main__': app.debug = True app.run(host='0.0.0.0', port=5000)
has answer: http://stackoverflow.com/a/52391322
answer count: 1
downvote count: 1
tagged with: flask
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91727370
upvote count: 0
has comment: http://stackoverflow.com/comment/91727435
type: UnansweredQuestion
type: Question

http://stackoverflow.com/comment/91544040
comment on: http://stackoverflow.com/q/52297189
score: 0
type: Comment
has text: Can you show us the code you have written so far?
type: QuestionComment

http://stackoverflow.com/comment/91805760
comment on: http://stackoverflow.com/a/52415536
type: AnswerComment
score: 0
has text: @tink, if you can give me the example of the problem fields I'll try to fix the script accordingly .
type: Comment

http://stackoverflow.com/comment/91633500
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52343765
has text: You should provide code which works with the OP's exact data. Cutting and pasting from another question doesn't help much.
score: 1

http://stackoverflow.com/q/52421581
has body: In my python code I got a few casts of bool() onto variables which I know are likely already Boolean. Are there any downsides to this? (Performance, etc.) Here's a basic clone of the function I'm using. import re pattern= "[A-Z]\w[\s]+:" other_cond= "needs_to_be_in_the_text" def my_func(to_check: str) -&gt; bool: res = re.search(pattern, to_check) res2 = other_cond in to_check return bool(res), bool(res2) # res2 either None or True # I need boolean returns because later in my code I add all these # returned values to a list and use min(my_list) on it. to see if # there's any false value in there. min() on list with None values causes exception
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52421599
has comment: http://stackoverflow.com/comment/91791445
has comment: http://stackoverflow.com/comment/91791241
has comment: http://stackoverflow.com/comment/91791565
has answer: http://stackoverflow.com/a/52424576
score: -1
has comment: http://stackoverflow.com/comment/91786300
linked to: http://stackoverflow.com/q/49009870
possible better answer: http://stackoverflow.com/a/52421599
type: Question
has title: Casting potential bool to bool in Python, any downsides?
tagged with: boolean
has answer: http://stackoverflow.com/a/52421698
downvote count: 1
favorite count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/91786279
tagged with: python
upvote count: 0
has comment: http://stackoverflow.com/comment/91790955
has comment: http://stackoverflow.com/comment/91792161
accepted answer: http://stackoverflow.com/a/52424576

http://stackoverflow.com/q/52416293
has comment: http://stackoverflow.com/comment/91778216
has comment: http://stackoverflow.com/comment/91778042
tagged with: django-models
has comment: http://stackoverflow.com/comment/91778292
has title: Django RelatedManager nesting to access nested fields
has comment: http://stackoverflow.com/comment/91778249
has comment: http://stackoverflow.com/comment/91778322
has comment: http://stackoverflow.com/comment/91778171
downvote count: 0
has comment: http://stackoverflow.com/comment/91777757
tagged with: django-rest-framework
favorite count: 0
has body: Models.py class Order(models.Model): order_name = models.CharField(max_length=10,unique = True, default = "") class LineItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True, related_name="items") product = models.ForeignKey(Product, on_delete=models.CASCADE,null=True, related_name="prod") quantity = models.IntegerField(default = 0) class Product(models.Model): product_name = models.CharField(max_length=10) product_price = models.DecimalField(max_digits=10,decimal_places=2) So I am trying to create an APIView PUT Request to be able to change Order contents. So my create method in OrderItemSerializer is not working correctly. I'm new to Django.. def update(self, instance, validated_data): So basically I am unable to complete this function. This is the structure of my instance - { "order_name": "OrderA", "line_items": [ { "product": { "id": 7, "product_name": "ProdA", "product_price": "23.99" }, "quantity": 2, "product_total": 47.98 }, { "product": { "id": 9, "product_name": "ProdC", "product_price": "19.99" }, "quantity": 23, "product_total": 459.77 } ], "cart_total": 507.75 } Serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['product_name','product_price'] class OrderSerializer(serializers.ModelSerializer): line_items = LineItemSerializer(many=True, source='items') class Meta: model = Order fields = ['order_name', 'line_items', 'cart_total'] def create(self, request): serialized = self.serializer_class(data=request.DATA) if serialized.is_valid(): serialized.save() return Response(status=HTTP_202_ACCEPTED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class LineItemSerializer(serializers.ModelSerializer): class Meta: model = LineItem depth =1 fields = ('product', 'quantity', 'product_total') Views.py class LineItemList(APIView): def get(self,request): lineitemlist = LineItem.objects.all() serializer = LineItemSerializer(lineitemlist,many = True) …
has comment: http://stackoverflow.com/comment/91777586
has comment: http://stackoverflow.com/comment/91797153
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/91777917
tagged with: python
has comment: http://stackoverflow.com/comment/91778095
has comment: http://stackoverflow.com/comment/91777927
answer count: 0
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/q/52356401
type: Question
tagged with: xlsxwriter
has comment: http://stackoverflow.com/comment/91657576
has comment: http://stackoverflow.com/comment/91657412
upvote count: 2
has body: I have imported the following data from Excel with pandas: import pandas as pd sht = pd.read_excel(path, 'Table', index_col=None, header=None, usecols = "A:C") sht.head() |-------+------------+----------| | jon | tyrion | daenerys | | sansa | cersei | rhaegar | | arya | jaime | 0 | | bran | tywin | 0 | | robb | 0 | 0 | | 0 | 0 | 0 | |-------+------------+----------| Then I created the following Series (D) in pandas: D = pd.Series((sht[sht!=0]).values.flatten()).dropna().reset_index(drop=True) D |----------| | jon | | tyrion | | daenerys | | sansa | | cersei | | rhaegar | | arya | | jaime | | bran | | tywin | | rob | |----------| How could I insert the Series D in the column D of sht (the "Table" sheet of my spreadsheet)? I tried: writer = pd.ExcelWriter(path, engine='openpyxl') K.to_excel(writer,'Table', startrow=0, startcol=4, header=False, index=False) writer.save() But it deletes all the other tabs from my spreadsheet and also erases the values in the A:C columns of my spreadsheet...
answer count: 2
has comment: http://stackoverflow.com/comment/91658817
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52356815
accepted answer: http://stackoverflow.com/a/52356815
tagged with: python
has title: How to insert a Pandas Series into a specific column of an existing Excel file (without deleting content from that file)?
possible better answer: http://stackoverflow.com/a/52356472
score: 2
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52356472
downvote count: 0
tagged with: openpyxl
has comment: http://stackoverflow.com/comment/91657512

http://stackoverflow.com/comment/91789922
type: AnswerComment
has text: Ok, this usually happens when we have a foreign key pointing to some non existent data.In your Bug model you have Project and Assigned_to as foreign keys, pointing to Project and User. Make sure that the data exists in those tables and is not invalid. That is why count (in Bug admin) is correct but it is not able to pull the record due to data inconsistency.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52368543

css-selectors
tags question: http://stackoverflow.com/q/52422266
tags question: http://stackoverflow.com/q/52273320
tags question: http://stackoverflow.com/q/52330140
tags question: http://stackoverflow.com/q/52321116
tag name: css-selectors
type: Tag

http://stackoverflow.com/q/52403554
type: UnansweredQuestion
has body: I'm trying to create a metric to optimize the precision of True Positives of the positive class in a Decision Tree classifier: metrica = make_scorer(precision_score, pos_label=1, greater_is_better=True, average="binary") And then using RandomizedSearchCV for hyperparameters tune: random_search = RandomizedSearchCV(clf, scoring= metrica, param_distributions=param_dist, n_iter=n_iter_search) I get the following result: Tunning the Tree with these parameters, I get zero percent of True Positives ... Simply changing splitter='random' to 'best', I get better at 82% accuracy in the positive class. What is failing in my metric or RandomSearchCV?
has title: Creating a metric for True Positives with make_scorer
type: Question
has answer: http://stackoverflow.com/a/52405480
tagged with: decision-tree
score: 0
tagged with: metrics
answer count: 1
tagged with: python

http://stackoverflow.com/comment/91749242
has text: I think you'll find that it works without the `break`. I'm not sure where you had the infinite loop, I didn't see any.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52402785
type: AnswerComment

http://stackoverflow.com/comment/91877978
score: 0
has text: Hi Zooba, Thanks a lot. After setting environment variables, this message is displayed 1>PYTHON_INCLUDE: C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\include 1>PYTHON_LIB: C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\libs 1>The system cannot find the path specified. 1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.CppCommon.targets(209,5): error MSB6006: "cmd.exe" exited with code 3. 1>Done building project "twslink2pt.vcxproj" -- FAILED.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52372039

http://stackoverflow.com/a/52406819
downvote count: 2
has body: Try changing this for i in range(10000): #Try increasing this value to >10k. Try 100k or higher You should be able to see an increase in accuracy thereafter.
upvote count: 0
score: -2
answers question: http://stackoverflow.com/q/52405276
has comment: http://stackoverflow.com/comment/91774561
has comment: http://stackoverflow.com/comment/91757931
type: Answer

http://stackoverflow.com/comment/91567955
comment on: http://stackoverflow.com/a/52310481
score: 0
type: AnswerComment
has text: One `split` for `items`, and the other `split` for `colours`. If the OP does not care about matching words and only needs substring match then there's no need for `c.split()` (for `colours`).
type: Comment

http://stackoverflow.com/comment/91788562
comment on: http://stackoverflow.com/a/52422673
has text: We can declare what column each calculation is about using it in the `.agg` with a dictionary?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52350257
has title: Python 3 set equality
has body: I use Python3. {1,2} == {1,2} returns True, but {1,2} is {1,2} returns false. It seems reasonable as id({1,2}) is different from another id({1,2}). However why id({1,2}) == id({2,1}) returns true? Even id({1,2}) == id({2,1,3}) returns true.
type: Question
has comment: http://stackoverflow.com/comment/91645915
has comment: http://stackoverflow.com/comment/91645882
downvote count: 0
duplicate of: http://stackoverflow.com/q/20753364
linked to: http://stackoverflow.com/q/3877230
has comment: http://stackoverflow.com/comment/91646017
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
answer count: 0
score: 1
tagged with: set
linked to: http://stackoverflow.com/q/24802740
tagged with: equality

http://stackoverflow.com/a/77735185
upvote count: 1
has comment: http://stackoverflow.com/comment/137046345
score: 1
has body: Just for the information, If you are using Django version &gt;= 4.1, they have introduced SecurityMiddleware that disables third-party cookies. As a result, you may encounter issues with the Power BI embedded iframe. I struggled with this. to allow third-party cookies you may need to configure SECURE_CROSS_ORIGIN_OPENER_POLICY in settings.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52322594

http://stackoverflow.com/comment/91574419
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52312853
has text: Yes. Sorry. See my similar comment to Naga above.

http://stackoverflow.com/comment/91804694
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52349503
has text: Okay, I will try that and get back to you. Thank you very much!
score: 0

http://stackoverflow.com/comment/91691597
type: QuestionComment
has text: @Prune My apologies, what do you want then? I provided the data and the code all you have to do is copy and paste and add the data into a notebook.
score: 0
comment on: http://stackoverflow.com/q/52372686
type: Comment

http://stackoverflow.com/a/55426109
has body: I am considering that you are using the tf.layers.batch_normalization function, since you are adding the update operations from tf.GraphKeys.UPDATE_OPS as dependencies. The problem with your code is that you define the dependencies that include the batch norm updates using the whole tf.GraphKeys.UPDATE_OPS collection. Whenever you create a batch norm layer with tf.layers.batch_normalization, the update ops for that layer is added to the tf.GraphKeys.UPDATE_OPS collection. Thus, in the first code block, which defines the uNet2D, the optimizer will have only the collection of batch norm updates for UNet2D as dependencies. But, when you create the attentionNetwork, more batch norm updates are added to tf.GraphKeys.UPDATE_OPS. Therefore, the dependencies for the optimizer of the attentionNetwork actually include all batch norm updates, including the ones for the uNet2D model. In order to solve that, you need to filter the batch norm updates for each model. If you are using scopes to create each model, for example, as in: with tf.variable_scope('unet2d'): # ... creation of the model uNet2D.. with tf.variable_scope('attention_network'): # ... creation of the model attentionNetwork.. you can use the scopes to filter the batch norm updates for each model: update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='unet2d') with tf.control_dependencies(update_ops): optimizer = tf.train.AdamOptimizer(learning_rate=LR[i]).minimize(W*cost, var_list=tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='unet2d')) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='attention_network') with tf.control_dependencies(update_ops): optimizer_d = tf.train.AdamOptimizer(learning_rate=0.2*LR[i]).minimize(cost_d, var_list=tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='attention_network')) One side note: make sure that the correct variables are used in the optimizers. Since you are not passing the variables to the parameter var_list in the minimization function…
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52304339

http://stackoverflow.com/a/52335191
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52324156
answers question: http://stackoverflow.com/q/52324156
has body: Comment as answer per OP's request: The problem here is that you're providing a path relative to the script, but relative paths are interpreted relative to the process's working directory, which is often completely different from the script location. The directory already exists relative to the working directory, but you're looking at a path relative to the script, and (correctly) finding nothing there. If the directory must be created relative to the script, change the code to: scriptdir = os.path.dirname(__file__) # abspath is just to simplify out the path so error messages are plainer # while os.path.join ensures the path is constructed with OS preferred separators newdir = os.path.abspath(os.path.join(scriptdir, '..', '..', 'dist')) os.makedirs(newdir)
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/91560815
score: 2
comment on: http://stackoverflow.com/q/52306809
has text: Assuming `myColumn = [...` is a quote from your code, you don't have strings with double backslashes. You have string _literals_ with double backslashes, which are understood by Python as strings with single backslashes. [Relevant documentation](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52423896
type: Answer
answers question: http://stackoverflow.com/q/52423641
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52423641
score: 2
type: AcceptedAnswer
downvote count: 0
has body: product={'Name': ['Small Pizza', 'Medium Pizza', 'Large Pizza'], 'Price': [5, 8, 12]} for i in range(0,len(product['Name'])): print("{}. {} :{}".format(i,product['Name'][i], product['Price'][i]))

http://stackoverflow.com/a/52511253
has comment: http://stackoverflow.com/comment/91969497
downvote count: 0
has comment: http://stackoverflow.com/comment/92100709
type: Answer
upvote count: 4
has body: current attempt In the following I have added a few lines before last lines of your code: d = ({'Time': ['8:03:00', '8:17:00', '8:20:00', '10:15:00', '10:15:00', '11:48:00', '12:00:00', '12:10:00'], 'Place': ['House 1', 'House 2', 'House 1', 'House 3', 'House 4', 'House 5', 'House 1', 'House 1'], 'Area': ['X', 'X', 'Y', 'X', 'X', 'X', 'X', 'X']}) df = pd.DataFrame(data=d) def g(gps): s = gps['Place'].unique() d = dict(zip(s, np.arange(len(s)) // 3 + 1)) gps['Person'] = gps['Place'].map(d) return gps df = df.groupby('Area', sort=False).apply(g) s = df['Person'].astype(str) + df['Area'] # added lines t = s.value_counts() df_sub = df.loc[s[s.isin(t[t &lt; 3].index)].index].copy() df_sub["tag"] = df_sub["Place"] + df_sub["Area"] tags = list(df_sub.tag.unique()) f = lambda x: f'R{int(tags.index(x) / 3) + 1}' df_sub['reassign'] = df_sub.tag.apply(f) s[s.isin(t[t &lt; 3].index)] = df_sub['reassign'] df['Person'] = pd.Series(pd.factorize(s)[0] + 1).map(str).radd('Person ') To be honest I am not so sure it works in all cases, but it gives your intended output in the test case. Previous attempts Let's see if I am able to help with a limited understanding of what you are trying to do. You have sequential data (I'll call them events) and you want to assign to each event a "person" identifier. The identifier you will assign on each successive event depends on previous assignments and it seems to me it need to be governed by the following rules to be applied sequentially: I know you: I can reuse a previous identifier if: same values for "Place" and "Area" already appeared for a given identifier (has time something to do with it?). I do NOT know you: I will create a new identifier if: a new value of Area appears (so Place and Area play different roles?). do I know you?: I might reuse a previously used identifier if: an identifier has not been assigned to at least three events (what if this happens for multiple identifiers? I will assume I use the oldest...). nah, I don't: in case …
has comment: http://stackoverflow.com/comment/91969271
has comment: http://stackoverflow.com/comment/92033037
score: 4
answers question: http://stackoverflow.com/q/52416796

http://stackoverflow.com/comment/91635771
has text: Here it turns out it does not matter, but it is good practice not to update and object over which you are iterating, making the `range` approach the preferred one.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52344942
score: 2

http://stackoverflow.com/comment/91541251
comment on: http://stackoverflow.com/q/52279355
has text: Why don't you separate it from the beginning and feed it to the network with two separate input layers for each one?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91509863
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52280469
has text: @appsdownload, Yes, hence the comment `For the specific format you see`.

binary-tree
tag name: binary-tree
type: Tag
tags question: http://stackoverflow.com/q/52363048

http://stackoverflow.com/q/52370844
tagged with: flask-babel
tagged with: pelican
type: Question
downvote count: 0
answer count: 1
has title: How to combine two mechanism for localization site written on Pelican?
favorite count: 0
has body: I use two mechanisms for localization site: 1. I use the standard template tag {{ gettext 'some_text'}} in my index.html 2. I wrote custom jinja extension that takes the content of markdown file according to language that used on the site. And I use Babel to create messages.pot file and then to create massages.po file. I have this babel configuration in babel.cfg : [jinja2: theme/templates/index.html] silent = false And this is my custom jinja extension - custom_jinja_extension.py : from jinja2 import nodes from jinja2.ext import Extension from markdown import Markdown class IncludeMarkdownExtension(Extension): """ a set of names that trigger the extension. """ tags = set(['include_markdown']) def __init__(self, environment): super(IncludeMarkdownExtension, self).__init__(environment) def parse(self, parser): tag = parser.stream.__next__() ctx_ref = nodes.ContextReference() if tag.value == 'include_markdown': args = [ctx_ref, parser.parse_expression(), nodes.Const(tag.lineno)] body = parser.parse_statements(['name:endinclude_markdown'], drop_needle=True) callback = self.call_method('convert', args) return nodes.CallBlock(callback, [], [], body).set_lineno(tag.lineno) def convert(self, context, tagname, linenum, caller): """ Function for converting markdown to html :param tagname: name of converting file :return: converting html """ for item in context['extra_siteurls']: if item == context['main_lang']: input_file = open('content/{}/{}'.format('en', tagname)) else: input_file = open('content/{}/{}'.format(context['main_lang'], tagname)) text = input_file.read() html = Markdown().convert(text) return html I use this template tag - {% include_markdown 'slide3.md' %}{% endinclude_markdown %} In my pelicanconf.py I add such strings for jinja extensions: # Jinja2 extensions JINJA_ENVIRONMENT = { 'extensions': [ 'jinja2_markdown.MarkdownExtension', 'jinja2.ext.i18n', 'custom_jinja_extension.IncludeMarkdownExtension' ] } When I run the command: pybabel extract --mapping bab…
has answer: http://stackoverflow.com/a/52587357
tagged with: python
score: 1
type: UnansweredQuestion
tagged with: localization
upvote count: 1
tagged with: jinja2

http://stackoverflow.com/q/52322381
type: Question
accepted answer: http://stackoverflow.com/a/52373570
tagged with: aws-glue
tagged with: pyspark
downvote count: 0
tagged with: amazon-web-services
has body: When I run the Glue job boilerplate in AWS Glue using Python, I get an error import sys from awsglue.transforms import * from awsglue.utils import getResolvedOptions from pyspark.context import SparkContext from awsglue.context import GlueContext from awsglue.job import Job glueContext = GlueContext(SparkContext.getOrCreate()) spark = glueContext.spark_session args = getResolvedOptions(sys.argv, ['JOB_NAME']) job = Job(glue_context) job.init(args[‘JOB_NAME’], args) Here's the error in getResolvedOptions File "/usr/lib64/python2.7/argparse.py", line 1733, in parse_known_args namespace, args = self._parse_known_args(args, namespace) File "/usr/lib64/python2.7/argparse.py", line 1957, in _parse_known_args self.error(_('argument %s is required') % name) awsglue.utils.GlueArgumentError: argument --JOB_NAME is required This follows my code and then job.commit() But AWS says do not provide JOBNAME. What am I doing wrong? And also what does getResolved do? I tried reading AWS documentation but couldn't get anything.
has answer: http://stackoverflow.com/a/60532965
score: 8
has answer: http://stackoverflow.com/a/52336808
favorite count: 0
has answer: http://stackoverflow.com/a/59606516
upvote count: 8
answer count: 5
has answer: http://stackoverflow.com/a/52373570
tagged with: python
possible better answer: http://stackoverflow.com/a/52336808
has answer: http://stackoverflow.com/a/63981466
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91618171
has title: awsglue.utils.GlueArgumentError: argument --JOB_NAME is required

http://stackoverflow.com/comment/91512787
score: 0
type: Comment
type: AnswerComment
has text: I have a CloudTrail turned on that monitors object-level activities (for all s3 buckets, including read and write activities), however, when I try to list "PutObject" events in my update above, it doesn't work (i.e. the list of events comes up blank).
comment on: http://stackoverflow.com/a/52281584

http://stackoverflow.com/comment/91671732
has text: @FHTMitchell Indeed. I've updated my answer accordingly then.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52363526
type: Comment

http://stackoverflow.com/q/52428025
score: -2
has comment: http://stackoverflow.com/comment/91799665
has comment: http://stackoverflow.com/comment/91799588
has answer: http://stackoverflow.com/a/52432694
answer count: 2
has comment: http://stackoverflow.com/comment/91799511
has comment: http://stackoverflow.com/comment/91799547
tagged with: pandas
has comment: http://stackoverflow.com/comment/91799850
has comment: http://stackoverflow.com/comment/91800107
has answer: http://stackoverflow.com/a/53864407
favorite count: 0
has body: I am pre-processing a large dataset with 840.000 samples and more than 400 features. I need to store dataframes in single csv files to reduce memory. THEREFORE, I should avoid pd.concat since it takes loads of memory I have different dataframes, depending on the nature of the variables. How can I append CSV files by columns? It seems that: df_1.to_csv('file.csv', index=False) df_2.to_csv('file.csv', mode='a', index=False) df_3.to_csv('file.csv', mode='a', index=False) Creates the file file.csv, and then append df_2, and df_3 just below each other. How can I append it by columns and not by rows? EXAMPLE: DF1 row1: variable_a variable_b row2: 0 1 row3: 1 1 row839999: 0 1 DF2: row1: variable_c variable_d row2: 0 1 row3: 1 1 row839999: 0 1 FINAL DF row1: variable_a variable_b variable_c variable_d row2: 0 1 0 1 row3: 1 1 1 1 row839999: 0 1 0 1
has comment: http://stackoverflow.com/comment/91799527
has title: How can I append pandas data frames to CSV files COLUMN-WISE?
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
upvote count: 1
tagged with: python
downvote count: 3
type: Question

cvxpy
tags question: http://stackoverflow.com/q/52289930
type: Tag
tag name: cvxpy
tags question: http://stackoverflow.com/q/52314581

http://stackoverflow.com/a/52329290
has comment: http://stackoverflow.com/comment/91629585
score: 1
type: Answer
has body: The issue here is that you are not generating a list but a string. In data_2_days, you return a list which containts 2 tuples of 3 elements. In figure_probs, when you iterate over this list, you get on tuple at each iteration that you can split in 3 elements. In data_start_and_end, you generate a string representing a list of tuples of 3 elements. Then, in figure_probs, when you iterate over this string, you get 1 character at each iteration and the python interpreter returns the ValueError because you try to split this single character in 3. Change your data_start_and_end function to generate a list of tuple and it should work fine. def data_start_and_end(start_date,end_date): start_date = DateTime.strptime(start_date, '%Y-%m-%d') end_date = DateTime.strptime(end_date, '%Y-%m-%d') no_days = (end_date-start_date).days list_dates = [] x = 0 current_date = start_date while x &lt;= no_days: if date.month &lt; 10: month_str = "0"+str(current_date.month) else: month_str = str(current_date.month) if date.day &lt; 10: day_str = "0"+str(current_date.day) else: day_str = str(current_date.day) list_dates.append((str(current_date.year), month_str, day_str)) current_date = current_date + TimeDelta(days=1) x = x + 1 return list_dates On a side note, return is a statement in python and do not need parenthesis. I think you can also get read of the variable x and just iterate while date &lt;= end_date.
answers question: http://stackoverflow.com/q/52327787
upvote count: 1
downvote count: 0

http://stackoverflow.com/a/52389688
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52389401
has comment: http://stackoverflow.com/comment/91724276
type: Answer
has body: Better yet, don't use a global variable. Pass the desired data frame as an argument. from datetime import datetime import pandas as pd def do_stuff_and_append_df(df): dt = datetime.now() row = dict.fromkeys(df.columns.tolist()) row['datetime'] = dt row['pduType'] = 'blah' df = df.append(row, ignore_index=True) print(df.head()) return df def main(): # empty dataframe for appending header = ['datetime', 'pduType'] df = pd.DataFrame(columns=header) # Main loop try: while True: df = do_stuff_and_append_df(df) except KeyboardInterrupt: print('\nSaving and exiting.') df.to_csv('data.csv') main()
upvote count: 1

http://stackoverflow.com/a/52299996
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52286106
has body: You can get around this issue by rebuilding the listctrl using the list t_col1. import wx from wx.lib.agw import ultimatelistctrl as ULC class Mywin(wx.Frame): t_col1 = ['PICTURE 1', 'PICTURE 2', 'PICTURE 3', 'PICTURE 4', 'PICTURE 5', 'PICTURE 6', 'PICTURE 7'] t_col4 = ['1', '1', '3', '5', '5', '1', '2'] def __init__(self, parent, title): wx.Frame.__init__(self, parent) box2 = wx.BoxSizer(wx.VERTICAL) title = wx.StaticText(self, wx.ID_ANY, label='Pictures On Frame:') box2.Add(title, 0, wx.ALL, 5) self.list = ULC.UltimateListCtrl(self, agwStyle = ULC.ULC_REPORT | ULC.ULC_HAS_VARIABLE_ROW_HEIGHT) colhead = ["", "File", "Ext", "Size", "Rating"] colwidth = [30, 300, 45, 45, 45] for x in range(0, len(colhead)): self.list.InsertColumn(x, colhead[x], width=colwidth[x]) box2.Add(self.list, 1, wx.EXPAND) btnSizer2 = wx.BoxSizer(wx.HORIZONTAL) btnC = wx.Button(self, label="Clear") btnC.Bind(wx.EVT_BUTTON, self.on_clear) btnSizer2.Add(btnC, 0, wx.ALL | wx.CENTER, 5) box2.Add(btnSizer2, 1, wx.EXPAND) self.SetSizer(box2) self.SetTitle('Picture Frame Selector') self.Centre() self.Maximize() self.CreateList() self.Show() def CreateList(self): rb_list = ["1", "2", "3", "4", "5"] for x in range(0 , len(self.t_col1)): self.list.InsertStringItem(x, '') cBox = wx.CheckBox(self.list) self.list.SetItemWindow(x, 0, cBox) self.list.SetStringItem(x, 1, self.t_col1[x]) self.list.SetStringItem(x, 2, '.jpg') dBox = wx.ComboBox(self.list, value=self.t_col4[x], choices=rb_list, style=wx.CB_READONLY) self.list.SetItemWindow(x, 4, dBox, expand=True) def on_clear(self, event): for x in range(len(self.t_col1) -1 , -1, -1): if self.list.GetItemWindow(x, 0).IsChecked(): self.t_col1.pop(x) self.list.DeleteAllItems() self.CreateList() event.Skip() if __name__ == "__main__": ex = wx.App() Mywin(None, 'Row Delete Issue') ex.MainLoop() Note that items are removed from the list in reverse, for obvious reasons and I use list.pop() so that I can use its position from range rather than list.remove() I have not…
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52286106
has comment: http://stackoverflow.com/comment/91558365

http://stackoverflow.com/q/52402163
type: Question
tagged with: multiprocessing
has answer: http://stackoverflow.com/a/52402588
has title: Python multiprocessing hangs on pool.map
has body: I am trying to apply python multiprocessing module to create multiple spss (.sav) fles. But, unfortunately it is getting hanged for hours and I have to ultimately forse stop the process to kill the process. Please find the code snippet below, import csv import os import copy import sys import savReaderWriter from functools import partial def write_to_savfile(metadata_dict, exported_file): sav_file_name = exported_file[:-4] + ".sav" with savReaderWriter.SavWriter(savFileName=sav_file_name, varNames=metadata_dict['var_names'], varTypes=metadata_dict['var_types'] , varLabels=metadata_dict['var_labs'], missingValues=metadata_dict['miss_vals'], valueLabels=metadata_dict['value_labels'] , measureLevels=metadata_dict['measure'], columnWidths=metadata_dict['col_width'], formats=metadata_dict['allFmt'] , ioLocale='en_US.UTF-8' , ioUtf8=True) as writer: try: variable_position = metadata_dict["varPostion"] template=[-1.7976931345812589e+208]*(len(variable_position)) stringVars=[metadata_dict['var_names'].index(k) for k, v in metadata_dict['var_types'].items() if v&gt;0] for z in stringVars: template[z]=u"" lastCase="-125485698569" tline=copy.copy(template) outLines = [] freshStart=0 fileIn=open(exported_file,"r") for lineToProcess in fileIn: lineSplit=lineToProcess[:-1].split("~!#") if lineSplit[1]!=lastCase and freshStart==0: outLines.append(tline) tline=copy.copy(template) tline[0]=lineSplit[0] #tline[1]=lineSplit[1] lastCase=lineSplit[1] tline[variable_position[lineSplit[2]]]=lineSplit[3] freshStart=0 outLines.append(tline) outLines.pop(0) # First element is the blank template print "Writing data to .zsav file for survey "+str(exported_file) for record in outLines: writer.writerow(record) print "done: ",exported_file except Exception as e: print e raise Exception('Failed to create .sav File' + str(e)) if __name__ == "__main__": sorted_file_names = ['1.csv','2.csv','3.csv'] metadata_dict = {some dictionary used in the above function} pool = mp.Pool(processes=mp.cpu_count()) …
score: 0
has comment: http://stackoverflow.com/comment/91748301
answer count: 1
has comment: http://stackoverflow.com/comment/91748391
has comment: http://stackoverflow.com/comment/91748782
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/91729295
type: Comment
has text: Feel free to store the old surface in some variable and remove it before plotting a new one.
score: 1
comment on: http://stackoverflow.com/q/52379426
type: QuestionComment

http://stackoverflow.com/a/52423095
has body: First you have to have a specific xml to detect only cars.You can get it from the here.I have developed a code just to uniquely identify and count the cars that are visible to the cctv you are using,sometimes it totally depends on the frame rate and detection too,so you can control the frame rate and also the total count variable. import cv2 cascade_src = 'cars.xml' cap = cv2.VideoCapture('rtsp_of_ur_cctv') car_cascade = cv2.CascadeClassifier(cascade_src) prev_count=0 total_count=0 while True: ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cars = car_cascade.detectMultiScale(gray, 1.1, 1) if len(cars)&gt;prev_count: diffrence=len(cars)-prev_count total_count=total_count+diffrence #here yo can save unique new entry and possibly avoid the recursive ones print(total_count) for (x,y,w,h) in cars: cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2) prev_count=len(cars) cv2.imshow('video', img) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
score: 0
answers question: http://stackoverflow.com/q/52422060
type: Answer

http://stackoverflow.com/comment/91676220
comment on: http://stackoverflow.com/a/52337825
type: AnswerComment
score: 0
has text: I'm not familiar with nltk, so I don't know. But please [ask a new question](https://stackoverflow.com/help/how-to-ask) if you have doubst or problems that are different from this question.
type: Comment

http://stackoverflow.com/comment/91596135
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52324538
has text: Please read [ask] and [tour]. If you have any specific questions about *programming* you're welcome to ask here.

http://stackoverflow.com/q/52389105
has body: I was going through Apache Airflow tutorial https://github.com/hgrif/airflow-tutorial and encountered this section for defining task dependencies. with DAG('airflow_tutorial_v01', default_args=default_args, schedule_interval='0 * * * *', ) as dag: print_hello = BashOperator(task_id='print_hello', bash_command='echo "hello"') sleep = BashOperator(task_id='sleep', bash_command='sleep 5') print_world = PythonOperator(task_id='print_world', python_callable=print_world) print_hello &gt;&gt; sleep &gt;&gt; print_world The line that confuses me is print_hello &gt;&gt; sleep &gt;&gt; print_world What does >> mean in Python? I know bitwise operator, but can't relate to the code here.
tagged with: bit-shift
type: Question
has comment: http://stackoverflow.com/comment/91723308
tagged with: airflow
has title: How >> operator defines task dependencies in Airflow?
score: 50
has comment: http://stackoverflow.com/comment/105893803
has answer: http://stackoverflow.com/a/52389312
answer count: 1
accepted answer: http://stackoverflow.com/a/52389312
has comment: http://stackoverflow.com/comment/91723214
tagged with: operators
favorite count: 0
has comment: http://stackoverflow.com/comment/91723362
tagged with: python
has comment: http://stackoverflow.com/comment/91723159
type: AnsweredQuestion
downvote count: 0
upvote count: 50

http://stackoverflow.com/q/52275985
type: UnansweredQuestion
tagged with: python
has title: What is the difference between "ImportError: DLL load failed" and "ImportError: cannot import name"?
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/91511923
score: 0
has comment: http://stackoverflow.com/comment/91499825
has comment: http://stackoverflow.com/comment/91500597
linked to: http://stackoverflow.com/q/42863505
has body: The statement from PyQt5 import QtWidgets yields ImportError: DLL load failed: The specified module could not be found., but the statement from PyQt5 import sdklfjsdlfkj yields ImportError: cannot import name 'dfgdfgdfg'. This is confusing to me, because it's not like in the first snippet I'm trying to import something from QtWidgets. I mean, the QWidgets module is either there or it isn't, right? How is it possible that it's there "enough" to avoid a cannot import name, but also not there enough to be able to import it?
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91499692

http://stackoverflow.com/comment/91771513
type: Comment
type: QuestionComment
has text: @AlexanderReynolds I need them to be together because I am taking this mask and using it to measure length and girth of the object. So these gaps create an area where I can't measure girth. Basically I want to interpolate from those edges to complete the shape so I can measure it.
comment on: http://stackoverflow.com/q/52411321
score: 0

interactive
tags question: http://stackoverflow.com/q/52428900
type: Tag
tag name: interactive

http://stackoverflow.com/a/52409738
downvote count: 0
answers question: http://stackoverflow.com/q/52409631
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91763400
accepted answer of: http://stackoverflow.com/q/52409631
has body: According the the quote you gave from the documentation, the API uses TCP. You can access this with any networking library in any language, including Python. To start, you will need to learn the basics of TCP. A google search will lead you to the technical documentation. An RFC gives the official specification. Then you will need a Python library to open a network connection and send binary data. Finally, you will need to read the documentation for the API.
has comment: http://stackoverflow.com/comment/91763552
type: AcceptedAnswer

http://stackoverflow.com/q/52282544
has comment: http://stackoverflow.com/comment/91547865
has comment: http://stackoverflow.com/comment/91516316
score: 0
has comment: http://stackoverflow.com/comment/91569998
has body: I am trying to count the number of rows in a pyspark.sql.dataframe.DataFrame. I do that with: stack_sub_jdf2.count() which gives the following error: Py4JJavaError: An error occurred while calling o2540.count. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 23 in stage 57.0 failed 4 times, most recent failure: Lost task 23.3 in stage 57.0 (TID 1703, dedwfprshd056.de.neustar.com, executor 151): java.lang.ClassCastException: org.apache.hadoop.io.Text cannot be cast to org.apache.hadoop.io.IntWritable The dataframe looks like: DataFrame[mid: string, maf_pid: string, true_email_pid: int, address_current_score_max: int, address_date_max: int, distance_min: double, n_did_min: bigint, n_ekeys_email_min: bigint, gender_code_max: int, is_telco_phone_cust_max: int, is_deceased_min: int, is_key_record_max: int, is_names_swapped_min: int, dob_quick_fill_min: int, dob_date_max: int, phone_date_max: int, first_name_in_email_max: int, last_name_in_email_max: int, middle_initial_in_email_max: int, is_default_zip9_max: int, confidence_score_max: int, label: int, strsplit_address_source_exploded_index1: vector, strsplit_email_source_exploded_index1: vector, address_current_code_max_index1: vector, ethnicity_max_index1: vector, er_matching_rule_max_index1: vector, age_bucket_max_index1: vector, email_verification_code_strings_index1: vector, dpc_index1: vector] What should I do to troubleshoot? I'm guessing the problem is one of the columns in the dataframe and I have experimented with removing columns without luck. For example, I created a dataframe stack_sub_jdf3 with a single variable: stack_sub_jdf3.printSchema() root |-- address_date_max: integer (nullable = true) But I get the same result: stack_sub_jdf3.count() Py4JJavaError: An error occurred while calling o2824.count. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 4 in stage 69.0 failed 4 times, most recent failure: Lost task 4.3 in stage 69.0 (TID 1808, dedwdprshc028.de.ne…
has comment: http://stackoverflow.com/comment/91547863
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91526666
answer count: 0
has title: PySpark: dataframe cannot be count()
has comment: http://stackoverflow.com/comment/91562445
type: Question
tagged with: pyspark

github
tags question: http://stackoverflow.com/q/52286025
tags question: http://stackoverflow.com/q/52282250
tags question: http://stackoverflow.com/q/52323897
tag name: github
type: Tag
tags question: http://stackoverflow.com/q/52400481

http://stackoverflow.com/comment/91754612
has text: Yes it has a context manager. Just ran the code now and the threads don't run up if you use the context manager.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52405433
type: AnswerComment

http://stackoverflow.com/q/52368027
has comment: http://stackoverflow.com/comment/91680403
upvote count: 1
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52368126
has body: My dictionaries that include names of characters and their offsets look like this: {'Amestris': [(2247, 2255)], 'Beda': [(3266, 3270)], 'Fuery': [(2285, 2290), (2380, 2385), (2686, 2691), (2723, 2728), 'Gloria': [(1565, 1571)], 'Hawkeye': [(22, 29), (832, 839), (999, 1006), (1119, 1126), (1927, 1934), (3007, 3014), (4068, 4075)]} My desired output would be the keys of the dictionary (the character names). In addition, the first column should be enumerating the character names as their Ids, starting from 0. The tab-delimited csv file should look like this: Id Label 0 Amestris 1 Beda 2 Fuery 3 Gloria 4 Hawkeye So far I've reached this point: import csv import pickle exmen = pickle.load(open("exmen.p", "rb")) with open('mycsvfile.csv', 'w') as f: i = 0 fieldnames = ['Id', 'Label'] w = csv.writer(f, delimiter=' ', fieldnames=fieldnames) w.writeheader() w.writerow(i(dict(fieldnames, (key))) for key in exmen) I'm getting this error message: line 28, in &lt;module&gt; w = csv.writer(f, delimiter=' ', fieldnames=fieldnames) TypeError: 'fieldnames' is an invalid keyword argument for this function I'm not sure how to include the headers Id and Label other than using fieldnames and how to implement the enmuerating of the rows, here I tried to apply i = 0 and tried to find somewhere in the last line to apply an i += 1 but it gave me the error warning syntax error Any ideas for improving the code? Thanks in advance!
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52368126
tagged with: enumerate
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91680275
type: Question
has title: Keys of a dictionary of lists to a row-enumerated, tab-delimited csv file
tagged with: key

http://stackoverflow.com/a/52309493
upvote count: 1
answers question: http://stackoverflow.com/q/52309157
score: 1
type: AcceptedAnswer
has body: \r is carriage return which places "the cursor" at the beginning of the line. If you don't want to actually perform a carriage return don't include it in the input: print(scannerData.replace('\r', ''), end='')
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52309157
type: Answer

http://stackoverflow.com/comment/91576510
comment on: http://stackoverflow.com/a/52303518
score: 0
has text: You're welcome. If you found this was useful, please consider [accepting it](https://stackoverflow.com/help/someone-answers) as the answer to your question.
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52420351
type: Answer
has comment: http://stackoverflow.com/comment/91784320
has comment: http://stackoverflow.com/comment/91784254
has body: I have used the traditional minimax algorithm without pruning . And that is already the answer to your question. This is why pruning and remembering past states is such an important topic in algorithmic design. If you increase the board size to 4x4 you'll have exponential growth and experience an explosion of computational time. If you estimate the possible number of moves in a 3x3 board, you will have (3x3)! = 9!, which equals 362 880 moves. If you now do this for the possible moves on a 4x4 board, you will get 16! possible states, which is an incredibly large amount of 20 922 790 000 000 possible moves. Although these are just approximations, you can estimate that your computational time must be more than a million times higher. For further explanation see: Tic-Tac-Toe minimax algorithm doesn&#39;t work with 4x4 board
upvote count: 2
has comment: http://stackoverflow.com/comment/91784213
score: 2
answers question: http://stackoverflow.com/q/52419756
has comment: http://stackoverflow.com/comment/91784870
accepted answer of: http://stackoverflow.com/q/52419756
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91783931

http://stackoverflow.com/comment/91752400
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52381492
type: Comment
has text: There are 12 pages and total 72 results. However, every time I run the program it returns a random number of results. Sometimes its 36 and other time it's 41. The program is not consistent.

http://stackoverflow.com/comment/91561308
type: Comment
score: 0
has text: @a_python_user gevent==1.0.2
comment on: http://stackoverflow.com/q/52306938
type: QuestionComment

http://stackoverflow.com/q/52338532
favorite count: 0
has answer: http://stackoverflow.com/a/52365983
has body: I created this demo to demonstrate an error thrown from the library internals. This code splits dataset into train/eval/test and uses train/eval for hyper-parameter search, early stopping, while the test set is hold out for later evaluation. I narrowed down the error to be related to cross validation of GridSearchCV but I couldn't figure out the exact root cause and fix. from sklearn import svm, datasets from sklearn.model_selection import GridSearchCV from sklearn.model_selection import train_test_split import numpy as np import pandas as pd import xgboost as xgb iris = datasets.load_iris() df = pd.DataFrame(data=np.c_[iris['data'], iris['target']], columns=iris['feature_names'] + ['target']) X, y = df'sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)', df['target'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) X_train_split, X_eval_split, y_train_split, y_eval_split = train_test_split(X_train, y_train, test_size=0.25, random_state=42) parameters = { 'max_depth': (2, 3, 4), } fit_params = { 'early_stopping_rounds': 2, 'eval_set': (X_eval_split, y_eval_split), } model = xgb.XGBClassifier() gs = GridSearchCV(model, parameters, cv=3) gs.fit(X_train_split, y_train_split, **fit_params) However I'm receiving this obscure message: Traceback (most recent call last): File "/Users/foo/bar/.env/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 3078, in get_loc return self._engine.get_loc(key) File "pandas/_libs/index.pyx", line 140, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/hashtable_class_helper.pxi", line 1492, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas/_libs/hashtable_class_helper.pxi", line 1500, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 0 During handling of the above exception, another exception occurred: Traceback (most recent call last):…
tagged with: python
accepted answer: http://stackoverflow.com/a/52365983
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/52339482
type: Question
tagged with: scikit-learn
possible better answer: http://stackoverflow.com/a/52339482
has comment: http://stackoverflow.com/comment/91625700
answer count: 2
tagged with: pandas
score: 3
has title: "KeyError: 0" with xgboost, scikit-learn and pandas
downvote count: 0
tagged with: xgboost

http://stackoverflow.com/comment/91770174
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52413178
type: AnswerComment
has text: @mad_ I added a way using `all()`.

http://stackoverflow.com/comment/91642883
comment on: http://stackoverflow.com/q/52348044
score: 0
has text: ok another thing is there anyway to use jitter or anything to reduce the shape size of the dots then? @ImportanceOfBeingErnest
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52416781
has body: I'm told to condense this in python in a more simplified form. Is it possible to do so in an orderly manner? (not ((b or not c) and (not a or not c))) or (not (c or not (b and c))) or (a and not c) and (not a or (a and b and c) or (a and ((b and not c) or (not b)))) (not (a and not b) or (not c and b)) and (not b) or (not a and b and not c) or (a and not b))
type: Question
has comment: http://stackoverflow.com/comment/91776911
tagged with: boolean-logic
answer count: 1
has title: How to simplify these boolean statements
favorite count: 0
upvote count: 0
downvote count: 5
has answer: http://stackoverflow.com/a/52417157
type: UnansweredQuestion
tagged with: boolean-expression
tagged with: python
has comment: http://stackoverflow.com/comment/91777085
tagged with: boolean-operations
has comment: http://stackoverflow.com/comment/91776957
score: -5

http://stackoverflow.com/q/52292765
favorite count: 0
has body: I have a list of US ZIP codes and I have to calculate distance between all the ZIP Code Points. Its a 6k ZIPs long list, each entity has ZIP, City, State, Lat, Long, Area and Population. So, I have to calculate distance between all the points, ie; 6000C2 combinations. Here is a sample of my data I've tried this in SAS but its too slow and inefficient, hence I'm looking for a way using Python or R. Any leads would be appreciated.
upvote count: 5
has comment: http://stackoverflow.com/comment/91535374
has comment: http://stackoverflow.com/comment/91544280
tagged with: python
has answer: http://stackoverflow.com/a/57466875
accepted answer: http://stackoverflow.com/a/57466875
has comment: http://stackoverflow.com/comment/91533588
type: AnsweredQuestion
has title: How to calculate Distance between two ZIPs?
has comment: http://stackoverflow.com/comment/91538241
has comment: http://stackoverflow.com/comment/91533770
possible better answer: http://stackoverflow.com/a/52295272
linked to: http://stackoverflow.com/q/40452759
has comment: http://stackoverflow.com/comment/91533512
type: Question
tagged with: sas
has answer: http://stackoverflow.com/a/52295272
score: 4
has answer: http://stackoverflow.com/a/52382689
tagged with: http://stackoverflow.com/tag/r
tagged with: distance
has comment: http://stackoverflow.com/comment/91533379
answer count: 3
tagged with: pandas
downvote count: 1
has comment: http://stackoverflow.com/comment/91554611

http://stackoverflow.com/comment/91610698
comment on: http://stackoverflow.com/q/52331595
score: 0
type: Comment
type: QuestionComment
has text: @PM2Ring, I've edited my question to explain my use case more thoroughly.

http://stackoverflow.com/comment/91734061
type: Comment
type: QuestionComment
score: 0
has text: https://docs.python.org/3.2/library/collections.html#deque-objects Near the bottom above the example, it explains the access times. https://wiki.python.org/moin/TimeComplexity Explains the general operations time complexities.
comment on: http://stackoverflow.com/q/52394415

http://stackoverflow.com/comment/91746227
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52401194
score: 3
has text: Add `new_string.replace(' ', '-')` just before printing it

http://stackoverflow.com/comment/91544054
has text: probably a bug in wxPython? Which version of {wx}Python do you have? Can you try with the latest release?
comment on: http://stackoverflow.com/q/52286106
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91584811
score: 1
comment on: http://stackoverflow.com/a/52318674
type: AnswerComment
has text: Please post an actual desired output we can verify, you've already changed your output twice
type: Comment

http://stackoverflow.com/q/52355953
answer count: 0
has title: ValueError: hour must be in 0..23 pandas.to_sql()
type: UnansweredQuestion
tagged with: python
has body: I have this code up and running in my other mac, when I moved to a new one I start to see this problem, they have the same timezone and I'm using the same Python version, digging a little bit I didn't find any useful tips to fix it, as i can see the data looks normal but for some reason the pandas.to_sql() is complaining about it: Update: Testing with Ubuntu Xenial - Python3.5 - Working Mac High Sierra 10.13.6 - Python3.7 - Not Working Mac High Sierra 10.13.5 - Python3.7 - Working Libs were being handled by the requirements.txt file. Example of my current data: 0 2017-09-13 10:05:00.009 1 2017-09-13 10:05:00.009 2 2017-09-13 10:05:00.009 3 2017-09-13 10:05:00.009 4 2017-09-13 10:05:00.009 5 2017-09-13 10:05:00.009 6 2017-09-13 10:05:00.009 And here is my sample code: def RetrieveData(filename=None, papel=None): df = pd.read_csv("%s" %(filename), header=None, delimiter="\;", skiprows=1, engine='python', names=["Session Date", "symbol", "Deal Number", "Deal Price", "volume", "Hour", "Ind Cancel", "Offer Date", "Seq Offer Date", "GenerationID", "Deal Condition", "Date Sell Offer", "Sequence Sell Offer", "Generation Id Sell", "Sell Condition", "Indicator", "Broker Buy", "Broker Sell"], ) df = df[df.symbol.str.contains(papel, na=False)] df['period'] = pd.to_datetime(df['Session Date']) + pd.to_timedelta(df['Hour']) print(df['period']) df.set_index('period', inplace=True) vol = df['volume'].resample('1d').sum() symbol = df['symbol'].resample('1d').sum() price = df['Deal Price'].resample('1d').ohlc() bars = pd.concat([price, vol, symbol], axis=1) bars.rename(columns={ 'open' : 'ohlc_open', 'close' : 'ohlc_close', 'high' : 'ohlc_high', 'low' : 'ohlc_low'}, inplace=True) engine = create_engine('sqlite:///database.db') bars.to_sql(name='symbol', con=engine, index=True, if_exists='append') My database definition: class Symbol(Base): __tablename__ = 'Symbol' id = Column(Integer, primary_key=True) symbol = Column(String(250), nullable=False) volume = Column(Integer, nullable=Fal…
has comment: http://stackoverflow.com/comment/91657534
type: Question
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/91656592
has comment: http://stackoverflow.com/comment/91656780

http://stackoverflow.com/a/52354191
type: Answer
accepted answer of: http://stackoverflow.com/q/52354164
answers question: http://stackoverflow.com/q/52354164
has body: The module inside matplotlib is called pyplot, not pylot. The pylot package on PyPI is entirely unrelated to matplotlib.
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91556746
comment on: http://stackoverflow.com/q/52303980
score: 0
has text: @mckuok it contains the exact same thing... You can easily reproduce my problem with the code I gave you and the paper I gave you in the post. I think I followed the MWE recommendations :). It's late here for me so I'll try to reply tomorrow.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52280858
answer count: 2
upvote count: 1
downvote count: 1
has title: Can't import functions from just created file
favorite count: 0
has comment: http://stackoverflow.com/comment/91510103
possible better answer: http://stackoverflow.com/a/52280913
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52280913
tagged with: python
type: AnsweredQuestion
type: Question
has body: In my code, I check if a file exists, and if it doesn't exist then I create it, like so: dir = (os.listdir('.')) if 'my_functions.py' not in dir: fdf = open('my_functions.py', 'w') fdf.write("""my function code here """) print(os.listdir('.')) from my_functions import function1, function2 This doesn't work, I get an error that says "ImportError: cannot import name 'function1'" Why is this? The print statement prints all the files in the directory, and I can see that my_functions.py is in the directory. If it's there, why can't it import the functions? I know it's not an issue with the my_functions.py code itself, because if I run it again (after my_functions.py has been created the first time) then it works without issues.
has answer: http://stackoverflow.com/a/52280895
accepted answer: http://stackoverflow.com/a/52280895
score: 0

http://stackoverflow.com/q/52352215
tagged with: raspberry-pi
has body: Traceback (most recent call last): devices = scanner.scan(arg.timeout) self._mgmtCmd(self._cmd()+"end") Failed to execute mgmt cmd '%s'" % (cmd)) bluepy.btle.BTLEException: Failed to execute mgmt cmd 'scanend'
tagged with: bluetooth
score: 0
has comment: http://stackoverflow.com/comment/91651114
answer count: 1
accepted answer: http://stackoverflow.com/a/54680291
has title: bluepy.btle.BTLEException: Failed to execute mgmt cmd 'scanend'
tagged with: python
has answer: http://stackoverflow.com/a/54680291
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/91612792
score: 1
comment on: http://stackoverflow.com/q/52332925
type: QuestionComment
has text: And if you simply have `form.errors` instead of `form.description.errors`, do you see any errors?
type: Comment

http://stackoverflow.com/q/52417517
upvote count: 3
has comment: http://stackoverflow.com/comment/91778264
has answer: http://stackoverflow.com/a/52417631
has title: Why the regex to match a project tag is not working?
answer count: 5
has answer: http://stackoverflow.com/a/52417637
has answer: http://stackoverflow.com/a/52417785
accepted answer: http://stackoverflow.com/a/52417631
type: AnsweredQuestion
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/91778242
has comment: http://stackoverflow.com/comment/91778290
possible better answer: http://stackoverflow.com/a/52417802
favorite count: 0
has body: Can anyone provide guidance on why the following regex is not working? project = 'AirPortFamily' line = 'AirPortFamily-1425.9:' if re.findall('%s-(\d+):'%project,line): print line EXPECTED OUTPUT:- AirPortFamily-1425.9
has answer: http://stackoverflow.com/a/52417802
has answer: http://stackoverflow.com/a/52417803
type: Question
tagged with: python

http://stackoverflow.com/comment/111923580
score: 1
has text: This still happens in 2020
comment on: http://stackoverflow.com/q/52361732
type: Comment
type: QuestionComment

http://stackoverflow.com/a/62421681
type: Answer
downvote count: 0
upvote count: 6
answers question: http://stackoverflow.com/q/52365190
has body: As ZdaR said: import cv2 import numpy as np img = cv2.imread("/home/user/Downloads/lena.png") blurred_img = cv2.GaussianBlur(img, (21, 21), 0) mask = np.zeros((512, 512, 3), dtype=np.uint8) mask = cv2.circle(mask, (258, 258), 100, np.array([255, 255, 255]), -1) out = np.where(mask==np.array([255, 255, 255]), img, blurred_img) cv2.imwrite("./out.png", out) This is good idea but I've got same error as penta: @ZdaR I get TypeError: Scalar value for argument 'color' is not numeric A simple solution is to modify color value when you create Circle: mask = cv2.circle(mask, (258, 258), 100, (255, 255,255), -1) just CHANGE np.array([255,255,255]) to (255,255,255).
score: 6

http://stackoverflow.com/comment/91726805
has text: But in all seriousness, I'd take a look at https://stackoverflow.com/questions/4760215/running-shell-command-from-python-and-capturing-the-output
score: 0
comment on: http://stackoverflow.com/q/52372187
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52343200
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/113210976
answers question: http://stackoverflow.com/q/52341748
accepted answer of: http://stackoverflow.com/q/52341748
type: AcceptedAnswer
has body: Found the answer. By adding source="workspace_set" in all the Serializer classes, the results can be achieved:- class WorkSpaceSerializer(serializers.ModelSerializer): projects = ProjectSerializer(many=True,read_only=True,source="workspace_set") class Meta: # depth = 2 model = WorkSpace fields = '__all__'
upvote count: 1

http://stackoverflow.com/comment/91554867
has text: I'd look in https://github.com/mehcode/python-xmlsec/issues and post additional details about your environment
comment on: http://stackoverflow.com/q/52303579
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/93989999
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52361660
type: Comment
has text: @wotter Regarding this. If I am fetching a list of all files in the directory and one or more of the file names contains spaces, how do I pass these filenames as arguments without having to do it manually. For example:- If am using the following code: `%run $script 'CMVOLT_01102018 (1).CSV'`, it runs as expected but when I am storing the file name 'CMVOLT_01102018 (1).CSV' in a variable `filename` and then running the same command: `%run $script $filename`, it gives me a FileNotFoundError: `File b'CMVOLT_01102018' does not exist` How do I deal with this?

http://stackoverflow.com/a/52495489
score: 4
type: Answer
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52428086
answers question: http://stackoverflow.com/q/52428086
has body: according to the uwsgi doc, you need to specify the external HTTP server address in form of HOST:PORT, for example, with config: route-if = equal:${PATH_INFO};/s http:220.181.111.188:80,www.baidu.com result: [pid: 5113|app: -1|req: -1/1] 127.0.0.1 () {24 vars in 249 bytes} [Tue Sep 25 17:58:33 2018] GET /s =&gt; generated 118322 bytes in 34 msecs via route() (HTTP/1.1 200) 18 headers in 944 bytes (0 switches on core 0)
type: AcceptedAnswer

http://stackoverflow.com/q/52274223
type: Question
upvote count: 2
tagged with: concatenation
has body: data=pd.concat(a,ignore_index=True,axis=0) a is a list of dataframes with different shape and columns but most of them are the same, I want to concatenate it into one dataframe but received an error. 'NoneType' object has no attribute 'is_extension'
tagged with: pandas
has answer: http://stackoverflow.com/a/52276298
answer count: 1
has title: pandas concatenate list of data frames with different columns python
has comment: http://stackoverflow.com/comment/91500345
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91496787
tagged with: python
has comment: http://stackoverflow.com/comment/91495792
score: 2
downvote count: 0
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91495813

telegram-bot
tags question: http://stackoverflow.com/q/52303725
tag name: telegram-bot
type: Tag

http://stackoverflow.com/comment/91693236
comment on: http://stackoverflow.com/q/52373652
has text: @danielleontiev: If you've got a more specific problem you can provide a [MCVE] for, I'd ask a new question focused on solving your real problem.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91528883
score: 0
has text: What is exactly the error or the unexpected behavior you get?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52290491

http://stackoverflow.com/comment/91644300
has text: Thank you so so much! there is one dot which is missed out, on the top left corner of the lemon. have any idea how to find it? I thought of making another check of Black/White values. What do you think?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52298872
type: Comment

http://stackoverflow.com/q/52429644
tagged with: python
score: 3
upvote count: 3
tagged with: pymongo
has body: I am trying to use PyMongo to upload a mixed set of date and text data to a new collection in my remote MongoDB server. However, I'm getting a error as a result of null values mixed in with dates—i.e. rows where there is a None value instead of a datetime.datetime() object. As some background: The raw data is stored in a CSV file, which I'm reading into a pandas.DataFrame() using pandas.read_csv(). Once I have the data in pandas, I do some rudimentary cleaning before transforming the data into a list of dictionaries, which I then upload to the collection using the standard collection.insert_many() method. Initially, the values in each row / document / dictionary are stored as strings. However, before uploading the data, I convert a number of date columns into datetime objects by calling datetime.datetime.strptime() on each value. Not every dictionary has these date fields populated, though. For these dictionaries, I simply use a None instead of a datetime object. The resulting data that I'm trying to upload, then, is a list of dictionaries with a number of NoneType values mixed in, and when I call insert_many() I get this: ValueError: NaTType does not support utcoffset. I'm not familiar with utcoffset, and my attempts to research this have confounded me. Has anyone run into this issue, or have suggestions on how to handle missing datetime data in PyMongo? Here's my code: import pandas as pd import pymongo source = '/path/to/data' sampleData = pd.read_csv(source, dtype=str) Date_Columns = [ 'date_a', 'date_b', 'date_c', 'date_d' ] cleanData = sampleData for col in Date_Columns: # Convert the strings to datetime objects for each column. # If a value is null, then use a None object instead of a datetime. Strings = sampleData[col].values Formats = [dt.datetime.strptime(d, '%m/%d/%Y') if isinstance(d, str) else None for d in Strings] cleanData[col] = Formats client = pymongo.MongoClient('XX.XX.XX.XX', 99999) db = client['my_db'] c = db['my_collection'] # Convert the clea…
type: Question
tagged with: mongodb
has title: PyMongo: NatType ValueError on Bulk Insert to New Collection
linked to: http://stackoverflow.com/q/42228292
has answer: http://stackoverflow.com/a/52429796
has comment: http://stackoverflow.com/comment/104223054
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52305559
type: UnansweredQuestion
tagged with: python
has body: I understand the procedure to approximate pi using Monte Carlo. What confuses me is how to ensure that you get the desired precision (say, 4 decimal place, 3.1416) using Monte Carlo? I tried to use a while loop ensuring the front digits are stabilized. However, the result does not converge to Pi. Could anyone help me spot the mistake in the code? from random import seed from random import random class Solution(object): def approximatePi(self): seed(323) allCount, circleCount = 0,0 oldPi, newPi = 0, 1 while int(oldPi * 4 * 100000) != int(newPi * 4 * 100000): x = random() y = random() allCount = allCount + 1 if x * x + y * y &lt; 1: circleCount = circleCount + 1 oldPi,newPi = newPi, circleCount / allCount print(oldPi, newPi) return 4 * newPi s = Solution() print(s.approximatePi())
answer count: 0
has comment: http://stackoverflow.com/comment/91558562
has title: Approximate pi using monte carlo to certain precision
type: Question
has comment: http://stackoverflow.com/comment/91595385
has comment: http://stackoverflow.com/comment/91595717
score: 0

http://stackoverflow.com/q/52353627
tagged with: moving-average
score: 0
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
tagged with: split-apply-combine
tagged with: python
accepted answer: http://stackoverflow.com/a/52353977
type: AnsweredQuestion
has body: I have a dataframe with the following columns: name, date, day_index, value I want to add a 4th column to the same dataframe which is the exponentially weighted moving average of the 3rd column (value) for each name, sorted by first date and then day_index. I can generate this as a series using the following code. df.sort_values(['date','day_index'],inplace=True) ecw_series = df.groupby('name').apply(lambda x: x["value"].ewm(halflife=2).mean()) However, if I try and directly add this to the original dataframe, I get the following error: df['ecw'] = df.groupby('name').apply(lambda x: x["value"].ewm(halflife=2).mean()) incompatible index of inserted column with frame index And if I try and merge the series with the dataframe I get the following error: df['index'] = df.index df = df.merge(ecw_series, left_on=['name','index'],right_index=True) can not merge DataFrame with instance of type &lt;class 'pandas.core.series.Series' At this point, I was considering converting the series to a dataframe, and then merging. But I am sure there must be a better way.
has title: Pandas - directly add moving average columns from group by to dataframe
has answer: http://stackoverflow.com/a/52353977
type: Question

http://stackoverflow.com/comment/91778737
type: Comment
type: QuestionComment
score: 0
has text: I'm trying to compare different naming schemes for the tags. So, for example, the same kind of information could be stored in two different files with two different tags called `<FinancialGroup>` and `<FinancialGrp>` or for have any number of other differences in the naming. Also, some files might have certain kinds of information and their corresponding tags in the first place, and some others might be missing some portion of those.
comment on: http://stackoverflow.com/q/52379601

http://stackoverflow.com/comment/91705332
type: Comment
type: QuestionComment
has text: @vikscool I am not sure about API, i am parsing different accounts which is bad, Instagram won't like it, and they ask tons of question, like where, why and how you will use it. At the end they just won't give permission
score: 1
comment on: http://stackoverflow.com/q/52380351

http://stackoverflow.com/q/52319398
favorite count: 0
has comment: http://stackoverflow.com/comment/91586226
has answer: http://stackoverflow.com/a/52320812
has body: ok so, i have a program that runs and every time it executes a code it writes a comment to a log file: def logger(event): event = str(event) current_date = datetime.datetime.now() current_time_for_log = current_date.strftime('%d-%m-%y %H:%M:%S --- ') date_file_name = current_date.strftime('%d-%m-%y') with open('{}'.format(date_file_name), 'a+') as log_file: log_file.write('-' * 50 + '\n' + '\n') log_file.write(current_time_for_log + event + '\n') if the file exist it will write to the file if it does not it creates the file and names it the current date(i.e 13-09-18) now what i want to accomplish and just cant figure out how to do using os.path.exist() is that every time i run the program is will check if there is a file with current date if not create it and if it does exist create a file with the same date but add '_1' to it: first time running the program- creates the file 13-09-18 second time """- creates the file 13-09-18_1 third time """- creates the file 13-09-18_2 etc... what happens when i use the os.path.exist() is at best i get an incrementing file names but it does that everytime the function is called so every comment gets a file with incrementing names instead of writing all the comments of the run to the same file..
tagged with: python
tagged with: logging
has comment: http://stackoverflow.com/comment/91586290
type: AnsweredQuestion
tagged with: filenames
score: 1
tagged with: file
upvote count: 1
accepted answer: http://stackoverflow.com/a/52320812
type: Question
has comment: http://stackoverflow.com/comment/91586359
has title: python | making a file and incrementing the name every run
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91586701

docker
tags question: http://stackoverflow.com/q/52327284
type: Tag
tags question: http://stackoverflow.com/q/52419849
tags question: http://stackoverflow.com/q/52326749
tags question: http://stackoverflow.com/q/52302361
tags question: http://stackoverflow.com/q/52382555
tags question: http://stackoverflow.com/q/52365838
tags question: http://stackoverflow.com/q/52331254
tags question: http://stackoverflow.com/q/52420714
tags question: http://stackoverflow.com/q/52374294
tags question: http://stackoverflow.com/q/52341979
tag name: docker
tags question: http://stackoverflow.com/q/52318670
tags question: http://stackoverflow.com/q/52347087
tags question: http://stackoverflow.com/q/52358107
tags question: http://stackoverflow.com/q/52317458
tags question: http://stackoverflow.com/q/52309527
tags question: http://stackoverflow.com/q/52338121
tags question: http://stackoverflow.com/q/52283535
tags question: http://stackoverflow.com/q/52408536
tags question: http://stackoverflow.com/q/52333769
tags question: http://stackoverflow.com/q/52294939
tags question: http://stackoverflow.com/q/52390678

http://stackoverflow.com/a/52442003
has comment: http://stackoverflow.com/comment/91828997
type: Answer
answers question: http://stackoverflow.com/q/52420147
has comment: http://stackoverflow.com/comment/91829238
accepted answer of: http://stackoverflow.com/q/52420147
has body: You can use BeautifulSoup to return all the element you want at the same time. You could then determine which one is being returned using elem.name and build up the necessary information for each row. As label comes last, you could use that to write the output row. Python has a CSV library to help you with this. It takes a list of values and correctly formats it as an output row. Normally you would not need to add quotes to everything, but as your expected output has this, you can add quoting=csv.QUOTE_ALL to force it to add it to all values. itemgetter() is just a useful function that can extract the require elements from Python data, e.g. a list or a dictionary in a single call. from bs4 import BeautifulSoup from operator import itemgetter import csv credential_fields = ['name', 'host', 'username', 'info', 'type', 'url', 'email'] get_fields = itemgetter(*credential_fields) with open('test.xml') as f_input: soup = BeautifulSoup(f_input, 'xml') with open('output.csv', 'w', newline='') as f_output: csv_output = csv.writer(f_output, delimiter=';', quoting=csv.QUOTE_ALL) csv_output.writerow(credential_fields + ['notes', 'label']) for elem in soup.find_all(['notes', 'credential', 'label']): if elem.name == 'notes': note = elem.get_text(strip=True).replace('\n', ' ') elif elem.name == 'credential': credential = list(get_fields(elem)) else: label = elem['id'] csv_output.writerow(credential + [note, label]) This would give you an output format: "name";"host";"username";"info";"type";"url";"email";"notes";"label" "somename";"somehost";"someusername";"someinfo";"LDAP";"3423";"33454";"";"1" "somename2";"somehost2";"someusername2";"someinfo2";"LDAP";"12";"34";"some noteasdasdasd";"4"
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91665402
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52360119
has text: @Kalanamith yeah. but there's no runtime difference. hehe. aesthetically - i agree with you, it's hard to read and debug...
type: AnswerComment

http://stackoverflow.com/q/52420357
accepted answer: http://stackoverflow.com/a/52420369
has title: 'contains' for numpy library?
has body: Something like this: This works: df.C = np.where((df.C.values == 'yes')), 'no', df.C.values) But if the word is part of the row and no tht e whole row something like 'contains' from pandas would be needed. df.C = np.where((df.C.values.contains('ye')), 'no', df.C.values) but this doesn't work. I would like to use numpy because of the speed.
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52420369
score: 1
upvote count: 1
type: Question
tagged with: numpy

http://stackoverflow.com/comment/91585757
has text: For being the first question is a really good explained one :D
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52319120

http://stackoverflow.com/q/52301568
accepted answer: http://stackoverflow.com/a/52302069
score: -3
has comment: http://stackoverflow.com/comment/91550947
has comment: http://stackoverflow.com/comment/91551543
has comment: http://stackoverflow.com/comment/91551761
has comment: http://stackoverflow.com/comment/91551310
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91551250
upvote count: 0
has answer: http://stackoverflow.com/a/52302069
has comment: http://stackoverflow.com/comment/91551426
has title: The action didnot return a valid dictionary in ibm watson
type: Question
answer count: 1
tagged with: python-2.7
downvote count: 3
has body: This is my dictionary which is coming as response { "body": { "Status": "Alive" } } But when i am trying to fetch the status by print('new_dict :',new_dict) it is giving response as new_dict : {'Status': 'Alive'}" How this extra double quote is coming. Has anyone faced this issue. How to solve this.
tagged with: python
has comment: http://stackoverflow.com/comment/91551040
favorite count: 0
has comment: http://stackoverflow.com/comment/91551261
has comment: http://stackoverflow.com/comment/91551191
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91551242

http://stackoverflow.com/comment/91611028
score: 1
comment on: http://stackoverflow.com/a/52332024
type: AnswerComment
type: Comment
has text: Thanks, I tried, but I get 'You can accept your own answer in 2 days'. I will try again in 2 days.

http://stackoverflow.com/q/52371865
tagged with: python-3.x
tagged with: python
score: 2
type: AnsweredQuestion
has title: Finding values starting with a specific piece of string
has body: I have a *.txt file and I keep some codes of some files in it. Format is the following: code1, a/b/c/1.jpg code2, a/b/c/2.jpg code1, a/b/c/3.jpg code2, a/b/d/4.jpg code3, a/b/d/5.jpg My purpose is finding the files in the same folder with the same codes (duplicates). All the file names are different. If the same code occurs in different folder like code2, a/b/c/ and code2, a/b/d/ I want to skip it. Right now I have the following code which searches a specific code in the whole *.txt document: reader = csv.reader(csvfile) dataDict = dict() for row in reader: if any (row): if row[0] in dataDict.keys(): dataDict[row[0]].append(row[1]) else: dataDict[row[0]] = [row[1]] But this gives me the duplicates in different folders. However, I want to find the duplicate files exactly in the same folder. Edit:The title is not clear. I did not know how to describe this in the title.
upvote count: 3
accepted answer: http://stackoverflow.com/a/52372007
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91688653
has comment: http://stackoverflow.com/comment/91688531
has answer: http://stackoverflow.com/a/52372007
answer count: 1
has comment: http://stackoverflow.com/comment/91688819
has comment: http://stackoverflow.com/comment/91688607
favorite count: 0

http://stackoverflow.com/q/52281454
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91548675
has title: python compressed 4Gb bz2 EOFError: end of stream was already found nested subfolders
tagged with: compression
tagged with: http://stackoverflow.com/tag/tar
tagged with: eof
has answer: http://stackoverflow.com/a/52301509
type: Question
linked to: http://stackoverflow.com/q/37603510
score: 0
has comment: http://stackoverflow.com/comment/91548152
has body: I'm trying to read a specific file from a compressed file bz2 using python. tar = tarfile.open(filename, "r|bz2", bufsize=57860311) for tarinfo in tar: print tarinfo.name, "is", tarinfo.size, "bytes in size and is", if tarinfo.isreg(): print "a regular file." # read the file f = tar.extractfile(tarinfo) #print f.read() elif tarinfo.isdir(): print "a directory." else: print "something else." tar.close() But at the end I got the error: /usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/tarfile.pyc in read(self, size) 577 buf = "".join(t) 578 else: --&gt; 579 buf = self._read(size) 580 self.pos += len(buf) 581 return buf /usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/tarfile.pyc in _read(self, size) 594 break 595 try: --&gt; 596 buf = self.cmp.decompress(buf) 597 except IOError: 598 raise ReadError("invalid compressed data") EOFError: end of stream was already found I also tried to list the files within the tar through 'tar.list()' and again ... -rwxr-xr-x lindauer/or3uunp 0 2013-05-21 00:58:36 r3.2/ -rw-r--r-- lindauer/or3uunp 6057 2012-01-05 14:41:00 r3.2/readme.txt -rw-r--r-- lindauer/or3uunp 44732 2012-01-04 10:08:54 r3.2/psychometric.csv -rw-r--r-- lindauer/or3uunp 57860309 2012-01-04 09:58:20 r3.2/logon.csv /usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/tarfile.pyc in _read(self, size) 594 break 595 try: --&gt; 596 buf = self.cmp.decompress(buf) 597 except IOError: 598 raise ReadError("invalid compressed data") EOFError: end of stream was already found I listed the files inside the archive using the tar command. Here is the result: tar -tvf r3.2.tar.bz2 drwxr-xr-x 0 lindauer or3uunp 0 May 21 2013 r3.2/ -rw-r--r-- 0 lindauer or3uunp 6057 Jan 5 2012 r3.2/readme.txt -rw-r--r-- 0 lindauer or3uunp 44732 Jan 4 2012 r3.2/psychometric.csv -rw-r--r-- 0 lindauer or3uunp 57860309 Jan 4 2012 r3.2/logon.csv -rw-r--r-- 0 lindauer or3uunp 12494829865 J…
answer count: 1
tagged with: bz2

http://stackoverflow.com/a/52390566
answers question: http://stackoverflow.com/q/52365956
score: 1
has comment: http://stackoverflow.com/comment/91750962
has comment: http://stackoverflow.com/comment/91759926
type: AcceptedAnswer
downvote count: 0
has body: You mentioned in the comments that you are running on lttng-tools 2.10.2. This version affected by a bug with the Python tracing agent. The bug makes it impossible to trace python applications when the user is not part of the tracing group and the lttng session daemon is running as root. This requirement normally only exists for kernel tracing. You are encountering this bug because systemd launches a root lttng session daemon at startup. You can easily test if it's indeed this bug by logging in as root and killing the root lttng session daemon and running a session daemon as your own non-root user like this: As root: pkill lttng-sessiond As your non-root user: lttng-sessiond -d lttng create lttng enable-event --python my-logger lttng start python test.py ... &lt;ctrl + c&gt; lttng stop lttng view If you get events now then your are affected by the bug. This bug has been fixed in the 2.10 branch and will make it to the Ubuntu packages. Until the package gets updated, you can add yourself to the tracing group or prevent systemd from launch a root lttng session daemon on startup.
has comment: http://stackoverflow.com/comment/91759984
type: Answer
accepted answer of: http://stackoverflow.com/q/52365956
upvote count: 1

http://stackoverflow.com/comment/91725281
type: AnswerComment
comment on: http://stackoverflow.com/a/52373962
score: 0
type: Comment
has text: @Tasos the link does work, I've tested it and put the output in the answer. You only need to append that code inside the python subprocess. Stackoverflow is a place where you should show your work and people help you to complete it, not the other way. At this point the answer provides the tools for your needs.

http://stackoverflow.com/q/52271714
score: 1
tagged with: multithreading
upvote count: 1
tagged with: queue
type: Question
has answer: http://stackoverflow.com/a/52286506
has body: I've found an example representing producer-consumer with two threads. But, when I send a signal to the process to stop, it doesn't. It expects second signal e.g. SIGKILL to completely stop. I thought the problem is with task_done() but it seems not. import time import queue import threading import random class Producer(threading.Thread): """ Produces random integers to a list """ def __init__(self, queue): """ Constructor. @param queue queue synchronization object """ threading.Thread.__init__(self) self.queue = queue def run(self): """ Thread run method. Append random integers to the integers list at random time. """ while True: integer = random.randint(0, 256) self.queue.put(integer) print('%d put to queue by %s' % (integer, self.name)) time.sleep(1) class Consumer(threading.Thread): """ Consumes random integers from a list """ def __init__(self, queue): """ Constructor. @param integers list of integers @param queue queue synchronization object """ threading.Thread.__init__(self) self.queue = queue def run(self): """ Thread run method. Consumes integers from list """ while True: integer = self.queue.get() print('%d popped from list by %s' % (integer, self.name)) self.queue.task_done() def main(): q = queue.Queue() t1 = Producer(q) t2 = Consumer(q) t1.start() t2.start() t1.join() t2.join() if __name__ == '__main__': main() Output: 210 put to queue by Thread-1 210 popped from list by Thread-2 Traceback (most recent call last): File "/Users/abc/PycharmProjects/untitled1/ssid.py", line 74, in &lt;module&gt; main() File "/Users/abc/PycharmProjects/untitled1/ssid.py", line 69, in main t1.join() File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1056, in join self._wait_for_tstate_lock() File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1072, in _wait_for_tstate_lock elif lock.acquire(block, timeout): KeyboardInterrupt 244 put to queue by Thread-1…
tagged with: producer-consumer
has title: Why doesn't the producer-consumer stop?
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52286506
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/91690158
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52347470
type: QuestionComment
has text: @Baskaya: Good—although there is no real difference here between composition and inheritance. Both are equally hamstrung by inextensible design of the code to be reused.

http://stackoverflow.com/q/52300727
type: Question
has comment: http://stackoverflow.com/comment/91549840
has comment: http://stackoverflow.com/comment/91549828
has body: So I have a programming course at school, in Python 3. And the task is basically to make a program that asks for two integers between 1-9. The outcome will be a multiplication table with the amount of rows of the first integer and the number of columns of the second integer. So If one would type in 5 and 6 they would get: I found a code here on SO that generates that program. And right now. I am trying to dissect it and understand it. But I am stuck on some points. so here is the code: row,col=5,6 i=0 while i &lt;= row : j=0 while j &lt;= col: if i+j==0 : print('{:4s}'.format(''),end='') #corner elif i*j==0 : print('{:4d}'.format(i+j),end='') # border else : print('{:4d}'.format(i*j),end='') # table j=j+1 print() i=i+1 Ok. So what my tiny brain doesn't understand is how the border on the left hand side, which is vertical, is generated. If the first condition is met, a blank space in the upper left corner will be generated, and +1 will be added to the variable j. Afterwards, condition two will be met which will in turn give a horizontal border, this will continue until j is greater than col. But if j>col, how can the left border be generated? What part of the code generates the vertical border? Also. What do the input in the curly braces mean before the .format operator? for instance, how does {:4s} differ from {4:d}? Are they simply distances and "s" is for strings and d for numbers? Also, what does the last, statement print() do?
has comment: http://stackoverflow.com/comment/91549673
answer count: 1
tagged with: python
has title: I don't understand this particular line
favorite count: 0
has comment: http://stackoverflow.com/comment/91549360
has comment: http://stackoverflow.com/comment/91549638
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91549646
downvote count: 2
has answer: http://stackoverflow.com/a/52301112
upvote count: 1
score: -1

http://stackoverflow.com/q/52272831
type: Question
favorite count: 0
answer count: 3
tagged with: python
tagged with: regex
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52273461
has title: regex to extract all numbers with different lengths and special characters
has answer: http://stackoverflow.com/a/52273229
upvote count: 3
type: UnansweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/52272913
score: 2
has body: text1=""" my acc no is 1234 5678.I pay 123$ as an interest @ 14.9% starting from 12/07/19.My debit number is 123-45666-789-112""" I want output to have all numbers like 1234 5678, 123$, 14.9%, 12/07/19, 123-45666-789-112 Code am trying to run is giving partial results. Please help me out import re reg="\d{1,}[^a-zA-Z]?\d{1,}?[^a-zA-Z]?\d?" gc=re.compile(reg) number = gc.findall(text1) print(number) ['1234 567', '123$', '14.9%', '12/07', '19.', '123-456', '66-789', '112'] Also how do i extract if I want two words before number? i.e acc no is 1234 5678 etc..

http://stackoverflow.com/q/52295024
linked to: http://stackoverflow.com/q/37173892
has comment: http://stackoverflow.com/comment/91537734
has comment: http://stackoverflow.com/comment/91540154
has comment: http://stackoverflow.com/comment/91540732
tagged with: arrays
has comment: http://stackoverflow.com/comment/91540350
has body: When I try to load data from a csv file, I get this error: TypeError: Cannot cast array data from dtype('float64') to dtype('S32') according to the rule 'safe' in my original code I had: training_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]]) instead of having training_set_inputs like that, I want to read data from a csv file. My csv file contains same data as following: 0,0,1 1,1,1 1,0,1 0,1,1 I load my csv file like that: import csv training_set_inputs = [] # open file with open('neuron.csv', 'rb') as f: reader = csv.reader(f) # read file row by row for row in reader: training_set_inputs.append(row) Here's my whole script: import pandas as pd import csv from numpy import exp, array, random, dot class NeuralNetwork(): def __init__(self): # Seed the random number generator, so it generates the same numbers # every time the program runs. random.seed(1) # We model a single neuron, with 3 input connections and 1 output connection. # We assign random weights to a 3 x 1 matrix, with values in the range -1 to 1 # and mean 0. self.synaptic_weights = 2 * random.random((3, 1)) - 1 # The Sigmoid function, which describes an S shaped curve. # We pass the weighted sum of the inputs through this function to # normalise them between 0 and 1. def __sigmoid(self, x): return 1 / (1 + exp(-x)) # The derivative of the Sigmoid function. # This is the gradient of the Sigmoid curve. # It indicates how confident we are about the existing weight. def __sigmoid_derivative(self, x): return x * (1 - x) # We train the neural network through a process of trial and error. # Adjusting the synaptic weights each time. def train(self, training_set_inputs, training_set_outputs, number_of_training_iterations): for iteration in xrange(number_of_training_iterations): # Pass the training set through our neural network (a single neuron). output = self.think(training_set_inputs) # Calculate the error (The difference between the desired output # and the predicted output). error = training_…
has comment: http://stackoverflow.com/comment/91540450
has comment: http://stackoverflow.com/comment/91539498
has comment: http://stackoverflow.com/comment/91541027
has title: Python import CSV into array TypeError: Cannot cast array data from dtype('float64') to dtype('S32') according to the rule 'safe'
answer count: 1
has comment: http://stackoverflow.com/comment/91539712
has comment: http://stackoverflow.com/comment/91537736
has comment: http://stackoverflow.com/comment/91540581
favorite count: 0
has comment: http://stackoverflow.com/comment/91537882
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/52295192
has comment: http://stackoverflow.com/comment/91539955
score: 0
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/q/52326749
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91604397
has body: I have a docker image which contains a simple web page. it works fine on its own: docker run -p 747:747 &lt;docker image name&gt; Also I wrote a nomad job to get the docker image and run it: job "example" { datacenters = ["dc1"] type = "service" update { max_parallel = 1 min_healthy_time = "10s" healthy_deadline = "3m" progress_deadline = "10m" auto_revert = false canary = 0 } migrate { max_parallel = 1 health_check = "checks" min_healthy_time = "10s" healthy_deadline = "5m" } group "web" { count = 1 restart { # The number of attempts to run the job within the specified interval. attempts = 2 interval = "30m" delay = "15s" mode = "fail" } ephemeral_disk { size = 300 } task "redis" { driver = "docker" config { image = "mahdijalilvand/docker_web:latest" port_map { http = 747 } command = "python" args = ["/app/app/app.py"] } resources { cpu = 500 # 500 MHz memory = 1024 # 1024MB network { mbits = 10 port "db" {} } } service { name = "redis-cache" tags = ["global", "cache"] port = "db" check { name = "alive" type = "tcp" interval = "10s" timeout = "2s" } } } } } but I do not have any access to the web page.
answer count: 0
tagged with: nomad
type: Question
has comment: http://stackoverflow.com/comment/91605107
has title: nomad job failed to start docker
has comment: http://stackoverflow.com/comment/91604975
tagged with: docker
score: 0

http://stackoverflow.com/a/52406263
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91819367
accepted answer of: http://stackoverflow.com/q/52382306
answers question: http://stackoverflow.com/q/52382306
type: Answer
has comment: http://stackoverflow.com/comment/91783364
score: 0
has body: As far as I know, this is currently not possible in an extension. There are some parts of CKAN's authorization architecture that can be modified and extended via plugins, for example via the IAuthFunctions, IAuthenticator, and IPermissionLabels interfaces. The roles in ckan.authz, however, are hard-coded. You could try to use IAuthFunctions to override CKAN's built-in auth functions to create a similar effect. In particular, you could use that approach to remove some privileges from certain editor members, making them into the "super" users that you're trying to implement. (Note that adding privileges to member users will probably not work, since those users will fail the checks based on their role even if your modified auth functions would grant them access) It won't solve your immediate problem, but I do think that it would be nice for CKAN to support what you're trying to do. I've therefore created a ticket in CKAN's feature-discussion-tracker. Feel free to add further information about your use case to it.

http://stackoverflow.com/comment/91805643
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52428999
has text: I could read the file. They code is counting the lang in the dataframe chunk. Thanks a ton. Really appreciate the help.
type: AnswerComment

http://stackoverflow.com/comment/91696766
type: AnswerComment
has text: How would you substitute `alpha` in g, after you did `g.subs(a, sy.symbols('alpha'))` ? There is no reference to variable `alpha`, so it is not possible to call `g.subs(alpha, sy.symbols('something_else'))`.
type: Comment
comment on: http://stackoverflow.com/a/52374626
score: 0

http://stackoverflow.com/comment/91707576
has text: Thanks, it is a good question. There is a good old open source game (and it is made with ncurses). And I want or try at least to wrap this game and make a frontend for this game with Godot. And I am trying to make a script to parse stdout and send keys.
score: 0
comment on: http://stackoverflow.com/q/52377179
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91710050
has text: `python object` on google will result in multiple tutorial / courses on it.
score: 1
comment on: http://stackoverflow.com/q/52382919
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52389918
has body: I am having a difficult time building a dictionary of parent child flags. I have a dictionary like this: d = { 'A': ['Blue'], 'B': ['A'], 'C': ['A'], 'D': ['C'], } This is my logic or thought process: If a key is 'Blue', it is the parent, and gets a flag of 0. If the value is in d.keys(), it gets a flag of 1. Where I get stuck is on the grandchildren. Here is the code I have now, and is a result of me banging my head against a figurative wall for many hours now. level = 0 while level &lt; 1000: for key, value in d.items(): if value[0] == 'Set': if len(value) == 1: value.extend([level]) elif len(value) &gt;= 2: continue elif value[0] in d.keys(): value.extend([level]) level += 1 The result is: A: ['Blue', 0] B: ['A', 1] C: ['A', 2] D: ['D', 3] D is a grandchild of C and should have a flag of 2, and C is a child of A and should have a value of 2, just like the other child, B. The purpose of this is to create the correct flags no matter how many grandchildren or great-grandchildren levels there are. The bigger picture here is to use this data to insert nested loops. I have a strange database and have to use a certain proprietary module to iterate through the lookup tables that are made available to me via class attributes. So, the code will be while parent: ...block of code for parent... ...insert same structure here if not the parent... ...statement at end of parent block... So, a child loop may look like this: while parent: ...block of code for parent... while child: ...block of code for child... ...variable for block insertion... ...statement at end of child block... ...statement at end of parent block... The ...statement at end of parent/child block... is a similar to next() but using the proprietary module I need to use for this. So, the mapper is to be used to let the program know how many nested while loops to create using this structure. I haven't gotten to inserting the nested blocks but I know it can be done. :) I would love to learn from someone who can expl…
favorite count: 0
has comment: http://stackoverflow.com/comment/91725171
has comment: http://stackoverflow.com/comment/91725265
has comment: http://stackoverflow.com/comment/91728353
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91725170
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52390685
score: 1
has comment: http://stackoverflow.com/comment/91724955
has comment: http://stackoverflow.com/comment/91725361
has comment: http://stackoverflow.com/comment/91725267
upvote count: 1
has comment: http://stackoverflow.com/comment/91725169
has comment: http://stackoverflow.com/comment/91725124
type: Question
possible better answer: http://stackoverflow.com/a/52390242
has title: Python Dictionary of Parent Child Map
downvote count: 0
has answer: http://stackoverflow.com/a/52390242
has comment: http://stackoverflow.com/comment/91725285
accepted answer: http://stackoverflow.com/a/52390685
answer count: 3
has answer: http://stackoverflow.com/a/52390176

python-xarray
tags question: http://stackoverflow.com/q/52412607
tags question: http://stackoverflow.com/q/52326526
tags question: http://stackoverflow.com/q/52314391
tags question: http://stackoverflow.com/q/52384940
type: Tag
tags question: http://stackoverflow.com/q/52299927
tags question: http://stackoverflow.com/q/52374936
tags question: http://stackoverflow.com/q/52406826
tag name: python-xarray
tags question: http://stackoverflow.com/q/52313237

http://stackoverflow.com/q/52288408
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91524535
possible better answer: http://stackoverflow.com/a/52288570
has answer: http://stackoverflow.com/a/52288570
accepted answer: http://stackoverflow.com/a/52347094
type: Question
tagged with: ctypes
score: 5
has comment: http://stackoverflow.com/comment/91590705
upvote count: 5
has title: python access self in dll callback function in class
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91595399
has comment: http://stackoverflow.com/comment/91524767
favorite count: 0
has answer: http://stackoverflow.com/a/52347094
has body: i have a dll function of some api like this: def dllcallback(items): pass i want to access self in class functions linked with dll callback. class myobject(object): def __init__(self): self.a = 999 @dllcallback def mycallback(self, items): print (self.a) self.a = 888 print (self.a) i don't think dllcallback accepts self as argument. so this was fail. i wish myobject.mycallback will trigger when dllcallback is called by api, and shows: 999 888 and i tried the below to make 'self' be accessible by inner functions, but this approach killed the Kernel... class myobject(object): def __init__(self): self.a = 999 def callbacks(self): @dllcallback def mycallback(items): print (self.a) self.a = 888 print (self.a) i am not sure the reason why the kernel died. thanks in advance for any suggestion. UPDATED: 20180912 1436 Actually, the override method could be called without self as argument, class myobject(object): def __init__(self): self.a = 999 @dllcallback def mycallback(items): global self print (self.a) self.a = 888 print (self.a) NameError: name 'self' is not defined I suppose 'self' cannot be obtained like this...any suggestions? UPDATED: 20180913 1645 Got some progress in writing a class including ctypes dll callback functions class myobject(object): def __init__(self): if u'32bit' in architecture(): # 32bit WinOS self.spdll = windll.LoadLibrary('XXX.dll') else: # 64bit WinOS self.spdll = cdll.LoadLibrary('XXX.dll') self.a = 999 def callbacksinit(self): def mycallback(items): print (self.a) self.a = 888 print (self.a) self.mycallbackaddr = WINFUNCTYPE(None, c_char_p) def regcallbacks(self): self.spdll.APICALLBACK(self.mycallbackaddr) With this code, i can access self.a when mycallback is triggered by API. And fortunately for me, self.a can be changed to 888 after mycallback is done without global declaration (e.g. global self) in mycallback. I have no idea why this happens...why WINFUNCTYPE(None, c_char_p) works in this way and why self.a can be changed without global …
tagged with: python

http://stackoverflow.com/q/52366997
tagged with: max
downvote count: 0
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/52367027
tagged with: python
has body: I am trying to find the maximum length word in a sentence, like a = "my name is john and i am working in STACKOVERFLOWLIMITED" To fetch the largest word in this sentence, I am trying something like c = a.split(',') c = ['my', 'name', 'is', 'john', 'and', 'i', 'am', 'working', 'in', 'STACKOVERFLOWLIMITED'] When I am trying to print max (C) output - 'working' Why the output doesn't contain "STACKOVERFLOWLIMITED" as the longest word in that sentence?
type: UnansweredQuestion
upvote count: 3
type: Question
score: 3
has answer: http://stackoverflow.com/a/52367142
has title: I am trying to find the maximum length word in a sentence
answer count: 2
has comment: http://stackoverflow.com/comment/91679295

http://stackoverflow.com/comment/91655856
type: Comment
score: 2
has text: You need `(Score, Name)` to pass as a single object. Put them in a tuple. So `cursor.execute("UPDATE Highscores SET Player_Score = ? WHERE Player_Name = ? ", (Score, Name))`
type: QuestionComment
comment on: http://stackoverflow.com/q/52355627

readonly
tag name: readonly
type: Tag
tags question: http://stackoverflow.com/q/52416824

http://stackoverflow.com/q/52413285
has answer: http://stackoverflow.com/a/52422758
answer count: 1
tagged with: yahoo-finance
has title: Python YahooFinancials in combination with mysql connector lead to SSL error
type: UnansweredQuestion
tagged with: python
tagged with: database-connection
has body: I have the following code from mysql.connector import MySQLConnection, Error from yahoofinancials import YahooFinancials yahoo_financials = YahooFinancials('AAPL') historical_stock_prices = yahoo_financials.get_prev_close_price() This code causes the following error message: OSError: [Errno socket error] [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645) The code does work very well without importing MySQLConnection but I need MySQLConnection later. Furthermore, on my machine MySQLConnection works in another python script without YahooFinancials.
type: Question
tagged with: ssl
tagged with: ssl-certificate
score: 0

http://stackoverflow.com/comment/91707423
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52381259
has text: Yeah got it working as expected. No need to do serial.to_bytes
type: AnswerComment

http://stackoverflow.com/comment/137136860
comment on: http://stackoverflow.com/a/60290438
score: 0
type: AnswerComment
has text: no, that actually makes threading works in both ends
type: Comment

http://stackoverflow.com/comment/91506674
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52279133
has text: What do you mean by append to the end of the file? Add data into the next set of cell or add the first cells together then the 2nd cells, etc.

http://stackoverflow.com/a/52283764
has body: It is probably the difference between locks (SHARED v. RESERVED). From SQLite Doc): An attempt to execute COMMIT might also result in an SQLITE_BUSY return code if an another thread or process has a shared lock on the database that prevented the database from being updated. When COMMIT fails in this way, the transaction remains active and the COMMIT can be retried later after the reader has had a chance to clear. In the read example, it is a SHARED lock, the transaction remains active and gets COMMITed after the next successful INSERT. I know the API doc says the context manager will rollback. But I also know what I see. The connection object has an in_transaction attribute: True if a transaction is active (there are uncommitted changes), False otherwise. Read-only attribute. I added some prints to my repro and found that, in fact, the transactions were staying active when the insert failed. before insert 0 in tx? False after insert 0 in tx? False before insert 1 in tx? False Writing failed at '1'. Ex: database is locked in tx? True before insert 2 in tx? True Writing failed at '2'. Ex: database is locked in tx? True before insert 3 in tx? True Writing failed at '3'. Ex: database is locked in tx? True before insert 4 in tx? True after insert 4 in tx? False before insert 5 in tx? False Writing failed at '5'. Ex: database is locked in tx? True before insert 6 in tx? True Writing failed at '6'. Ex: database is locked in tx? True before insert 7 in tx? True Writing failed at '7'. Ex: database is locked in tx? True before insert 8 in tx? True after insert 8 in tx? False before insert 9 in tx? False Writing failed at '9'. Ex: database is locked in tx? True before insert 10 in tx? True Writing failed at '10'. Ex: database is locked in tx? True before insert 11 in tx? True All rows were inserted. The explicit rollback would prevent this problem.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52276142
score: 0
accepted answer of: http://stackoverflow.com/q/52276142
type: Answer

http://stackoverflow.com/q/52315717
has comment: http://stackoverflow.com/comment/91579222
has comment: http://stackoverflow.com/comment/91578860
has comment: http://stackoverflow.com/comment/91578780
answer count: 2
has comment: http://stackoverflow.com/comment/91579088
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52315889
tagged with: python
tagged with: regex
has body: I am trying to figure out the syntax for regular expression that would match 4 alphanumeric characters, where there is at least one letter. Each should be wrapped by: &gt; and &lt; but I wouldn't like to return the angle brackets. For example when using re.findall on string &gt;ABCD&lt;&gt;1234&lt;&gt;ABC1&lt;&gt;ABC2 it should return ['ABCD', 'ABC1']. 1234 - doesn't have a letter ABC2 - is not wrapped with angle brackets
accepted answer: http://stackoverflow.com/a/52315889
score: 2
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/91578971
possible better answer: http://stackoverflow.com/a/52316798
downvote count: 1
has title: python regex to find alphanumeric string with at least one letter
type: Question
has answer: http://stackoverflow.com/a/52316798

http://stackoverflow.com/comment/91741263
has text: Yup, I did try using `sudo pip freeze > to_delete.txt` and got the output I showed in the question.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52398250

http://stackoverflow.com/comment/91726125
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52374591
has text: Will loading of random rows work for you?Like this https://nikgrozev.com/2015/06/16/fast-and-simple-sampling-in-pandas-when-loading-data-from-files/
type: Comment

http://stackoverflow.com/comment/91652252
has text: @JonClements Ok, thank you. Is it possible to see what causes the no match for 'address' since that obviously is in the file?
score: 0
comment on: http://stackoverflow.com/q/52353566
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52397700
has title: Redshift external table from parquet file showing null values for string data type
downvote count: 0
tagged with: amazon-redshift-spectrum
score: 1
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/91799832
favorite count: 0
tagged with: amazon-redshift
has comment: http://stackoverflow.com/comment/91757674
tagged with: parquet
answer count: 0
tagged with: pyarrow
type: UnansweredQuestion
tagged with: python
has body: I am creating an external table in Redshift, pointing at a Parquet file stored in S3. The parquet file is created with pyarrow. When I SELECT * the external table defined below the "timestamp" works but the "anonymous_id" (VARCHAR) is null. The same applies to any VARCHAR. CREATE EXTERNAL TABLE propensity_identify (anonymous_id VARCHAR(max), timestamp timestamp without time zone) PARTITIONED BY (loaded_at timestamp) STORED AS PARQUET LOCATION 's3://bucket/key' TABLE PROPERTIES ('compression'='none', 'serialization.null.format'='') The parquet schema is: anonymousId: BYTE_ARRAY UTF8 timestamp: INT96 Any idea why that happens? STL_S3CLIENT_ERROR says: S3ServiceException:HTTP/1.1 403 Forbidden,Status 403 Thank you very much for your help!
has comment: http://stackoverflow.com/comment/91741063

http://stackoverflow.com/q/52290434
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/76306637
favorite count: 0
tagged with: h5py
has comment: http://stackoverflow.com/comment/91528691
tagged with: python
has comment: http://stackoverflow.com/comment/91567342
type: UnansweredQuestion
tagged with: hdf5
has answer: http://stackoverflow.com/a/52340368
has title: How to create a table by using h5py?
type: Question
score: 0
answer count: 2
has body: I am a python learner, now at the basic level. I need to know, how to create a table using h5py and pass 10000 values. Looking for quick assistance. Thanks in advance.

http://stackoverflow.com/comment/91655827
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52354573
has text: the order of columns got changed but Yeah it worked.! Thanks for the help. @NagaKiran

http://stackoverflow.com/a/52278407
type: Answer
score: 2
upvote count: 3
has body: As per design pattern variable should be created just before to use. In the code you are using x without creating or initializing default value. "y" = you are iterating the list (primes). So in each iteration y will be initialized by the current value.So it will not give any error.
downvote count: 1
answers question: http://stackoverflow.com/q/52278149

http://stackoverflow.com/a/52313591
type: Answer
has comment: http://stackoverflow.com/comment/91574685
upvote count: 1
score: 1
has body: You can use whatever you want for the salt keys : they are just random strings and they are not related to each others so any random string generator will be fine. As far as I know, there are no restrictions on the characters used in the salt
downvote count: 0
answers question: http://stackoverflow.com/q/52313499
has comment: http://stackoverflow.com/comment/91574821

http://stackoverflow.com/comment/91591122
type: Comment
has text: so dict to csv doesnt seem very easy to do, probably would have been better to use lists instead of dictionaries but whatever, made it so it outputs a list of lists and then can easily write it to csv, works on my end now anyway
comment on: http://stackoverflow.com/a/52316923
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91721552
comment on: http://stackoverflow.com/a/52388156
score: 0
type: AnswerComment
has text: @JeffTehrani `[np.busday_count(x[0],x[1]) for x in df.values.astype('datetime64[D]')] `
type: Comment

http://stackoverflow.com/q/52277922
upvote count: 2
has comment: http://stackoverflow.com/comment/91505650
tagged with: web-scraping
accepted answer: http://stackoverflow.com/a/52279830
type: AnsweredQuestion
score: 2
has title: BeautfulSoup : can't get ALL the image src
type: Question
has comment: http://stackoverflow.com/comment/91504209
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91504916
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52279830
tagged with: python
favorite count: 0
has body: I'm trying to get every images from a website and sometimes BeautifulSoup doesn't get every src attributes from the HTML. Example: data = requests.get('https://www.qmedichealth.com/') soup = BeautifulSoup(data.text, 'html.parser') img = soup.find_all('img') The code is simple but I can't get the url of the slider on this website, it works for every image except the one below : &lt;img alt="image description" style="width: 1583px; margin-left: 0px; height: 1055.33px; margin-top: -0.166667px;" src="https://cdn.shopify.com/s/files/1/0970/0888/t/3/assets/img07.jpg"&gt; What I actually get: &lt;img alt="image description"/&gt; Any idea about this behaviour?

http://stackoverflow.com/comment/91756997
score: 0
comment on: http://stackoverflow.com/q/52406584
has text: "Can I do this with python?" -- if worst comes to worst, it shouldn't be too hard to write your own function to do this, right?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52414162
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52414058
type: AcceptedAnswer
has body: You have the packages you want - numpy and pandas. I'd recommend going through a few tutorials, starting with a basics numpy one, but focusing on pandas. Doing work like this in python is best done in an interactive notebook editor, so if you can install Jupyter/IPython that'll make your life way easier in the future. Also, build out your test datasets first and drop them in a file, so every day when you start you can import 1 file and have small, usable datasets ready to go (you'll have to use the csv package probably)!
accepted answer of: http://stackoverflow.com/q/52414058

http://stackoverflow.com/q/52274856
tagged with: mysql
type: Question
has comment: http://stackoverflow.com/comment/91497799
upvote count: 1
has body: I used the following command to increase a field in mysql table in python. cursor,db_connection=await database_connection() await cursor.execute("update topics set last_voice_id=last_voice_id+1 where topic_id='%s'" % topic_id) await db_connection.commit() i want to get the field last_voice_id after it's updated. how do i do this?
tagged with: mysql-python
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
answer count: 0
downvote count: 0
has title: how to get an updated field in python-mysql after the field updated
score: 1

http://stackoverflow.com/q/52378452
answer count: 1
has comment: http://stackoverflow.com/comment/91701492
has comment: http://stackoverflow.com/comment/91701522
downvote count: 0
score: 1
favorite count: 0
tagged with: postgresql
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91701759
has comment: http://stackoverflow.com/comment/91701598
has comment: http://stackoverflow.com/comment/91701632
has body: I'm a beginner and I've been creating a Django project. I'm trying to switch sqlite3 db to postgresql. But when I do make migrations, this error occurred. django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host, user, database I searched about this error. And some people checked pg_hba.conf file, but I have no idea where this file is. Also when I created project before and did the same thing, there's no this error. Why is this error happening this time? What is the cause? How can I fix this error? Here is configuration part in settings.py DATABASES = { 'default': { #elephantsql 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('DATABASE_NAME', ''), 'USERS': os.environ.get('DATABASE_USER', ''), 'PASSWORD': os.environ.get('DATABASE_PASSWORD', ''), 'HOST': os.environ.get('DATABASE_HOST', ''), 'PORT': os.environ.get('DATABASE_PORT'), } }
has comment: http://stackoverflow.com/comment/91701674
upvote count: 1
has comment: http://stackoverflow.com/comment/91720863
type: Question
has comment: http://stackoverflow.com/comment/91701456
has comment: http://stackoverflow.com/comment/91701710
has comment: http://stackoverflow.com/comment/91720643
has comment: http://stackoverflow.com/comment/91701528
has title: Django; django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host, user, database
has comment: http://stackoverflow.com/comment/91701541
has answer: http://stackoverflow.com/a/61294820

http://stackoverflow.com/comment/91553339
score: 0
comment on: http://stackoverflow.com/q/52301201
type: Comment
type: QuestionComment
has text: @misantroop my bad I tested a user agent that has a lower version haha but yea that fixed the problem .. Thanks!!!.. sorry only picked up programming 3 days ago =))

http://stackoverflow.com/comment/91614981
comment on: http://stackoverflow.com/a/52333902
has text: hey it is an example and this is time series and i group the index as index.date and i want to calculate the percentage change for every group with just the previous element of 1st element of a group. The first group percentage will be NaN as they don't have previous element @Anna Iliukovich-Strakovskaia
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52423697
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/31726643
score: 0
tagged with: machine-learning
duplicate of: http://stackoverflow.com/q/31726643
tagged with: plot
type: Question
has body: I'm to Python and learning it by doing. I want to make two plots with matplotlib in Python. The second plot keeps the limits of first one. Wonder how I can change the limits of each next plot from previous. Any help, please. What is the recommended method? X1 = [80, 100, 120, 140, 160, 180, 200, 220, 240, 260] Y1 = [70, 65, 90, 95, 110, 115, 120, 140, 155, 150] from matplotlib import pyplot as plt plt.plot( X1 , Y1 , color = "green" , marker = "o" , linestyle = "solid" ) plt.show() X2 = [80, 100, 120, 140, 160, 180, 200] Y2 = [70, 65, 90, 95, 110, 115, 120] plt.plot( X2 , Y2 , color = "green" , marker = "o" , linestyle = "solid" ) plt.show()
tagged with: matplotlib
tagged with: data-science
has answer: http://stackoverflow.com/a/52424250
answer count: 2
possible better answer: http://stackoverflow.com/a/52424143
accepted answer: http://stackoverflow.com/a/52424250
has answer: http://stackoverflow.com/a/52424143
has title: How to create multiple plots
tagged with: python

http://stackoverflow.com/comment/91532659
comment on: http://stackoverflow.com/q/52292286
has text: But `c, d` is also after the first `:i`, so which one would you consider?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91515352
comment on: http://stackoverflow.com/q/52283184
type: Comment
type: QuestionComment
score: 1
has text: @user3483203 OP edited the question so it's not a dupe anymore. I'm reopening this, but I don't like to do that behind the closers back hence the heads up.

http://stackoverflow.com/comment/91617916
score: 0
comment on: http://stackoverflow.com/q/52335247
type: Comment
type: QuestionComment
has text: Not seeing where you're taking the absolute value of `y` after subtracting out `x`.

http://stackoverflow.com/a/52397830
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52397709
type: AcceptedAnswer
downvote count: 0
has body: Code: value_dict = {(0, 0): 'P0', (20, 0): 'P1', (20, 11.36): 'P2', (0, 11.36): 'P3'} values = [ [0, 0, 20, 0, 15, 5.5, 5, 5.5], [20, 0, 20, 11.36, 15, 5.5], [20, 11.36, 0, 11.36, 5, 5.5, 15, 5.5], [0, 11.36, 0, 0, 5, 5.5] ] data = [5, 5.5, 15, 5.5] # add data to value_dict iterator = iter(data) for i, j in enumerate(iterator): value_dict[j, next(iterator)] = 'D{}'.format(i) # Translate the data result = [] for v in values: line = [] iterator = iter(v) for i in iterator: line.append(value_dict[(i, next(iterator))]) result.append(line) print(value_dict) print(result) Results: { (0, 0): 'P0', (20, 0): 'P1', (20, 11.36): 'P2', (0, 11.36): 'P3', (5, 5.5): 'D0', (15, 5.5): 'D1' } [ ['P0', 'P1', 'D1', 'D0'], ['P1', 'P2', 'D1'], ['P2', 'P3', 'D0', 'D1'], ['P3', 'P0', 'D0'] ]
type: Answer
answers question: http://stackoverflow.com/q/52397709
score: 2

http://stackoverflow.com/q/52385596
score: 2
has comment: http://stackoverflow.com/comment/91716810
has comment: http://stackoverflow.com/comment/91719963
has answer: http://stackoverflow.com/a/63534668
upvote count: 2
has body: learning django and created a new project. login to admin page through http://127.0.0.1:8000/admin But after adding profile code for every user I am getting the below error Error user/models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) image=models.ImageField(default='default.jpg',upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img=Image.open(self.image.path) if img.height&gt;300 or img.width &gt;300: output_size=(300,300) img.thumbnail(output_size) img.save(self.image.path) user/views.py from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm,UserUpdateForm,ProfileUpdateForm def register(request): if request.method=="POST": form=UserRegisterForm(request.POST) if form.is_valid(): form.save() # it will save user in database #form.cleaned_data is dictionary it will contain the data from form username=form.cleaned_data.get('username') messages.success(request,f'Your account has been created!') return redirect('login') else: form=UserRegisterForm() # instance of UserCreationForm() class will create form in template as we are passing there return render(request,'users/register.html',{'form':form}) @login_required() def profile(request): if request.method == "POST": u_form=UserUpdateForm(request.POST,instance=request.user) p_form=ProfileUpdateForm(request.POST,request.FILES,instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context={ 'u_form':u_form, 'p…
type: Question
answer count: 8
has comment: http://stackoverflow.com/comment/91715950
has comment: http://stackoverflow.com/comment/91721251
has comment: http://stackoverflow.com/comment/91719922
has answer: http://stackoverflow.com/a/59837746
has answer: http://stackoverflow.com/a/54663755
downvote count: 0
has title: RelatedObjectDoesNotExist at /admin/login/ User has no profile
has answer: http://stackoverflow.com/a/53476411
favorite count: 0
has comment: http://stackoverflow.com/comment/91718031
has comment: http://stackoverflow.com/comment/91717978
has answer: http://stackoverflow.com/a/64502848
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/55896579
has answer: http://stackoverflow.com/a/70070511
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/74171678

http://stackoverflow.com/q/52407721
type: UnansweredQuestion
favorite count: 0
type: Question
score: 3
tagged with: arima
upvote count: 3
tagged with: python
answer count: 1
tagged with: statsmodels
has answer: http://stackoverflow.com/a/57248935
has title: Why does ARIMA fit properly but generate flat predictions?
tagged with: time-series
has body: Model Fits but the Predictions Fail Using a (4,0,13) ARIMA model on the following data shown in the picture below yields flat predictions (also shown shown in the second picture below). I am not sure why the model can fit the data in the training set, but then predict nothing afterwards. I found another question here which said I needed to add a seasonal component. I detail my experience with that below. The Time Series (zoomed in) The Predictions* * The predictions plot shows all the training data as well as the validation data after the orange vertical line. The training fit is rounded to be integers (it's not possible to have real numbers in this dataset). Note the prediction is just flat and then dies. Problem Definition I have 15 minute interval data and desire to apply a SARIMA model to it. It has a daily seasonality, which is defined from 7am-9pm (therefore, every 4 * 15 = 60 periods (4, 15 minute periods in an hour * 15 hours)). I first tested for stationarity with the Augmented Dickey-Fuller test. This passed, and so I started to analyze the ACF and PACF to determine the SARIMA parameters. Parameter Determination (p,d,q) ACF &amp; PACF on Original Data From this, I see there is no unit root (sum of ACF and PACF do not equal 1), and that we need to difference the series since there is no big cut off in the ACF. ACF &amp; PACF on Differenced Data From this, I see it is slightly overdifferenced, so I may want to try no integrated term and add an AR term at 15 (the point where the ACF in the original plot enters the bands). I also add an MA term here. (P,D,Q)s I now look for the seasonal component. I do a seasonal difference of period 60 since that's where the spike is in the plots. Seasonal difference Seeing this, I should add 2 MA terms to the seasonal component (Rules 13 and 7 from here) But the site also says to not use more than 1 seasonal MA usually, so I leave it at 1. Model This leaves me with a SARIMA(0,1,1)(0,1,1,60) model. However, I run out of memor…
tagged with: forecasting
downvote count: 0

http://stackoverflow.com/a/52321541
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52320937
has body: This is a solution that doesn't use eval: &gt;&gt;&gt; from operator import getitem &gt;&gt;&gt; from functools import reduce &gt;&gt;&gt; from re import split &gt;&gt;&gt; str_rfrnc = '["text"]["title"]["res"]["din"]' &gt;&gt;&gt; data = { 'text': { 'title': { 'res': { 'din': 10 } } } } &gt;&gt;&gt; fields = split(r'[\[\]"]+', str_rfrnc)[1:-1] &gt;&gt;&gt; fields ['text', 'title', 'res', 'din'] &gt;&gt;&gt; reduce(getitem, fields, data) 10

http://stackoverflow.com/q/52375509
answer count: 3
has answer: http://stackoverflow.com/a/52376202
tagged with: google-cloud-pubsub
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/55667797
type: UnansweredQuestion
tagged with: streaming
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/74787736
score: 1
has title: How can I stream data from a Google PubSub topic into PySpark (on Google Cloud)
type: Question
has body: I have data streaming into a topic in Google PubSub. I can see that data using simple Python code: ... def callback(message): print(datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") + ": message = '" + message.data + "'") message.ack() future = subscriber.subscribe(subscription_name, callback) future.result() The above python code receives data from the Google PubSub topic (with subscriber subscriber_name) and writes it to the terminal, as expected. I would like to stream the same data from the topic into PySpark (RDD or dataframe), so I can do other streaming transformation such as windowing and aggregations in PySpark, as described here: https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html. That link has documentation for reading other streaming sources, (e.g. Kafka), but not Google PubSub. Is there a way to stream from Google PubSub into PySpark?
tagged with: pyspark

http://stackoverflow.com/a/52287861
upvote count: 9
has body: Use: df11 = df1.pivot('Date', 'Tickers','Qty') df22 = df2.set_index('Date') s = df22.mul(df11).bfill(axis=1).iloc[:, 0] print (s) Date 01-01-2018 3075.0 02-01-2018 175.0 03-01-2018 NaN 04-01-2018 NaN 05-01-2018 2075.0 Name: ABC, dtype: float64 Solution for add new column to df1: df11 = df1.pivot('Date', 'Tickers','Qty') df22 = df2.set_index('Date') df = df1.join(df22.mul(df11).stack().rename('new'), on=['Date','Tickers'], how='left') print (df) Date Tickers Qty new 0 01-01-2018 ABC 25 3075.0 1 02-01-2018 BCD 25 175.0 2 05-01-2018 XYZ 25 2075.0 EDIT: If pairs Dates with Tickers are duplicated, solution above is not possible use. print (df1) Date Tickers Qty 0 01-01-2018 ABC 25 1 01-01-2018 ABC 20 &lt;-added duplicated pairs 01-01-2018 and ABC 2 02-01-2018 XYZ 31 3 02-01-2018 BCD 25 4 05-01-2018 XYZ 25 df3 = df1'Date'.copy() #add new values to column df3['new'] = df2.set_index('Date').lookup(df1['Date'], df1['Tickers']) * df1['Qty'] #add missing values to duplicated Dates df3 = df2'Date'.drop_duplicates().merge(df3, how='left') print (df3) Date new 0 01-01-2018 3075.0 1 01-01-2018 2460.0 2 02-01-2018 2449.0 3 02-01-2018 175.0 4 03-01-2018 NaN 5 04-01-2018 NaN 6 05-01-2018 2075.0
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52287641
has comment: http://stackoverflow.com/comment/91527534
type: Answer
has comment: http://stackoverflow.com/comment/91527874
has comment: http://stackoverflow.com/comment/91526126
accepted answer of: http://stackoverflow.com/q/52287641
has comment: http://stackoverflow.com/comment/91526166
score: 9

http://stackoverflow.com/comment/91565599
comment on: http://stackoverflow.com/q/52309212
has text: There are concepts like copy and deepcopy in Python.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91535767
type: Comment
comment on: http://stackoverflow.com/a/52293506
has text: THank you guys but i still have a problem. It is not solving my issue completely. I am getting the wrong answer.
type: AnswerComment
score: 0

http://stackoverflow.com/q/52422986
tagged with: selenium-webdriver
answer count: 0
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91789082
downvote count: 0
has body: I need to take screenshot with alert box present in page using python
linked to: http://stackoverflow.com/q/3422262
has title: How to take screenshot with alert box present in page [selenium python]
has comment: http://stackoverflow.com/comment/91789042
favorite count: 0
has comment: http://stackoverflow.com/comment/91788944
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91788992
tagged with: python

http://stackoverflow.com/q/52357098
has title: Detect if mouse is Waiting or Busy using python
has body: I am creating a script in Python 2.7. The script automates mouse clicks, within an application. There are instances that after a mouse click, the mouse cursor will be "Waiting", I want to wait until the mouse cursor changes back to normal before I go to the next step within the code. Is it possible within python to detect whether the mouse is waiting?
has comment: http://stackoverflow.com/comment/91658788
has comment: http://stackoverflow.com/comment/91660445
tagged with: mouse-cursor
favorite count: 0
has answer: http://stackoverflow.com/a/78800263
type: UnansweredQuestion
tagged with: python
upvote count: 5
type: Question
score: 5
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/91765467
type: Comment
has text: I am trying to validate user input for a process and want to make sure they give input in correct format - comma separated and distinct. The process takes input as list.
score: 0
comment on: http://stackoverflow.com/q/52410695
type: QuestionComment

http://stackoverflow.com/comment/91524297
has text: ASCII is a subset of UTF-8. If the output is in ASCII, it is automatically also UTF-8.
comment on: http://stackoverflow.com/q/52288236
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/91770311
comment on: http://stackoverflow.com/a/52413234
type: Comment
has text: Shouldn't the `theURLs.append(x['url'])` be equal to another variable?
score: 0
type: AnswerComment

http://stackoverflow.com/a/52302276
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52302196
type: Answer
has body: The following code is working for a single line: [float(x) for x in "2.8858451e-001 -2.0294171e-002 -1.3290514e-001 -9.9527860e-001 -9.8311061e-001".split(" ")] The numbers are in a long string. You need to separate on the spaces and convert each string separately to float for multiple lines: return_list = [] for l in tra_x: for entry in l.split(" "): return_list.append(float(entry))
has comment: http://stackoverflow.com/comment/91553683
score: 2
has comment: http://stackoverflow.com/comment/91553735
downvote count: 0
has comment: http://stackoverflow.com/comment/91553448
has comment: http://stackoverflow.com/comment/91553385
has comment: http://stackoverflow.com/comment/91553075
upvote count: 2
has comment: http://stackoverflow.com/comment/91552920
accepted answer of: http://stackoverflow.com/q/52302196

http://stackoverflow.com/comment/91761873
score: 0
type: Comment
type: QuestionComment
has text: It's the only way I've found, but I think you'll find it pretty easy to use. The coding changes are minimal. Start with `pip install selenium` and have a look here: https://automatetheboringstuff.com/chapter11/ and scroll down to the selenium section.
comment on: http://stackoverflow.com/q/52408701

http://stackoverflow.com/a/52337962
has body: you need to return a value from the checkAuth() function checkAuth() ... ... return authenticated
type: Answer
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/52337934
upvote count: 3

http://stackoverflow.com/comment/91770870
type: QuestionComment
comment on: http://stackoverflow.com/q/52413533
score: 1
type: Comment
has text: possible duplicate of: https://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples

http://stackoverflow.com/comment/91579402
type: Comment
has text: @YannicHamann: Good idea, have added `re.compile` in the code.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52315889

http://stackoverflow.com/comment/91710226
has text: Ok so before when I do the @dnickless way I finish my loop in 47 seconds and with the aggregate more than 5 min... xD Atleast there is a way to speed up the aggregate, do this in 3 queries is the best way
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52371589
type: Comment

http://stackoverflow.com/q/52411253
upvote count: 2
type: UnansweredQuestion
score: 2
tagged with: python-unicode
type: Question
has title: Elastic Search with Unicode behaves abruptly with python
downvote count: 0
tagged with: unicode
has body: When I am using elasticsearch with python for unicode characters, I am seeing some unusual result. When we pass the query in a variable it results in No Records Found. But when we pass the query as it is in body part as mentioned in 1st example below, it gives correct result. 1- result_set = self._elasticsearch_conn_instance.search(index='{0}'.format(self._dir_index), \ size=MAX_RECORD_PER_QUERY, \ body={"query":{"constant_score":{"filter":{"bool":{"must": [{"term":{"NAME":"çãoSc"}}, {"term":{"OP":"Create"}}]}}}}}, \ sort='OP:asc,SNAP:asc') 2- result_set = self._elasticsearch_conn_instance.search(index='{0}'.format(self._dir_index), \ size=MAX_RECORD_PER_QUERY, \ body=computed_query, \ sort='OP:asc,SNAPID:asc') Note: In 2nd query 'computed_query' which is getting passed as body is assigned same query as in part of 1st. 1st one passes and gives correct result but the 2nd fails and says No Record Found. This case is only with Special Unicode characters and not with ASCII characters. Any help on this behavior would be useful. Thanks !!!
tagged with: elasticsearch
tagged with: python
favorite count: 0
tagged with: python-3.x
answer count: 0

http://stackoverflow.com/q/52326071
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91602768
tagged with: django
type: Question
has answer: http://stackoverflow.com/a/52326154
upvote count: 2
answer count: 2
has title: Send request to gunicorn directly
has body: We are running haproxy --&gt; nginx --&gt; gunicorn --&gt; django. I need to send some request to django from the server itself, but can't use the http url i.e. either haproxy or nginx one due to some network restricton. Can I send a http request to gunicorn directly using python. Like to the below url which nginx uses http://unix:/code/tanmay.garg/web/utrade/run/gunicorn.sock
favorite count: 0
tagged with: gunicorn
tagged with: python
has answer: http://stackoverflow.com/a/52326727
score: 2

http://stackoverflow.com/comment/91642599
score: 0
has text: @NChauhan No to both since we must print each line (or the OP can modify to writing to an output file) no matter whether it is a comment, replaced line, or ignored line :)
type: AnswerComment
comment on: http://stackoverflow.com/a/52348497
type: Comment

http://stackoverflow.com/comment/91761190
score: 0
type: Comment
type: QuestionComment
has text: @jakevdp Thanks. I have updated the question.
comment on: http://stackoverflow.com/q/52397228

http://stackoverflow.com/q/52345850
has comment: http://stackoverflow.com/comment/91637626
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52351722
has answer: http://stackoverflow.com/a/52353831
has body: Blue element's href value is what i want to access from this HTML I tried few ways to print the link but didn't work. My code below:- discover_page = BeautifulSoup(r.text, 'html.parser') finding_accounts = discover_page.find_all("a", class_="author track") print(len(finding_accounts)) finding_accounts = discover_page.find_all('a[class="author track"]') print(len(finding_accounts)) accounts = discover_page.select('a', {'class': 'author track'})['href'] print(len(accounts)) Output:- 0 0 TypeError: 'dict' object is not callable URL of the webpage is https://society6.com/discover but URL changes to https://society6.com/society?show=2 after logging into my account What am i doing wrong here? note:- I am using selenium chrome browser here. Answer given here works in my terminal but not when i run the file My full code:- from selenium import webdriver import time import requests from bs4 import BeautifulSoup import lxml driver = webdriver.Chrome() driver.get("https://society6.com/login?done=/") username = driver.find_element_by_id('email') username.send_keys("exp4money@gmail.com") password = driver.find_element_by_id('password') password.send_keys("sultan1997") driver.find_element_by_name('login').click() time.sleep(5) driver.find_element_by_link_text('My Society').click() driver.find_element_by_link_text('Discover').click() time.sleep(5) r = requests.get(driver.current_url) r.raise_for_status() '''discover_page = BeautifulSoup(r.html.raw_html, 'html.parser') finding_accounts = discover_page.find_all("a", class_="author track") print(len(finding_accounts)) finding_accounts = discover_page.find_all('a[class="author track"]') print(len(finding_accounts)) links = [] for a in discover_page.find_all('a', class_ = 'author track'): links.append(a['href']) #links.append(a.get('href')) print(links)''' #discover_page.find_all('a') links = [] for a in discover_page.find_all("a", attrs = {"class": "author track"}): links.append(a['href']) #links.append(a.get('href')) print(links) #sou…
downvote count: 0
score: 1
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/91638242
has comment: http://stackoverflow.com/comment/91638100
tagged with: webdriverwait
type: Question
has comment: http://stackoverflow.com/comment/91641521
tagged with: python
has comment: http://stackoverflow.com/comment/91638281
has comment: http://stackoverflow.com/comment/91637581
has answer: http://stackoverflow.com/a/52351581
has title: How to print the href attributes using beautifulsoup while automating through selenium?
has comment: http://stackoverflow.com/comment/91648026
answer count: 3
tagged with: selenium
tagged with: web-scraping
upvote count: 1
has comment: http://stackoverflow.com/comment/91637709

http://stackoverflow.com/q/52360995
possible better answer: http://stackoverflow.com/a/52361087
has answer: http://stackoverflow.com/a/52361087
has title: What is the difference of A[i] and A[i,:] in n-dimensional(n>1) numpy array?
tagged with: numpy
accepted answer: http://stackoverflow.com/a/52361759
has body: Suppose X be a n-dimensional (n>1) numpy array. Is there any difference between X[i] and X[i,:]? for instance, X = np.zeros((3,3)) print(X[i]) #[ 0. 0. 0.] print(X[i,:]) #[ 0. 0. 0.] I think it is totally same but in my guess, I think there is some difference in terms of speed to access. But I don't know exactly.
type: AnsweredQuestion
tagged with: arrays
downvote count: 0
score: 1
favorite count: 0
type: Question
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52361759
upvote count: 1
tagged with: indexing

http://stackoverflow.com/comment/91662599
score: 0
comment on: http://stackoverflow.com/a/52359007
type: Comment
has text: Almost never. The purpose of a function (and of this function in particular) is to produce an object that could be used by the caller. If the caller decides to print it later, so be it. But if you print the value in the function, it cannot be used anymore.
type: AnswerComment

http://stackoverflow.com/comment/91714298
type: Comment
type: QuestionComment
has text: Put your code and your files hierarchy please !!!
comment on: http://stackoverflow.com/q/52384771
score: 0

http://stackoverflow.com/q/52407318
type: UnansweredQuestion
tagged with: sys
has comment: http://stackoverflow.com/comment/91758520
type: Question
linked to: http://stackoverflow.com/q/48395685
has comment: http://stackoverflow.com/comment/91758817
has comment: http://stackoverflow.com/comment/91758624
has title: Pass Variable from Script 1 to Script 2 to Script 3
score: 0
tagged with: python
has body: I'm trying to write a script which pass a variable from Script 1 to Script 2, then Script 2 pass a variable to Script 3 using subprocess. But I am only get responses from Scripts 1 and 2. What I am expecting to get out is: TOM Dick Harry Hello But what I'm getting is: TOM Hello The Code I'm using is: Script 1 import subprocess pythonExecutable = 'C:\\Users\\bradl\\Anaconda2\\envs\\GeoSpatial_3.6\\python.exe' varTest_1 = "Tom" program = 'D:\\Training\\FromCommandLine\\Script_2.py' subprocessList1 = [pythonExecutable, program, varTest_1] p1 = subprocess.Popen(subprocessList1, stdout=subprocess.PIPE, stdin=subprocess.PIPE) out1, err1 = p1.communicate() print(out1.decode('utf-8')) Script 2 import sys import subprocess pythonExecutable = 'C:\\Users\\bradl\\Anaconda2\\envs\\GeoSpatial_3.6\\python.exe' program = 'D:\\Training\\FromCommandLine\\Script_3.py' varTest_2 = sys.argv[1] print(str(varTest_2).upper()) varTest_3 = "Dick" subprocessList2 = [pythonExecutable, program, varTest_3] p2 = subprocess.Popen(subprocessList2, stdout=subprocess.PIPE, stdin=subprocess.PIPE) out2, err2 = p2.communicate() print(out2.decode('utf-8')) print('Hello') Script 3 import sys varTest_4 = sys.argv[1] print(varTest_4) print(str(varTest_4).upper()) print('Harry') Any help would be appreciated!
tagged with: python-3.x
tagged with: subprocess
answer count: 0

http://stackoverflow.com/comment/91609962
type: AnswerComment
comment on: http://stackoverflow.com/a/52331423
has text: @EricDuminil Yes, I've seen the comments after answering... I started editing the answer, but there's not much to add to Chris Rands' and your answer, I think...
score: 0
type: Comment

http://stackoverflow.com/q/52290175
has answer: http://stackoverflow.com/a/52293832
has body: I am trying to mimic the behavior of PCA class available in sklearn.decomposition. I have wrote a method which computes the SVD but I am not sure what does fit(), tranform(), and fit_transform() do without which I'm not able to proceed further. I think fit() computes the svd and the singular values can be accessed using the singular_values_ attribute but I don't know about the remaining two methods.
accepted answer: http://stackoverflow.com/a/52293832
type: AnsweredQuestion
tagged with: pca
type: Question
has comment: http://stackoverflow.com/comment/91531151
upvote count: 2
tagged with: scikit-learn
score: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/91530562
has comment: http://stackoverflow.com/comment/91530881
answer count: 1
has title: What does fit, transform, and fit_transform do in PCA available in sklearn.decomposition?
favorite count: 0
has comment: http://stackoverflow.com/comment/91531105
tagged with: python

http://stackoverflow.com/q/52366262
type: AnsweredQuestion
has body: I would like to use tokenColor in Visual Studio Code to highlight the initial binding of a variable in python. That is to say, the first time a variable name appears in its scope, I would like it to have a different color. This would usually be where the keyword "let" or "var" would be used in JavaScript. How would I go about adding this to VSCode?
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/52372145
type: Question
tagged with: visual-studio-code
accepted answer: http://stackoverflow.com/a/52372145
has title: Highlight initial variable assignment in python with VSCode
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/98023829
has text: @FrankDupree did issue got resolved ?
comment on: http://stackoverflow.com/q/52331614
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91625633
type: Comment
type: QuestionComment
has text: sorry it was a typo, wrong copy paste. see now what my code is.
comment on: http://stackoverflow.com/q/52333573
score: 0

http://stackoverflow.com/a/52281669
type: AcceptedAnswer
score: 4
accepted answer of: http://stackoverflow.com/q/52281365
type: Answer
answers question: http://stackoverflow.com/q/52281365
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/91512818
has body: I suspect this error only occurs when there are multiple mouse move events in the event queue. Normally, pygame is fast enough to render the screen while accruing no more than one new user input event, so sendCoords will only be called once in between drawCircles calls. In that case, coords never exceeds a size of 52. But if several mouse move events accrue (perhaps due to system lag, or because the user is jiggling his mouse really fast), then sendCoords may be called many more times in a row. So by the time drawCircles executes, coords can have 53 elements, or even more. This becomes a problem when you reach drawCircles: def drawCircles(snakeLength): for i in range(len(coords)): pygame.draw.circle(SCREEN, colorList[i], coords[i], abs(i-(len(coords))) * 5, 0)#### Why does the list index go out of range? if i &gt; snakeLength : popList() Let's say this function executes when coords contains 53 elements, and snakeLength is 50. The loop will iterate normally until i equals 51. Then the i &gt; snakeLength will evaluate to True, and popList will be called. Now coords is one element smaller, and has a length of 52. That iteration of the loop ends, and the next iteration starts. i will equal 52. The pygame.draw.circle line will attempt to access coords[i], but because coords no longer has 53 elements, coords[i] will raise an IndexError trying to access the 53rd element. Python is not smart enough to understand that the for i in range(len(coords)) loop should end one iteration earlier than usual if coords reduces in size by one. It happily iterates all the way up to the original length of the list, heedless of whether this might cause a crash. One possible solution is to move popList outside of the list, so the size of coords doesn't change while you're iterating over it. def drawCircles(snakeLength): for i in range(len(coords)): pygame.draw.circle(SCREEN, colorList[i], coords[i], abs(i-(len(coords))) * 5, 0)#### Why does the list index go out of range? while len(coords) &…

http://stackoverflow.com/a/52401997
has body: You can use to_datetime and then if necessary Series.dt.strftime with custom format, check http://strftime.org/: df['date'] = pd.to_datetime(df'YEAR','MONTH','DAY','HOUR','MINUTE') df['date_new'] = df['date'].dt.strftime('%Y:%m:%d:%H:%M') print (df) WMO_NO YEAR MONTH DAY HOUR MINUTE H PS T RH TD WDIR \ 0 4018 2006 1 1 11 28 38 988.6 0.9 98 0.6 120 1 4018 2006 1 1 11 28 46 987.6 0.5 91 -0.7 122 2 4018 2006 1 1 11 28 57 986.3 0.5 89 -1.1 124 3 4018 2006 1 1 11 28 66 985.1 0.5 90 -1.1 126 4 4018 2006 1 1 11 28 74 984.1 0.4 90 -1.1 127 WSP date date_new 0 14.4 2006-01-01 11:28:00 2006:01:01:11:28 1 15.0 2006-01-01 11:28:00 2006:01:01:11:28 2 15.5 2006-01-01 11:28:00 2006:01:01:11:28 3 16.0 2006-01-01 11:28:00 2006:01:01:11:28 4 16.5 2006-01-01 11:28:00 2006:01:01:11:28
score: 0
accepted answer of: http://stackoverflow.com/q/52401886
answers question: http://stackoverflow.com/q/52401886
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/52275799
score: 0
has body: Honestly, I don't think it is possible to have images in a stand-alone version unless it's strictly for personal use. I spent at least 4 hours attempting to fix this same issue but it didn't work. You can add an image with a .ico file and use it with --onefile but you won't be able to have others use it unless you give them the image file separately. pyinstaller --onefile --icon='Pig.ico' AnimalFacts.py
type: Answer
has comment: http://stackoverflow.com/comment/91499429
answers question: http://stackoverflow.com/q/52275634

http://stackoverflow.com/q/52395143
has answer: http://stackoverflow.com/a/52395176
type: Question
linked to: http://stackoverflow.com/q/32004096
has comment: http://stackoverflow.com/comment/91735430
possible better answer: http://stackoverflow.com/a/52395187
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91735398
has title: How can I add values to just one key in a dictionary in python?
has body: I'd like to add more than one value to a key in a dictionary, for example: dictionary={'id':(value1,value2)} How could I add value3 without overwriting id, value1 and value2? Sorry, this is my first ask Thank you
has comment: http://stackoverflow.com/comment/91735481
duplicate of: http://stackoverflow.com/q/32004096
has answer: http://stackoverflow.com/a/52395187
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/52395176
type: AnsweredQuestion

http://stackoverflow.com/comment/91517438
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52284505
type: AnswerComment
has text: Awesome! The first section did the trick. I think there is a syntax problem with the general solution, but the first part does the trick. Thanks so much!

http://stackoverflow.com/q/52335675
has title: Filter for strings in Pandas series
has body: Is there a better way than this to filter for strings in a Pandas series? Here's what I came up with: df = pd.DataFrame({'a': [1,2,3,4,'cat','hat','mat'], 'b': [1,2,3,4,5,6,7] }) Original: a b 0 1 1 1 2 2 2 3 3 3 4 4 4 cat 5 5 hat 6 6 mat 7 df = df[df['a'].apply(lambda x: isinstance(x, str))] Result: a b 4 cat 5 5 hat 6 6 mat 7 However, this syntax seems verbose. Is there something of the form? : df[df['a'].is_type(str)] EDIT: I'm interested in checking for type, not content. So, for example, I would like to include '12345' and exclude 12345.
has comment: http://stackoverflow.com/comment/91618589
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52335721
has comment: http://stackoverflow.com/comment/91664792
type: Question
answer count: 2
tagged with: pandas
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52335736
favorite count: 0
accepted answer: http://stackoverflow.com/a/52335721
possible better answer: http://stackoverflow.com/a/52335736
tagged with: python
upvote count: 2

http://stackoverflow.com/a/52338175
answers question: http://stackoverflow.com/q/52338113
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: A simple way would be to add all acceptable answers to a list: startSeq = ['word1', 'word2', 'word3'] Then change this line: while startSeq != 'Y' or startSeq != 'y': To this: while word.lower() in startSeq: To check for a bunch of different 'start' words. The .lower() makes it so 'Yes', 'YES', and 'yes' all would be true if 'yes' was in startSeq
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52338113

http://stackoverflow.com/a/52339421
type: Answer
has body: model.py class Article(models.Model): def __str__(self): return str(self.title) title = models.CharField( max_length=255 ) article_md = models.TextField( null=True ) article_html = models.TextField( null=True ) def save(self, *args, **kwargs): self.article_html = markdown.markdown(self.article_md, extensions=['gfm']) super(Article, self).save(*args, **kwargs) admin.py class ArticleAdmin(admin.ModelAdmin): exclude = ['article_html'] admin.site.register(Article, ArticleAdmin)
answers question: http://stackoverflow.com/q/52338215
score: 0

http://stackoverflow.com/comment/91598725
has text: Why aggregate `sum` ?
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52325876
type: Comment

http://stackoverflow.com/q/52407630
tagged with: python
tagged with: dictionary
tagged with: list
has title: how to calculate recall fast and correct with duplicate document id's python 2.7
type: Question
has comment: http://stackoverflow.com/comment/91758991
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/91766249
has comment: http://stackoverflow.com/comment/91765496
has comment: http://stackoverflow.com/comment/91759149
answer count: 0
type: UnansweredQuestion
has body: I have two tsv data files (gold and results) with four columns and I would like to calculate the recall score. Here is the format of the gold file: (doc1) 173 174 mike (doc2) 189 194 sara (doc2) 189 194 mike (doc2) 200 207 car format of the resluts file: (doc1) 173 174 mike (doc2) 189 194 mike (doc2) 200 207 car and here is my code: from __future__ import division def eval(): tp=0 #true positives fn=0 #false negatives gold=[] results=[] with open('/path/to/gold.tsv', 'rb') as goldFile, open('/path/to/results.tsv', 'rb') as f: for l in goldFile: parts = l.decode('utf-8').split('\t') try: gold.append((parts[0], parts[3])) except:pass for line in f: cols = line.decode('utf-8').split('\t') try: results.append((cols[0], cols[3])) except:pass for i,j in gold: doc = [] for docid in results: if results[0] == i: doc.append(docid) for k, v in doc: if j == v: tp += 1 gold.remove((i,j)) results.remove((i,j)) continue gold.remove((i,j)) fn += 1 return float(tp)/(tp+fn) print(eval()) The output is: 0.0 Recall should be 0.75 in the above case, what am I doing wrong? And how to calculate more efficiently? I tried with dictionaries but since I have duplicate documents id's that is not possible. I'd really appreciate any guidance. Thanks in advance.

concurrency
tag name: concurrency
tags question: http://stackoverflow.com/q/52381091
type: Tag

http://stackoverflow.com/q/52370355
tagged with: dataframe
score: -1
type: Question
has comment: http://stackoverflow.com/comment/91685272
upvote count: 0
has body: I have two pandas dataframes: df1 IDs Value1 Value2 Value Value4 AB 1 1 1 5 BC 2 2 2 3 BG 1 1 4 1 RF 2 2 2 7 and df2 Index 0 1 2 3 1 True False True True 2 False False True False 3 False False True False 4 False False False False with the same number of columns and rows. df1 contains integer values, while df2 contains Boolean values. What I need is to subset df1 in the following manner: get only the columns that in df2 have at least on True value. Expected output: IDs Value1 Value3 Value4 AB 1 1 5 BC 2 2 3 BG 1 4 1 RF 2 2 7 How can I do that without iterrations and lists, but using pandas functions? Expected ouput: Thank you.
tagged with: pandas
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91685589
has title: Subset a dataframe by another dataframe
favorite count: 0
has answer: http://stackoverflow.com/a/52370501
type: UnansweredQuestion
downvote count: 1

http://stackoverflow.com/q/52409792
tagged with: interpolation
has comment: http://stackoverflow.com/comment/92014946
tagged with: mathematical-optimization
answer count: 0
has comment: http://stackoverflow.com/comment/91763316
type: Question
score: 0
has body: I have several (denoted by index i) sets of datapoints (x,y) stored in vectors x_i and y_i. x_i is not necessarily of the same lenght as x_i+1. I want to interpolate the data for every i separately and then work with the interpolated functions f_i. I have tried with scipy.interpolate and get interp1d objects as a result. These however are not sufficient since I need Addition: f_i + f_i+1 scalar multiplication: a * f_i shift/ dilation: f(a * x + b) The goal is to optimize the difference between f_i+1 and some manipulation of f_i to find the evolution. This is very hard to accomplish using vectors since the x_i[n] does not necessarily correspond to x_i+1[n] (not even when i use interpolation and gridding) Thanks for any suggestions Stephan
has comment: http://stackoverflow.com/comment/91769968
tagged with: linear-interpolation
has title: Python: Data Interpolation: working with interpolated functions
type: UnansweredQuestion
tagged with: python
tagged with: data-fitting

http://stackoverflow.com/comment/91768047
type: Comment
comment on: http://stackoverflow.com/q/52411558
type: QuestionComment
has text: You essentially added a handler for the ValueError exception. You can read more about this topic here https://docs.python.org/3/tutorial/errors.html . That probably seems to have fixed the issue, but I suspect it just suppressed it. That may be sufficient for a best-effort algorithm, but I was more talking about using this to debug and not as a solution to the problem
score: 0

http://stackoverflow.com/comment/91774998
comment on: http://stackoverflow.com/a/52415653
type: AnswerComment
score: 0
type: Comment
has text: I'm interested in why the set finished faster than the normal list, as `ar` has only distinct values.

http://stackoverflow.com/comment/91664330
type: Comment
has text: @user2357112 I'd wager a bet that it's partially also because they're not promising formatting compatibility between minor versions.
comment on: http://stackoverflow.com/a/52359816
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91581335
comment on: http://stackoverflow.com/a/52313584
has text: The "background" is not a background, it corresponds to the values of Z_diff where Z_red == Z_blue. You can anyways change the map colour by passing a different value to `cmap='RdBu'`, in `ax.imshow()`. The zeroes will remain zeroes though, even if represented with a different colour.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91693656
has text: Depends whether you want to do that from a single website or several ones. In the former case you could spot where these informations are located in the received html and parse them using [regex](https://docs.python.org/2/library/re.html) for instance. Then you'd be able to send a request with all required informations. However, for the later case, I do not have a solution that works all the time. That would be on a per-case basis unfortunately...
score: 0
comment on: http://stackoverflow.com/q/52374231
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91534538
has text: maybe can you show your variable 'h'
type: QuestionComment
comment on: http://stackoverflow.com/q/52293248
score: 0
type: Comment

http://stackoverflow.com/comment/91568749
has text: It works fine for me on IPython 5.2.2 / Python 3.6.0 / Spyder 3.1.3 / Windows 7 64-bit until I press Ctrl-C, at which point I get what you're describing. What 'hotkey' are you pressing and are you sure you get the problem before that? (In a Python console in Spyder, Ctrl-C then Enter successfully breaks out of the same loop.)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52298957

http://stackoverflow.com/a/52315400
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52314725
has body: What about something like this: downloads = Download.objects.values('pub__edqm_id').annotate(count=Count('pub__edqm_id')) context = {'downloads': downloads, .... And in the template {% for download in downloads %} {{ download.pub__edqm_id }} {{ download.count }} {% endfor %}
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52314725
score: 1

http://stackoverflow.com/comment/91528190
has text: Actually @Kaloth I now have trouble converting that image to a bitmap using: `image_file = wx.Image(img, wx.BITMAP_TYPE_ANY).ConvertToBitmap()` `overload 2: argument 1 has unexpected type 'PngImageFile'`
comment on: http://stackoverflow.com/a/52289851
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52411968
has comment: http://stackoverflow.com/comment/91769646
has comment: http://stackoverflow.com/comment/91768827
has comment: http://stackoverflow.com/comment/91768688
has body: How do I access id from my child class? class BaseClass: id = 'testing' class MyClass(BaseClass): something = id More specifically, I can't access id from class:User: class BaseModel: id = db.Column(db.Integer, primary_key=True) class User(db.Model, BaseModel): username = db.Column(db.String(35), nullable=False, unique=True) followed = db.relationship( 'User', secondary=followers, primaryjoin=(followers.c.follower_id == id), secondaryjoin=(followers.c.followed_id == id), backref=db.backref('followers', lazy='dynamic'), lazy='dynamic')
has comment: http://stackoverflow.com/comment/91767750
has comment: http://stackoverflow.com/comment/91769175
linked to: http://stackoverflow.com/q/52414291
type: Question
duplicate of: http://stackoverflow.com/q/52414291
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/52412619
score: 0
has comment: http://stackoverflow.com/comment/91768942
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/91767695
has comment: http://stackoverflow.com/comment/91768715
has title: Accessing base class variable
has comment: http://stackoverflow.com/comment/91768897
has comment: http://stackoverflow.com/comment/91767780
type: UnansweredQuestion
tagged with: flask-sqlalchemy

http://stackoverflow.com/comment/91602100
score: 0
type: Comment
type: AnswerComment
has text: Thank you so much! I think i need to refresh my list comprehensions haha ;-)
comment on: http://stackoverflow.com/a/52326737

http://stackoverflow.com/comment/91708315
comment on: http://stackoverflow.com/q/52376233
type: Comment
type: QuestionComment
has text: Yes, just importing the model doesn't work, it asks for the `OutputLayerType` argument however, I'm not sure if the Keras Layers I have in my h5 have correspondence in Matlab due to use of the Lambda layer. I don't see that on the list of layers in Matlab. But i'm not sure if that's why this error is arising.
score: 0

http://stackoverflow.com/comment/91916917
comment on: http://stackoverflow.com/q/52416191
type: QuestionComment
has text: The `format` parameter in `to_datetime` only specifies the format of the *input*. Pandas Timestamp objects don't store information on how the *output* is supposed to be formatted. You'd have to do that manually as per sds's answer.
type: Comment
score: 0

http://stackoverflow.com/q/52315947
has comment: http://stackoverflow.com/comment/91587146
has comment: http://stackoverflow.com/comment/91581612
possible better answer: http://stackoverflow.com/a/52316100
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/7906365
favorite count: 0
accepted answer: http://stackoverflow.com/a/52317385
tagged with: python-3.x
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/52317385
has answer: http://stackoverflow.com/a/52316100
has comment: http://stackoverflow.com/comment/91579576
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91587788
score: 6
has comment: http://stackoverflow.com/comment/91582161
has body: I am trying to save a plot into a file using plt.savefig, however I am dissatisfied with the output picture quality. Changing dpi option doesn't help. plt.savefig('filename.png', dpi=1200, format='png', bbox_inches='tight') I tried saving to 'svg' and 'eps' - makes no difference. I wonder if the problem is with something else, like version of some library or OS or something alike. It also looks like the problem is not with resolution but the way lines and symbols are drawn - too bold. plt.show() shows significantly better picture, and I can save it to png with satisfying quality - and surprisingly file size is about 8 times smaller (because of compressing, I suppose, which is fine.) Part of the picture saved using savefig() The same part of the picture saved from plot.show()
type: Question
linked to: http://stackoverflow.com/q/47633546
tagged with: matplotlib
has title: plt.savefig output image quality

list-comprehension
tags question: http://stackoverflow.com/q/52335680
tags question: http://stackoverflow.com/q/52401321
tags question: http://stackoverflow.com/q/52366922
tags question: http://stackoverflow.com/q/52346338
tags question: http://stackoverflow.com/q/52316063
tags question: http://stackoverflow.com/q/52348813
tags question: http://stackoverflow.com/q/52347965
tags question: http://stackoverflow.com/q/52373938
tags question: http://stackoverflow.com/q/52392130
tags question: http://stackoverflow.com/q/52358608
tags question: http://stackoverflow.com/q/52344932
tags question: http://stackoverflow.com/q/52279479
tag name: list-comprehension
tags question: http://stackoverflow.com/q/52285502
tags question: http://stackoverflow.com/q/52347737
type: Tag
tags question: http://stackoverflow.com/q/52358763
tags question: http://stackoverflow.com/q/52414505
tags question: http://stackoverflow.com/q/52306013
tags question: http://stackoverflow.com/q/52344942
tags question: http://stackoverflow.com/q/52276345
tags question: http://stackoverflow.com/q/52379437

http://stackoverflow.com/q/52345587
has body: So I'm creating a website and I was wondering if I could create a button / link to open a FILE, not another website, but a .py file. -Thanks
type: Question
has title: Open a .py file in HTML using a link / button
answer count: 2
has comment: http://stackoverflow.com/comment/91637016
upvote count: 0
has comment: http://stackoverflow.com/comment/91637228
has answer: http://stackoverflow.com/a/52345816
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/91637339
favorite count: 0
tagged with: python
score: -2
accepted answer: http://stackoverflow.com/a/52345816
has answer: http://stackoverflow.com/a/52345751
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91641269
downvote count: 2
tagged with: file
possible better answer: http://stackoverflow.com/a/52345751

http://stackoverflow.com/a/52411849
type: Answer
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/52410615
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52410615
has body: Use Django's inspectdb to generate your models and then use the Django Admin to enter/manage data. You would first create a Django project and run inspectdb to create the models. You would then create an app within the project, and move the models file you created over to replace the default models.py file in the app. Ensure the Django admin is enabled. Then, within the app, you would add to the default admin.py file the models to include in the admin. You can get a quick look at the admin by just including admin.site.register(ModelName) in admin.py for each model you want to enter data into. To tailor the presentation of the model, you just create a class YourModelAdmin(admin.ModelAdmin) and define how you want a particular model to appear. Setting up a basic admin site is actually very quick and one of the strong points of Django.
upvote count: 3

http://stackoverflow.com/q/52300650
tagged with: pandas
upvote count: 0
answer count: 1
has body: I'm trying to find the average for all the values in one of the columns in my dataset. I did df["column"].mean() but It's giving me a ridiculously big number that does not make sense considering how small my values are. The min() and max() function works fine, however. Here is what I'm talking about. To clarify, left side of the output in the first cell are the indexes, and right side are the values. delay["If Delayed, for how long?"].astype(int) print(delay["If Delayed, for how long?"].min()) print(delay["If Delayed, for how long?"].max()) print(delay["If Delayed, for how long?"].mean()
linked to: http://stackoverflow.com/q/31037298
favorite count: 0
has answer: http://stackoverflow.com/a/52300721
score: -3
has title: Pandas .mean() for a column
tagged with: python
tagged with: jupyter-notebook
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91549057
downvote count: 3
accepted answer: http://stackoverflow.com/a/52300721
has comment: http://stackoverflow.com/comment/91549062
type: Question

http://stackoverflow.com/q/52428396
has body: I want to validate if multiple timestamps are distinct ,comma separated and in correct format 'yyyy-mm-dd-hh-mm'. case 1 - '2016-02-23-10-02','2017-01-24-11-05', '2017-02-23-11-05', '2016-02-23-10-02' case 2 - '2016-02-23-10-02' '2017-01-24-11-05' '2017-01-89' edit - added set later def get_input(timestamps): unique_timestamps = set(timestamps) for i in unique_timestamps: try: datetime.strptime(i, '%Y-%m-%d-%H-%M') except ValueError: #raise error
score: -1
has comment: http://stackoverflow.com/comment/91800686
tagged with: python-2.7
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52428509
has title: multiple dates validation in python
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91800265
downvote count: 1
type: Question

http://stackoverflow.com/q/52315059
has comment: http://stackoverflow.com/comment/91581769
tagged with: amazon-ec2
answer count: 1
downvote count: 0
tagged with: boto3
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52323713
score: 2
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91577367
has comment: http://stackoverflow.com/comment/91596089
has comment: http://stackoverflow.com/comment/91633655
type: Question
tagged with: boto
has comment: http://stackoverflow.com/comment/91580750
has title: Is it possible to create EC2 instance from describe_instances() output?
has body: Using python and BOTO3 service there is an option to use describe_instances() to get all the information about the running instances in specific region. If I use that and save the output in JSON, later input that json and pass it to create_instances(), is it going to work or the format is different from what I need to pass to create_instnaces() function? I'm asking that because I would like to make an automated option to get back a terminated instance which I have all its information saved. thanks!

http://stackoverflow.com/q/52287099
has comment: http://stackoverflow.com/comment/91522063
downvote count: 6
has answer: http://stackoverflow.com/a/52287504
has body: DISCLAIMER: I am not asking how to check if an element is contained within a list. I am asking how to check which list an element is contained in. Consider this code: x = ["i", "hello", "great"] y = ["what", "food"] chosen = input("Input a word: ") #what comes next? I want to print the name of the list that variable chosen is a part of (the program should print x, y, or just nothing at all) How would I determine which list the inputted word is a part of?
answer count: 3
has answer: http://stackoverflow.com/a/52287129
score: -6
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
upvote count: 0
has answer: http://stackoverflow.com/a/52287184
has title: How to check which list an element is contained in
type: Question

http://stackoverflow.com/comment/91636473
has text: You haven't shown a list in your example. Please don't leave us guessing what the structure is for either list.
score: 1
comment on: http://stackoverflow.com/q/52345330
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91535870
type: Comment
has text: Have you tried to run your terms aggregation on the `movies.keyword` field instead?
type: QuestionComment
comment on: http://stackoverflow.com/q/52271773
score: 0

http://stackoverflow.com/comment/91609739
score: 0
type: Comment
type: QuestionComment
has text: It's good practice to add resources that you have used for research in order to solve your problem.
comment on: http://stackoverflow.com/q/52331377

http://stackoverflow.com/q/52412567
has comment: http://stackoverflow.com/comment/91769215
tagged with: paho
favorite count: 0
has title: Check connection on publish Paho MQTT Python
type: UnansweredQuestion
tagged with: mqtt
tagged with: python
downvote count: 0
answer count: 0
has body: Are there any way to check connection to MQTT Broker on publish? Looking for all callbacks, I can't check before or after publish the status from connection. It's publish anyway, without network.
score: 1
type: Question
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/91770986
upvote count: 1

http://stackoverflow.com/a/52351834
has comment: http://stackoverflow.com/comment/91648803
score: 0
type: Answer
has body: You can define get_absolute_url method in your model and than access it in other model's methods. Check https://docs.djangoproject.com/en/2.1/ref/models/instances/#get-absolute-url
has comment: http://stackoverflow.com/comment/91648997
answers question: http://stackoverflow.com/q/52351803

http://stackoverflow.com/q/52360859
answer count: 2
has answer: http://stackoverflow.com/a/52360935
downvote count: 0
tagged with: discord
favorite count: 0
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/52360935
possible better answer: http://stackoverflow.com/a/65583683
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/65583683
upvote count: 3
has title: Send a message if Wait_For_Message timeout is reached Discord Py
type: Question
has body: I'm trying to send a message if the timeout is reached for client.wait_for_message. In this case it's 30 seconds. I used TimeoutError but it doesn't throw any errors or work. try: msg = await client.wait_for_message(timeout= 30, author=message.author, check=check) if msg: await client.send_message(message.channel, "Nice job! {} solved the scramble! The word was {}!".format(message.author.mention, word)) except TimeoutError: await client.send_message(message.channel, "Oops! Nobody solved it. The word was {}!".format(word))
tagged with: discord.py

http://stackoverflow.com/comment/91747857
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52401920
has text: It looks like the input frame does not have shape expected. Try checking the number of channels on such frame. Could it be that the video is already a one channel set of images?

http://stackoverflow.com/q/52422680
tagged with: python
tagged with: regex
has body: I have a string деревня Лесное, деревня Пальмово, село Поляково, город Стерлитамак Desire output ['деревня Лесное', 'деревня Пальмово', 'село Поляково'] I try to use villages_compiler = re.compile(r"""\b^(?:[Дд]еревня|[Сс]ело|[Рр]азъезд|[ДдСсПпХх]|[Сс]т|[Дд]ер|[Пп]ос([её]лок|[Кк]оллективный сад)?|[Пп]гт|[Рр]\.?\s?[Пп]|[Сc]адовое товарищество|ДНП|ДНТ|ДПК|ДТ|ЖК|СТ|СНТ|СПК|СО|СК)(?:\.|\s|\.\s)(?:\«?|\"?)[\w\s\.-]+(?:\»?|\"?)""" \ r"""|\b^[\w\s-]+(?:[Сс]ельсовет|[Шш]оссе)""") re.findall(villages_compiler, "деревня Лесное, деревня Пальмово, село Поляково, город Стерлитамак") But it returns an empty list. When I change findall() to search() I get only деревня Лесное How can I fix that problem?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91788719
has comment: http://stackoverflow.com/comment/91788409
accepted answer: http://stackoverflow.com/a/52423117
has comment: http://stackoverflow.com/comment/91788806
type: Question
has title: Regex: find a lot of patterns in one string
possible better answer: http://stackoverflow.com/a/52422890
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52422890
has answer: http://stackoverflow.com/a/52423117
has comment: http://stackoverflow.com/comment/91790785

http://stackoverflow.com/q/52317957
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91584463
tagged with: python
has comment: http://stackoverflow.com/comment/91583559
tagged with: node.js
answer count: 0
has comment: http://stackoverflow.com/comment/91584239
has comment: http://stackoverflow.com/comment/91584600
has comment: http://stackoverflow.com/comment/91584556
has comment: http://stackoverflow.com/comment/91584502
type: Question
has title: Executing Python from NodeJS (hosted on an external domain)
has comment: http://stackoverflow.com/comment/91584047
has comment: http://stackoverflow.com/comment/91583760
has comment: http://stackoverflow.com/comment/91583612
tagged with: express
score: 0
has comment: http://stackoverflow.com/comment/91584288
has body: So I have the following node.js express server running: const express = require('express') const app = express() const PythonShell = require('python-shell'); app.get('/', (req, res) =&gt; { res.send('Please append a search'); }); app.get('/:card', (req, res) =&gt; { card = [req.params.card] var pyshell = new PythonShell('search_card.py', {args: card}); pyshell.on('message', (message) =&gt; { res.send(message); }); pyshell.end((err) =&gt; { if (err) throw err; }); }); app.listen(9000, () =&gt; console.log('App listening on port 9000!')); When I use the app using the local IP of the server (which is hosted within the intranet), everything works fine. But if I use the external IP, the root of the app works ( / ) so clearly the connection is possible and the port is open, etc, but if I use the search function ( /search_query ), it takes a few seconds (as if the python script is actually running) and then chrome says ERR_CONNECTION_REFUSED (This site can't be reached). Can anyone explain this behavior? EDIT: I put a console.log inside the pyshell.on('message') and the data is being received from the python program. Its as soon as it writes ends that it fails
has comment: http://stackoverflow.com/comment/91584197

http://stackoverflow.com/q/52344818
favorite count: 0
has comment: http://stackoverflow.com/comment/91635688
tagged with: python
accepted answer: http://stackoverflow.com/a/52344996
has comment: http://stackoverflow.com/comment/91635739
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has body: I'm attempting to have my dataframe insert a particular value into a column. The desired value will be the 'Return Weather' where both the 'City' and 'Day' match the specified values. Here's a toy example: index City Weather Day Return City Return Weather 0 New York 65 3 Baltimore 1 Atlanta 77 6 Chicago 2 Baltimore 68 9 Orlando 3 Chicago 62 13 Boston 4 Boston 57 14 Atlanta 5 Orlando 88 19 New York 6 Baltimore 59 3 Chicago 7 Chicago 66 6 Atlanta Here's the code I'm trying: for i in df.index: day = df.loc[i, 'Day'] rtn_city = df.loc[i, 'Return City'] df.loc[i, 'Return Weather'] = df.loc[(df['City'] == rtn_city) &amp; (df['Day'] == day), 'Weather'].values However I get: ValueError: Must have equal len keys and value when setting with an iterable If I set the last line to print... results = df.loc[(df['City'] == rtn_city) &amp; (df['Day'] == day), 'Temp'].values print(results) I get the correct answers but they appear to be lists: [59] [66] Which smells like my problem. Any thoughts?
has title: DataFrame.loc produces list object instead of single value
has answer: http://stackoverflow.com/a/52344996
tagged with: pandas
answer count: 1
downvote count: 0

http://stackoverflow.com/q/52310689
has comment: http://stackoverflow.com/comment/91568660
tagged with: ipython
has body: Using the Python extension of Visual Studio Code, I can select some code, right-click it, and select "Run Selection/Line in Python Terminal" (alternatively, I can hit Shift+Enter). However, this sends the selected code to a plain old Python REPL in the Terminal pane, whereas I'd like to have this code run in IPython instead (not the QtConsole, just the terminal-based IPython). Is it possible to set IPython as the default REPL? I tried setting /usr/local/bin/ipython3 as my default Python environment, but that doesn't work (it still executes the plain Python interpreter). FWIW, I'm on macOS.
type: Question
tagged with: visual-studio-code
score: 62
has answer: http://stackoverflow.com/a/62342371
possible better answer: http://stackoverflow.com/a/52324509
downvote count: 0
answer count: 7
has answer: http://stackoverflow.com/a/59485636
has comment: http://stackoverflow.com/comment/103914968
linked to: http://stackoverflow.com/q/52615414
has title: Use IPython REPL in VS Code
has answer: http://stackoverflow.com/a/54564892
accepted answer: http://stackoverflow.com/a/60272350
has answer: http://stackoverflow.com/a/69231258
favorite count: 0
has answer: http://stackoverflow.com/a/52324509
tagged with: python
has answer: http://stackoverflow.com/a/60272350
has answer: http://stackoverflow.com/a/54875920
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91568434
has comment: http://stackoverflow.com/comment/126805867
upvote count: 62

http://stackoverflow.com/q/52311730
linked to: http://stackoverflow.com/q/20360675
possible better answer: http://stackoverflow.com/a/52312117
has answer: http://stackoverflow.com/a/52312117
has title: Realign different date ranges to "last x days" for each row
has answer: http://stackoverflow.com/a/52312853
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52312554
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/52312853
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/30428094
has body: I need to analyse the final 60 days up to the last date each user was active. My dataframe contains the dates ('CalendarDate') that each user ('DataSourceId') was active ('Activity' an integer) - one row per date. I have grouped the dataframe by DataSourceId so I have dates in the columns and I have grabbed the last day each user was active 'max_date': df['max_date'] = df.groupby('DataSourceId')['CalendarDate'].transform('max') The data look something like this although 'CalendarDate' and 'max_date' are actually datetime64[ns] format (the Activity values are float64): ID Jan1 Jan2 Jan3 Jan4 Jan5... max_date 1 8 15 10 Jan5 2 2 13 Jan3 3 6 11 Jan2 Now, I want to realign the columns from calendar dates to "last x days" for each row. Like this: ID Last Last-1 Last-2 Last-3 ... Last-x 1 10 15 8 2 13 2 3 11 6 I have not been able to find any examples of similar transformations and am really stranded here. EDITED: After adapting jezrael's solution I noticed it failed on occassion. I think the problem is related to this code in jezrael's solution: r = data_wide.bfill().isna().sum(axis=1).values Example: This data fails (and r = [0 3]): CalendarDate 2017-07-02 2017-07-03 2017-07-06 2017-07-07 2017-07-08 2017-07-09 DataSourceId 1000648 NaN 188.37 178.37 NaN 128.37 18.37 1004507 51.19 NaN 52.19 53.19 NaN NaN Specifically the realigned dataframe looks like this: Last-0 Last-1 Last-2 Last-3 Last-4 Last-5 DataSourceId 1000648 18.37 128.37 NaN 178.37 188.37 NaN 1004507 52.19 NaN 51.19 NaN NaN 53.19 If I change the order in the dataframe by changing ID 1000648 to 1100648 (so that it becomes the second row) this is the result (r = [0 2]): Last-0 Last-1 Last-2 Last-3 Last-4 Last-5 DataSourceId 1004507 NaN NaN 53.19 52.19 NaN 51.19 1100648 NaN 178.37 188.37 NaN 18.37 128.37
answer count: 3

http://stackoverflow.com/a/52411998
type: AcceptedAnswer
has body: The error is straightforward: when you define a function, the parameters you declare must be simple names, such as input_file. You tried to specify a compound name, as if you are trying to create a variable HistoricalQuotes with an attribute csv. This is not how you make such a variable. It appears that you might be trying to do something with a file named HistoricalQuotes.csv. If so, this is not at all the proper syntax. Work through a tutorial on file handling to see the range of applications and sample code for this. In your case, it might be something such as def get_data(): with open("HistoricalQuotes.csv", `r`): # Here is where you read the data from the file you just opened.
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52396503
answers question: http://stackoverflow.com/q/52396503

http://stackoverflow.com/a/52337538
type: Answer
has comment: http://stackoverflow.com/comment/91623674
has body: locals() is weird. Inside a function, every locals() call copies the current local variable values into a dict associated with the stack frame and returns the dict. The dict is not used for actual local variable lookup, but it is attached to the frame object, and it is not a new dict every time; all locals() calls in the same stack frame reuse the same dict. When you call locals(), the locals dict now has a reference to all objects currently referred to by local variables. This will keep those objects alive until either the stack frame dies, or a new locals() call is made inside that stack frame with different local variable values. A few other things will also update the locals dict, such as retrieving the f_locals attribute of the stack frame object, but local variable assignment does not update the locals dict by itself.
downvote count: 0
has comment: http://stackoverflow.com/comment/91623334
score: 5
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52337367
upvote count: 5
answers question: http://stackoverflow.com/q/52337367

http://stackoverflow.com/comment/91530323
type: Comment
type: QuestionComment
has text: I'm quite out of ideas myself, I develop in linux (ubuntu) since forever. Sorry :(
comment on: http://stackoverflow.com/q/52289061
score: 0

http://stackoverflow.com/comment/91550017
has text: I am not sure if I understood it completely. Do you think you can adapt the code that I sent? I would really appreciate it. I also edited the code according with DJK advice. But it is still to time consuming.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52300167
type: Comment

http://stackoverflow.com/a/52390907
type: Answer
has body: I had a go with pyvips. I don't know if that's a possibility for you. pyvips is a streaming image processing library, so rather than keeping everything in memory, it builds a network of operations and then streams pixels from your source images through the network and straight back to disc. This program will load an image, paste a lot more images on top at random positions, then write the result back. import sys import random import pyvips # the access hint means we want to stream this image base = pyvips.Image.new_from_file(sys.argv[2], access='sequential') for filename in sys.argv[3:]: tile = pyvips.Image.new_from_file(filename, access='sequential') x = random.randint(0, base.width - tile.width) y = random.randint(0, base.height - tile.height) base = base.insert(tile, x, y) # all the processing happens on the final save as the pipeline executes base.write_to_file(sys.argv[1]) For test data, I made 100 1,500 x 2,000 pixel images plus a 10,000 x 10,000 pixel background image. I can run it like this: $ /usr/bin/time -f %e:%M python3 ../insert.py x.jpg ../background.jpg *.jpg 775200:0.75 So that's 0.75s and 780mb of memory for the whole process. This is a big desktop machine with 32 threads. If I tell vips to run with fewer threads, memory use drops quite a bit: $ VIPS_CONCURRENCY=1 /usr/bin/time -f %e:%M python3 ../insert.py x.jpg ~/pics/huge.jpg *.jpg 199020:1.38 Under 200mb now, though it's slower.
upvote count: 5
score: 5
answers question: http://stackoverflow.com/q/52376476
downvote count: 0

http://stackoverflow.com/q/52334477
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52334651
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52334651
downvote count: 0
type: Question
upvote count: 2
tagged with: python-import
tagged with: discord.py
has title: Interact with background task with commands in submodule [discord.py]
has body: I have a Discord bot written with the non-rewrite version of discord.py that sends a heartbeat-like message (among other things). I don't know if I understood it correctly but from tests, I found out that I need to have the async def heartbeat() function in the main.py file. Excerpt from main.py (heartbeat works as intended): [...] import asyncio import datetime from configparser import ConfigParser startup_time = datetime.datetime.utcnow() [...] async def heartbeat(): await bot.wait_until_ready() heartbeat_config = ConfigParser() heartbeat_config.read('./config/config.ini') hb_freq = int(heartbeat_config.get('Heartbeat', 'hb_freq')) # frequency of heartbeat message hb_channel = heartbeat_config.get('Heartbeat', 'hb_channel') # target channel of heartbeat message hb_channel = bot.get_channel(hb_channel) # get channel from bot's channels await bot.send_message(hb_channel, "Starting up at: `" + str(startup_time) + "`") await asyncio.sleep(hb_freq) # sleep for hb_freq seconds before entering loop while not bot.is_closed: now = datetime.datetime.utcnow() # time right now tdelta = now - startup_time # time since startup tdelta = tdelta - datetime.timedelta(microseconds=tdelta.microseconds) # remove microseconds from tdelta beat = await bot.send_message(hb_channel, "Still running\nSince: `" + str(startup_time) + "`.\nCurrent uptime: `" + str(tdelta)) await asyncio.sleep(hb_freq) # sleep for hb_freq seconds before initialising next beat await bot.delete_message(beat) # delete old beat so it can be replaced [...] if __name__ == "__main__": global heartbeat_task heartbeat_task = bot.loop.create_task(heartbeat()) # creates heartbeat task in the background bot.run(token) # run bot I have some commands that are supposed to interact with the created heartbeat_task, but they are in a different module, called dev.py (residing in the same directory as main.py). Excerpt from dev.py: [...] from main import heartbeat_task, heartbeat [...] @commands.group(pass_context=True) async def h…
tagged with: python-asyncio
answer count: 1

http://stackoverflow.com/comment/91653027
type: AnswerComment
has text: Meaning it is not possible I could achieve that expectation. Understand `cursor.execute(query_string)` always return a tuple http://initd.org/psycopg/docs/cursor.html#fetch . Tone of thanks for your help on this :)
type: Comment
comment on: http://stackoverflow.com/a/52352068
score: 1

http://stackoverflow.com/comment/91647798
comment on: http://stackoverflow.com/q/52351006
score: 0
has text: I agree, the `transpose` looks suspect. It's not the division. It's a function parameter that's the wrong type or size. But also, what is the shape of `q`? Looks like it might be 1d.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140196282
comment on: http://stackoverflow.com/a/52335971
type: AnswerComment
score: 2
has text: @HaPsantran, `r'{}'.format(my_variable)` and `'{}'.format(my_variable)` are **exactly** the same thing; the difference between them accomplishes no benefit, because `{}` contains no characters with parsing that's different between raw and conventional interpretation. What's in `my_variable` is irrelevant, because `format()` is only called after `'{}'` or `r'{}'` is parsed, and they both parse to the exact same thing.
type: Comment

http://stackoverflow.com/comment/91633671
type: Comment
has text: python dict has unique keys
score: 0
comment on: http://stackoverflow.com/q/52343860
type: QuestionComment

http://stackoverflow.com/comment/91673275
comment on: http://stackoverflow.com/q/52364406
score: 0
type: Comment
type: QuestionComment
has text: @Bazingaa Thanks for that fixing a mistake. But how can I do a linear combinations of some sensors and fit it against each strain sensor

http://stackoverflow.com/q/52398738
type: Question
has answer: http://stackoverflow.com/a/52398767
has body: I use code as below to sort links: links = set(soup.findAll('a')) links = sorted(links, key=lambda x: x['href'], reverse=True) sometime I got error as this:
tagged with: sorting
has comment: http://stackoverflow.com/comment/91741563
has title: Python sort to avoid "KeyError: 'href'"
linked to: http://stackoverflow.com/q/14587728
upvote count: 1
downvote count: 0
answer count: 1
favorite count: 0
tagged with: keyerror
tagged with: beautifulsoup
tagged with: python
tagged with: lambda
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52398767

http://stackoverflow.com/a/52359980
has body: Python requires capturing groups to be fully closed before any backreferences (\2) to the group. You can use Positive Lookbehind (?&lt;=[\s,.]) and Positive Lookahead (?=[\s,.]) zero-length assertions to match words inside single quotes, including words such as I'm, i.e.: re.findall(r"(?&lt;=[\s,.])'.*?'(?=[\s,.])", string) Full match 56-92 'Hello Mam how are you doing today?' Full match 106-130 'I'm fine. How are you?' Explanation Regex Demo
accepted answer of: http://stackoverflow.com/q/52359897
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91764537
answers question: http://stackoverflow.com/q/52359897
has comment: http://stackoverflow.com/comment/91664695
type: Answer
has comment: http://stackoverflow.com/comment/91673776
score: 2
upvote count: 2

http://stackoverflow.com/q/52344356
linked to: http://stackoverflow.com/q/1335507
has title: How to add a time limit on user input?
downvote count: 1
has comment: http://stackoverflow.com/comment/91634767
has comment: http://stackoverflow.com/comment/91634931
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91634705
has comment: http://stackoverflow.com/comment/91634683
has comment: http://stackoverflow.com/comment/91634684
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91634785
type: Question
linked to: http://stackoverflow.com/q/23294658
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/15528939
has body: Is it possible to add a time limit for user input in Python? something like this: while true: ans = input("please enter a text") timelimit = 5 seconds if timelimit = reach restart the code the given code in the other solution is that if the time runs out it still asking for input and not restarting is there any way I can restart the script or loop it out after time runs out?
has comment: http://stackoverflow.com/comment/91634603
score: 0

http://stackoverflow.com/comment/91735410
score: 0
type: Comment
has text: Thanks so much your code Alexander! It works for me!!
type: AnswerComment
comment on: http://stackoverflow.com/a/52379258

error-handling
tags question: http://stackoverflow.com/q/52391688
tags question: http://stackoverflow.com/q/52299781
tags question: http://stackoverflow.com/q/52301906
tag name: error-handling
tags question: http://stackoverflow.com/q/52407669
tags question: http://stackoverflow.com/q/52354405
tags question: http://stackoverflow.com/q/52318352
tags question: http://stackoverflow.com/q/52392502
tags question: http://stackoverflow.com/q/52424543
tags question: http://stackoverflow.com/q/52307055
tags question: http://stackoverflow.com/q/52427828
type: Tag

http://stackoverflow.com/comment/91689152
score: 0
type: Comment
type: QuestionComment
has text: What about instances ex: Georgi and Georgus?
comment on: http://stackoverflow.com/q/52370113

http://stackoverflow.com/comment/92176662
comment on: http://stackoverflow.com/a/52332084
score: 0
type: Comment
type: AnswerComment
has text: that is very strange, normally there is no way an item loader can slow down the startup in any significant way, perhaps include code of your spider with and without item loaders

http://stackoverflow.com/comment/91516216
score: 4
comment on: http://stackoverflow.com/q/52283976
type: Comment
type: QuestionComment
has text: They are just matching those characters / symbols .

http://stackoverflow.com/comment/91801686
comment on: http://stackoverflow.com/a/52425849
has text: @FeitanPortor We are neither aware about your _requirement_ nor about your _usecase_. You have raised your question and contributors are trying to help you out in their own capacity. Feel free to use either the _code_ or the _logic_ within :) it would be your choice
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52423813
tagged with: number-formatting
score: 0
has body: I'm trying to format the follow program so that the results for 'average' are only displayed to 2 decimal places. I get that the '%.2f' % code is used to do that, but I can't figure out how to integrate it into the final line of code producing an error. Here is the program and I'm working on. #the user has to enter three numbers for the program to average #request the first number answer1 = input('Please enter the first number: ') answer1 = int(answer1) #request the second number answer2 = input('Please enter the second number: ') answer2 = int(answer2) #request the third number answer3 = input('Please enter the third number: ') answer3 = int(answer3) final = answer1 + answer2 + answer3 final = int(final) #print the average print('The average of these numbers is ', final / 3) It's the final line here that I can't figure out where to insert the '%.2f' % to return the results for 2 decimal places. Any help would be greatly appreciated.
has answer: http://stackoverflow.com/a/52423955
has comment: http://stackoverflow.com/comment/94377493
tagged with: python
type: UnansweredQuestion
has title: Formatting results to display two decimal places
linked to: http://stackoverflow.com/q/455612
has answer: http://stackoverflow.com/a/52423892
type: Question
answer count: 2

http://stackoverflow.com/a/52327337
has body: I think I don't understand the question properly. There are 3 cases: A, B both positive A negative, B positive A, B both negative Now if I do this (in Python 2, to avoid having to do list(range(...)): this makes the explanation cleaner): &gt;&gt;&gt; A = 10; B = 20 # case 1 &gt;&gt;&gt; range(A,B+1) [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] &gt;&gt;&gt; A = -10; B = 2 # case 2 &gt;&gt;&gt; range(A,B+1) [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2] &gt;&gt;&gt; A = -10; B = -2 # case 3 &gt;&gt;&gt; range(A,B+1) [-10, -9, -8, -7, -6, -5, -4, -3, -2] So your remark the last number in the range won't be included doesn't seem to fit with what I can see. If you are receiving input data where A &gt; B, then the problem is not the negative number, but the fact that range() expects the values to be in ascending order. To cover that: &gt;&gt;&gt; A = 2; B = -2 # case 4 &gt;&gt;&gt; A,B = sorted((A,B)) &gt;&gt;&gt; range(A,B+1) [-2, -1, 0, 1, 2] This also works for cases 1, 2, and 3. If I have misunderstood the question please edit it to clarify.
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/52327163
upvote count: 1

http://stackoverflow.com/a/52285140
type: Answer
has body: scipy got an exelent solution here https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html def defa(x, a,b,c,d): return a*b*c*d # the form for regresion you want to do var1, var2 = scipy.optimize.curve_fit(defa,[x cordinates],[y cordinates]) print(var1) # your a b c and d will ne printed out in order btw incase your installing scipy for your first time now, you should know that scipy also requires you to have numpy :) f.x. import numpy as np from scipy.optimize import curve_fit def defa(x,a,b,c,d,e): return a**2+b**3+c**4+d**5+e print(curve_fit(defa,range(1000),range(1000))) OUTPUT: (array([9.32720415, 4.0480121, 3.12719445, 2.49008364, 154.80388797]),array([...])) this means that a = 9.32720415 b = 4.0480121 c = 3.12719445 d = 2.49008364 e = 154.80388797
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/128420885
answers question: http://stackoverflow.com/q/52285109
downvote count: 0

http://stackoverflow.com/q/52300398
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/91549333
score: 0
has answer: http://stackoverflow.com/a/52300552
accepted answer: http://stackoverflow.com/a/52300552
answer count: 1
has comment: http://stackoverflow.com/comment/91548563
has comment: http://stackoverflow.com/comment/91549248
has comment: http://stackoverflow.com/comment/91548552
has title: Trying to import python list into another document?
tagged with: python
linked to: http://stackoverflow.com/q/29267006
has body: hello i am very new to stack overflow community so i hope you can understand i am new to python as well. at my school we are doing python we have not been taught it much and we have been assigned a task of making a log in for authenticated users as well as some other code that we are going to be looking into more detail in class. we were told to try at home to make the authenticated users log in. the requirements have to be that it has to get the data from a table from another file and that if its not that user then it will ask it to try again. This is what i tried to do. We learnt how to do the loops i think that this is right. this is my main.py from variables import authUsers import time ##Import All Variables count = 0 while count != 3: authenticate = input('Please enter a Valid Username') if authenticate in open(variables.py, 'r').readlines(1): print ("hello") else: exit and this is the variables.py i made authUsers = ['userA', 'userB', 'userC'] it returns an error saying Traceback (most recent call last): File "G:\Python\Computer Science\main.py", line 14, in &lt;module&gt; if authenticate in open(variables.py, 'r').readlines(1): NameError: name 'variables' is not defined i cant exactly understand why its not able to identify it they are in the same directories. thx again. Here are the websites i looked at to try and get an answer to my problem but i couldnt figure out what was rong. Import list variable from separate files in python https://docs.python.org/2/library/sys.html#sys.path https://codereview.stackexchange.com/questions/10536/try-every-username-and-password-from-a-list-on-a-website
has comment: http://stackoverflow.com/comment/91549104

http://stackoverflow.com/comment/91675839
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52298328
has text: This works!! Can i call a function when the search is triggered??
type: AnswerComment

http://stackoverflow.com/a/53675625
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52287254
has body: One way to make an evolving tensorflow network would be to use either hyperneat or the es-hyperneat algorithms instead of running the evolution on the individual networks in the species this instead evolves a "genome" that is actually cppn that encodes the phenotype neural nets. For the cppn you can use a feed forward tensorflow network with the caveat of having different activation functions that can be used at each node, this lets the cppn evolve to be able to be queried for the structure and weights of the "phenotype" neural network for which you can use a generic tensorflow net(or whatever net you so choose) I would look into the neat-python and peas libraries and look at the networks they use and replicate those classes with tensorflow nets.
type: Answer

http://stackoverflow.com/comment/91792338
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52371215
type: Comment
has text: @Maxime you're not putting it in the `for` loop are you? I'll update my answer to show exactly how it should look with your code.

http://stackoverflow.com/a/52285545
upvote count: 1
has body: A more "Pythonic" way of handling this is with enumeration. I would also recommend implementing file I/O by using open() as a context manager. For example: with open('4.3 data.txt', 'w', encoding='utf-8') as y_file: for i, item in enumerate(z): print(str(i) + ' ' + str(item), file=y_file)
has comment: http://stackoverflow.com/comment/91519434
score: 1
has comment: http://stackoverflow.com/comment/91519479
accepted answer of: http://stackoverflow.com/q/52285485
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52285485
has comment: http://stackoverflow.com/comment/91519519
type: Answer

http://stackoverflow.com/comment/91684054
comment on: http://stackoverflow.com/q/52343688
score: 0
type: Comment
type: QuestionComment
has text: You should post what your desired output looks like.

neomake
tags question: http://stackoverflow.com/q/52324317
type: Tag
tag name: neomake

http://stackoverflow.com/a/52427433
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91799017
type: Answer
has comment: http://stackoverflow.com/comment/91798747
accepted answer of: http://stackoverflow.com/q/52427357
upvote count: 2
has comment: http://stackoverflow.com/comment/91798382
has comment: http://stackoverflow.com/comment/91798460
score: 2
has body: You can try (assuming the date is sorted ) df.groupby(level=[0,1]).apply(lambda x : x.iloc[1:,:])
answers question: http://stackoverflow.com/q/52427357

http://stackoverflow.com/q/52355025
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: django
linked to: http://stackoverflow.com/q/11481499
has comment: http://stackoverflow.com/comment/91654797
has body: How can I define variable in django template engine and change it while iteration? I want to create panel for posts management that I get from database and display them in table. then I want to set counter for table and for each post that I get from db increase it by one But I don't know how to define and set variable in template engine.
has title: How can I define variable in django template engine
has comment: http://stackoverflow.com/comment/91654724
type: Question
score: 0

http://stackoverflow.com/comment/91845014
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52396100
has text: I used it to create the neighbors. Just do it in the REPL. Its basic slicing.
type: AnswerComment

http://stackoverflow.com/q/52384149
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91714194
has comment: http://stackoverflow.com/comment/91714836
has answer: http://stackoverflow.com/a/52386343
has comment: http://stackoverflow.com/comment/91712530
has title: Fast way to check if elements in sub-dimension of a numpy array is in sub-dimension of another numpy array
has answer: http://stackoverflow.com/a/52385130
score: 4
accepted answer: http://stackoverflow.com/a/52385130
possible better answer: http://stackoverflow.com/a/52386343
has comment: http://stackoverflow.com/comment/91713243
has comment: http://stackoverflow.com/comment/91712353
answer count: 3
has comment: http://stackoverflow.com/comment/91712401
tagged with: python
has body: Lets say we have two integer numpy array A and B of size (N,M). I would like to check for every i in N, is A[i,:] in B[i,:]. A for-loop implementation is: for i in range(N): C[i] = np.isin(A[i,:],B[i,:]) However this is quite slow for large array. is there any faster way to implement this? (e.g. vectorization?) Thanks!
favorite count: 0
upvote count: 4
linked to: http://stackoverflow.com/q/40588403
has comment: http://stackoverflow.com/comment/91713545
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52384347
downvote count: 0

jython-2.5
tag name: jython-2.5
type: Tag
tags question: http://stackoverflow.com/q/52281531

http://stackoverflow.com/comment/91662963
comment on: http://stackoverflow.com/q/52358798
score: 0
type: Comment
type: QuestionComment
has text: plt.plot(input, output, label = name, color=colors[line_num])

http://stackoverflow.com/a/52272565
upvote count: 1
has body: If the search term is not reflected in the URL, it means that it is transmitted to the server as a POST reqest. This means that your Scrapy code also needs to make a POST request in order to submit the desired search term. The Scrapy request documentation has examples for making a POST request, simulating a form submission: return [FormRequest(url="http://www.example.com/post/action", formdata={'name': 'John Doe', 'age': '27'}, callback=self.after_post)]
answers question: http://stackoverflow.com/q/52272406
accepted answer of: http://stackoverflow.com/q/52272406
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/a/52342511
score: 0
type: Answer
has body: If I'm not mistaken request.form is a Multidict type which is like a Python dictionary. So you can get a default value from dictionary if you are not sure if the key exists, and avoid throwing the error in your application like this: search_filter = request.form.get("mysearch", "") search_term = request.form.get("search_term", "") And then check search_filterif it is empty or it has value.
answers question: http://stackoverflow.com/q/52341937

http://stackoverflow.com/comment/91512998
comment on: http://stackoverflow.com/q/52282245
type: QuestionComment
has text: I concur with @ShadowRanger, that it's difficult to do more than a prediction without additional information. I'd add that depending on how you are making the call out to the shell, if you in fact **are** passing the path to the python script as the second argument, you may be in the wrong working directory and it won't be able to find the script -- leaving the console to hang. Good luck!
type: Comment
score: 0

http://stackoverflow.com/q/52352226
has body: I'm trying repeat the rows of a dataframe. Here's my original data: pd.DataFrame([ {'col1': 1, 'col2': 11, 'col3': [1, 2] }, {'col1': 2, 'col2': 22, 'col3': [1, 2, 3] }, {'col1': 3, 'col2': 33, 'col3': [1] }, {'col1': 4, 'col2': 44, 'col3': [1, 2, 3, 4] }, ]) which gives me col1 col2 col3 0 1 11 [1, 2] 1 2 22 [1, 2, 3] 2 3 33 [1] 3 4 44 [1, 2, 3, 4] I'd like to repeat the rows depending on the length of the array in col3 i.e. I'd like to get a dataframe like this one. col1 col2 0 1 11 1 1 11 2 2 22 3 2 22 4 2 22 5 3 33 6 4 44 7 4 44 8 4 44 9 4 44 What's a good way accomplishing this?
accepted answer: http://stackoverflow.com/a/52352487
possible better answer: http://stackoverflow.com/a/52352350
tagged with: python-3.6
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/91649543
downvote count: 0
has answer: http://stackoverflow.com/a/52352487
favorite count: 0
has title: repeating the rows of a data frame
upvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/91649462
has answer: http://stackoverflow.com/a/52352350
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/24029659
has comment: http://stackoverflow.com/comment/91649446
type: Question
score: 5

http://stackoverflow.com/comment/91604299
score: 0
type: Comment
has text: Neat, thanks a lot. I will try comparing it to the answer by @EE_ below, but it's great to have 2 approaches
comment on: http://stackoverflow.com/a/52320926
type: AnswerComment

http://stackoverflow.com/comment/91783657
comment on: http://stackoverflow.com/q/52418511
type: Comment
type: QuestionComment
score: 0
has text: Please add python version information, pylint version information, the file content which you are trying to validate.

http://stackoverflow.com/comment/91564281
type: QuestionComment
has text: Your current import doesn't even make it clear that `division` is a future import: it could be a random function, variable or class defined in the parent. That is very confusing.
comment on: http://stackoverflow.com/q/52308367
score: 0
type: Comment

http://stackoverflow.com/comment/91627170
type: QuestionComment
has text: @BAt - Have you single-stepped through your code in a debugger? If you do, you will see why you are getting the incorrect answers. The first comment you received from John said "...can you clearly put into words how you would go about doing it...", this is a good way to code, write comments _first_ as to how you will do it (line by line) and then replace those with code.
comment on: http://stackoverflow.com/q/52339274
score: 0
type: Comment

http://stackoverflow.com/comment/91784232
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52419788
type: Comment
has text: @user3017048 Your original question suggests that `tdarray` is 1D... Yes, the latter two breaks for 2D array because iterating over `tdarray` gives 1D arrays and we cannot apply `math.isnan` or do `x.days` on them. What you can do is use `tdarray.ravel()` to flatten the array before iterating over it then reshape `tdarray` to its original shape.

http://stackoverflow.com/comment/91588891
type: Comment
type: QuestionComment
has text: In general `savefig` should come *before* `show`. Not sure in how far this could create the reported problem though. [This is the output](https://i.sstatic.net/5753M.png) i get, which looks the same to me.
comment on: http://stackoverflow.com/q/52284547
score: 0

http://stackoverflow.com/a/52356961
upvote count: 3
answers question: http://stackoverflow.com/q/52356646
has body: The dict.keys() view object supports set operations: dict1.keys() &amp; dict2.keys() # equivalent to set(dict1).intersection(dict2) However, for smaller dictionaries using a set will probably be faster: In [1]: dict1 = {'a': 'b', 'c': 'd'} In [2]: dict2 = {'b': 'c', 'c': 'd'} In [3]: %timeit dict1.keys() &amp; dict2.keys() 448 ns ± 1.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [4]: %timeit set(dict1).intersection(dict2) 330 ns ± 0.602 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) Note that set.intersection() accepts any iterable as an argument, so you can just pass dict2 to it. Also, no need to call dict1.keys()as a dict object by default iterates over its keys.
downvote count: 0
type: Answer
score: 3

http://stackoverflow.com/q/52329266
score: 2
downvote count: 0
type: Question
upvote count: 2
has title: Django rest framework - Create or update values from json
tagged with: django-rest-framework
has body: I am very much new to Django and Django Rest Framework. I have an API whose json format is as below (Simplified version for sake of simplicity) { "title" : "Lorem ipsum is a dummy title", "content" : "Lorem ipsum is a demo content" "tags" : ["Movies", "Food"] } Here is how my model looks like: class Tag(models.Model): class Meta: verbose_name_plural = "Tags" name = models.CharField(max_length=200) def __str__(self): return self.name class Post(models.Model): class Meta: verbose_name_plural = "Posts" title = models.CharField(max_length=255) content = models.TextField() tags = models.ManyToManyField(Tag, blank=True) def __str__(self): return self.title Here is how my serializer (Tags, Posts) looks like: class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' name = serializers.CharField(max_length=200) def create(self, validated_data): return Tag.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.save() return instance class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('title', 'content', 'tags') title = serializers.CharField(max_length=250) content = serializers.CharField(max_length=1000) tags = serializers.PrimaryKeyRelatedField(many=True, queryset=Tag.objects.all()) def create(self, validated_data): tags = validated_data.pop('tags') # [do i need to look for tags, create if not exists and retrieve the ids] post = Post.objects.create(**validated_data) for tg in tags: post.tags.add(tg) return post def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.content = validated_data.get('content', instance.content) tags = validated_data.pop('tags') # [do i need to check for tags, create if not exists and retrieve the ids] instance.save() return instance So I wish to save the post details with tags such that it create the tags if not exists. As i am new to…
has answer: http://stackoverflow.com/a/52329400
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/q/52275874
tagged with: python
type: AnsweredQuestion
score: 1
has title: Daemon thread keep alive in ipython when running python script
tagged with: multithreading
has answer: http://stackoverflow.com/a/52276041
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52276041
has body: Consider the following lines of code: import time import threading keepAlive = True def threadHandler(): print('thread started') while keepAlive: time.sleep(1) print('thread ended') tt = threading.Thread(name='SomeThread',target=threadHandler) tt.setDaemon(True) tt.start() If I copy and paste these lines into ipython, then, whenever I want, I can just type keepAlive = False to make the thread exit. Which is good! However, if I save the code above into a file named foo.py and then run it in ipython by doing %run foo.py, doing keepAlive = False in the ipython shell has absolutely no effect and the thread just carries on executing. It's as if threadHandler() had its own private copy of what the value of keepAlive was when the thread started. Is there a way to solve this?
tagged with: ipython
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/91664302
type: Comment
has text: Thanks. That helped. The issue i have is that sometimes param1 or param2 are null. I think i need to add a case statement to handle this?
score: 1
comment on: http://stackoverflow.com/a/52351895
type: AnswerComment

http://stackoverflow.com/comment/91589757
has text: Thanks for your help and time Kevin! @MooingRawr has shared his code that worked. :D
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52320198
type: Comment

http://stackoverflow.com/comment/91660134
type: QuestionComment
score: 0
has text: Please include a _legal_ Python matrix in your example.
comment on: http://stackoverflow.com/q/52357802
type: Comment

http://stackoverflow.com/a/52364100
has comment: http://stackoverflow.com/comment/91682235
has body: Like most GUI frameworks, pyglet uses a so-called "event loop". This is the thing that's started with pyglet.app.run(). It indeed blocks the current thread (not process) and schedules all the events that happen within the GUI framework. If you want to run your own stuff in between, you have to do it via the event loop, see https://pyglet.readthedocs.io/en/latest/programming_guide/time.html#guide-calling-functions-periodically. Alternatively, you can try to create a new thread (not process), but then you have to take care when accessing things that are potentially also accessed from the pyglet event loop. GUI frameworks are typically single-threaded and are often not thread-safe (I don't know details about pyglet). If you create an additional thread, you have to be very careful when interacting with the event loop from the other thread.
score: 0
has comment: http://stackoverflow.com/comment/91687647
type: Answer
has comment: http://stackoverflow.com/comment/91687307
answers question: http://stackoverflow.com/q/52357685

http://stackoverflow.com/comment/91776997
has text: What version of Julia are you using and where did the `conv` function come from?
comment on: http://stackoverflow.com/q/52416580
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91591689
has text: I use os.getcwd() to get the correct path to the bash script.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52322051

http://stackoverflow.com/comment/91752554
has text: `dict(map(reversed, d.items()))['k1']` -> `'key1'`. Assumes that your values are hashable and unique.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52404410

http://stackoverflow.com/comment/91748583
score: 0
type: Comment
type: QuestionComment
has text: You are right... I am sorry....
comment on: http://stackoverflow.com/q/52399793

http://stackoverflow.com/q/52349811
has comment: http://stackoverflow.com/comment/91645316
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: I'm attempting to build a query which will return a list of all technologies and the score of each user associated with each technology. This is based on the following models: class Technology(models.Model): technology = models.CharField(max_length=64) class Result(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) technology = models.ForeignKey(technology, on_delete=models.CASCADE) skill_level = models.ForeignKey(skill, to_field='level', on_delete=models.CASCADE) class Skill(models.Model): level = models.IntegerField(unique=True) Essentially I'd like to see somthing similar to the following: {technology: Cisco, users: {Alex: {skill_level: 1}}, {James: {skill_level: 2}} I'm not sure whether this can be acheived with a simple query or whether custom joins will need to be done? I'm also not sure whether I should be building this on the Technology model or the Result model?
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91645466
has title: Django - create dictionary of associated objects
has comment: http://stackoverflow.com/comment/91645430
has answer: http://stackoverflow.com/a/52350557
linked to: http://stackoverflow.com/q/7811556
has comment: http://stackoverflow.com/comment/91645392
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91645452
accepted answer: http://stackoverflow.com/a/52350557
has comment: http://stackoverflow.com/comment/91645198

http://stackoverflow.com/a/52387247
answers question: http://stackoverflow.com/q/52386913
score: 0
has body: you can group first and sort the values df.groupby('month').apply(lambda x: x.sort_values(['duration'],ascending=False)) Out: month user duration month 9 1 9 user_02 55.82 0 9 user_01 54.73 2 9 user_03 18.00
type: Answer

http://stackoverflow.com/q/52275090
has comment: http://stackoverflow.com/comment/91497789
has answer: http://stackoverflow.com/a/52275978
type: UnansweredQuestion
type: Question
score: 0
answer count: 2
has title: DataFrame arithmetic based on subset
tagged with: pandas
has comment: http://stackoverflow.com/comment/91498256
has comment: http://stackoverflow.com/comment/91497845
has body: Having a dataframe similar to: Country Column1 Product Week Val UK S1 A 2019-36 10 UK S1 A 2019-37 20 UK S1 A 2019-38 30 UK S1 B 2019-36 30 UK S1 B 2019-37 30 UK S1 B 2019-38 30 DE S1 A 2019-39 100 DE S1 A 2019-40 100 DE S1 A 2019-41 100 DE S1 B 2019-36 10 DE S1 B 2019-37 15 DE S1 B 2019-38 10 How does one go about saying: If Product = "B" then take the VAL from product "A" where all other columns are the same (Country, Column1 &amp; Week) and add 50% of that Val to the current value? E.g. The first "B" would have a value of 35: 30 + (50%*10) The second one 40: 30 + (50%*20) and the third one 45: 30 + (50%*30)
tagged with: python
has answer: http://stackoverflow.com/a/52275491

http://stackoverflow.com/q/52429696
has body: I encountered a problem while reading a CSV file with np.genfromtxt. All the records in CSV are in scientific notation, yet whilst reading the file with np.genfromtxt every item in the array is 'nan'. An example row from CSV: 1.02E+02;1.64E+00 In [1]: read = np.genfromtxt('13G-mapa-0001.CSV', delimiter=';') In [2]: read Out[2]: array([[nan, nan], [nan, nan], [nan, nan], ..., [nan, nan], [nan, nan], [nan, nan]]) Full file: 1,204619e+002;1,639486e+000 1,214262e+002;1,623145e+000 1,223904e+002;1,607553e+000 1,233547e+002;1,592153e+000 1,243189e+002;1,576472e+000 1,252832e+002;1,560220e+000 1,262474e+002;1,543355e+000 1,272117e+002;1,526069e+000 1,281759e+002;1,508706e+000 1,291402e+002;1,491635e+000 1,301044e+002;1,475144e+000 1,310686e+002;1,459387e+000 1,320329e+002;1,444416e+000
has title: Numpy converts scientific notation to nan while reading CSV
has comment: http://stackoverflow.com/comment/91803188
score: 1
has answer: http://stackoverflow.com/a/52431248
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91803006
has answer: http://stackoverflow.com/a/52430096
downvote count: 0
answer count: 3
linked to: http://stackoverflow.com/q/10140999
has answer: http://stackoverflow.com/a/52429788
tagged with: nan
favorite count: 0
linked to: http://stackoverflow.com/q/22970854
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/91670904
type: QuestionComment
comment on: http://stackoverflow.com/q/52363390
score: 2
has text: Please show the full traceback. Where is the error happening?
type: Comment

http://stackoverflow.com/a/52366346
answers question: http://stackoverflow.com/q/52365943
score: 2
downvote count: 0
has body: Try using openpyxl to save the outputs in excel sheet from openpyxl import Workbook book = Workbook() sheet = book.active a = input('enter the string') print(a) b = input('enter the number') print(b) sheet['A1'] = a sheet['B1'] = b book.save("test.xlsx")
upvote count: 2
has comment: http://stackoverflow.com/comment/91677332
type: Answer

http://stackoverflow.com/comment/91919629
score: 0
has text: If you encounter a bug in matplotlib you may report it at [the issue tracker](https://github.com/matplotlib/matplotlib/issues).
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52408068

http://stackoverflow.com/q/52286821
has comment: http://stackoverflow.com/comment/91521655
favorite count: 0
has title: Updating a list within a loop by applying a function
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91521671
has comment: http://stackoverflow.com/comment/91521645
has body: I'm trying to write a simple loop in Python. Here's the code: N = 1000 xrange = np.arange(-1.0,0.0,1.0/N) drange = 1.0 + xrange yrange = np.zeros(N) range = np.arange(0,N,1) for i in range: if drange[i] == 1.0: yrange[i] == 1.0 else: yrange[i] == np.log(drange[i])/(drange[i] - 1.0) print(yrange) However after the for loop has run, the list yrange doesn't get updated. It still has all values at zero. Is there anything wrong with the else: part of the loop?
has comment: http://stackoverflow.com/comment/91521817
score: 1
tagged with: loops
type: Question
has answer: http://stackoverflow.com/a/52286898
has comment: http://stackoverflow.com/comment/91521619
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/91737678
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52396342
score: 0
has text: Thanks for the assist! Had a feeling it was something in the formatting. Including the append inside the loop was the way to go.

http://stackoverflow.com/comment/91581556
type: AnswerComment
has text: I don't need to fix the problems automatically - I just need to get the document to a state where it retains structure but not content. If I can eyeball it and determine the deformity in the XML, I can fix them at source.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52317039

http://stackoverflow.com/a/66661021
answers question: http://stackoverflow.com/q/52311724
downvote count: 0
has body: I was using white noise in my applications after removing this: STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' and adding this: STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' solved the problem
score: 3
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/127084921

http://stackoverflow.com/comment/91787186
type: QuestionComment
has text: @deceze The hash value of an integer is determined by the integer's value. It has nothing to do with its memory address. (OTOH, there are some situations where it can be useful for the `__hash__` method of an object to use the id of the object). The order in a set (or a pre-3.6 dict) depends on the items' hash value and the order of insertion (& deletion).
comment on: http://stackoverflow.com/q/52421508
score: 0
type: Comment

http://stackoverflow.com/comment/91615468
type: Comment
type: QuestionComment
has text: Is your issue that you want to merge all "combinations" with "count" 1 into a single "combination" called "Other" with the appropriate count?
comment on: http://stackoverflow.com/q/52334127
score: 0

http://stackoverflow.com/comment/91787887
comment on: http://stackoverflow.com/q/52420164
score: 0
type: QuestionComment
has text: @Rafi, yes but a test case has 5 points of verification and for that test case i have made a class that has a method test_tc_01 which has 5 assertions. one for each verification point. If the first assertion fails. The rest of the asserts will be skipped
type: Comment

http://stackoverflow.com/comment/91518399
score: 1
comment on: http://stackoverflow.com/q/52284979
type: Comment
has text: See https://stats.stackexchange.com/questions/352036/what-should-i-do-when-my-neural-network-doesnt-learn (I asked the question to be closed though, it's OT).
type: QuestionComment

http://stackoverflow.com/a/52272490
downvote count: 0
answers question: http://stackoverflow.com/q/52272229
score: 1
has body: Try: df['Start']=pd.to_datetime(df['Start']) df['prevNum']=df['rowNow'].shift() df['nextNum']=df['rowNow'].shift(-1) df.loc[df['Start'].dt.hour!=df['Start'].shift().dt.hour,'prevNum']=pd.np.nan df.loc[df['Start'].dt.hour!=df['Start'].shift(-1).dt.hour,'nextNum']=pd.np.nan print(df) If column start is not a datetime format, do: df['Start']=pd.to_datetime(df['Start']) before everything Output: index Case Button Start rowNow prevNum nextNum 0 x a 2017-12-06 2018-09-11 10:17:43.227 0 NaN 1.0 1 x b 2017-12-06 2018-09-11 10:17:44.876 1 0.0 2.0 2 x c 2017-12-06 2018-09-11 10:17:45.719 2 1.0 NaN 3 y a 2017-12-06 2018-09-11 15:28:57.500 3 NaN 4.0 4 y e 2017-12-06 2018-09-11 15:29:19.079 4 3.0 NaN
accepted answer of: http://stackoverflow.com/q/52272229
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91492690
type: Answer
has comment: http://stackoverflow.com/comment/91518863

http://stackoverflow.com/comment/91576444
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52310978
has text: is there a way to do the convolution (the explanation provided) on .eps or pdf files??? I looked and didn't find a way that could work, could you guide on this??? Thanks in advance for ur reply :)

http://stackoverflow.com/q/52422327
has title: How to use part of a tensor in Keras?
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/91791400
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91814908
score: 2
downvote count: 0
type: Question
has body: I want to use part of a the tensor in the output of lstm layer, but don't know how to do it correctly. My purpose is tell LSTM layer the "real" length of its input sequence. Here is my attempt, but it fails. Isthere anyone who can help solve this problem and explain the details, thanks a lot~ input_spectrogram = Input(shape=(64,500,1)) input_length = Input(shape=(1,)) cnn1 = Conv2D(filters = 64, kernel_size = (1,4),input_shape=(64,500, 1),padding = 'same',strides = 1,activation = 'relu',name='conv1')(input_spectrogram) maxpooling1 = MaxPooling2D(pool_size = (1,4),name='maxpooling1')(cnn1) bn1 = BatchNormalization(name='BN1')(maxpooling1) cnn2 = Conv2D(filters = 128, kernel_size = (64,1),strides = 1,activation ='relu',name='conv2')(bn1) maxpooling2 = MaxPooling2D(pool_size = (1,2),name='maxpooling2')(cnn2) reshape = Reshape((62,128))(maxpooling2) lstm1 = LSTM(128,return_sequences = True,recurrent_dropout=0.3,name='lstm1')(reshape) #output:(None,62,128) softmax_in = Lambda(lambda x:x[0][x[1],:])([lstm1,input_length]) softmax_ = Dense(10,activation='softmax',name='softmax_')(softmax_in) seq = Model(inputs=input_spectrogram, outputs=[softmax_]) seq.compile(loss='categorical_crossentropy', optimizer='adadelta',metrics=['accuracy'])
has answer: http://stackoverflow.com/a/52424278
has answer: http://stackoverflow.com/a/52436321
upvote count: 2
answer count: 2

http://stackoverflow.com/a/52313321
upvote count: 1
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/52313194
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52313194
has body: I think converting to Index is not necessary, simply assign it or use DataFrame.set_index: df.index = arr Or: df = df.set_index(arr)

http://stackoverflow.com/comment/91498110
comment on: http://stackoverflow.com/a/52275187
type: Comment
has text: Note: changing `s` to `set` leads to amortized time complexity equal to `O*(n)`. The worst case time compelxity is still `O(n^2)`
score: 1
type: AnswerComment

http://stackoverflow.com/q/52295704
upvote count: 11
type: AnsweredQuestion
tagged with: redis-py
has answer: http://stackoverflow.com/a/52451988
has body: Except that python-redis-lock module provides contextmanager for the lock object - what are the differences when compared to the lock object you get from redispy module? what is so special about python-redis-lock? rc = Redis.from_url(settings.BROKER_URL) lock_str = "bld-%s-lock" % bld_id Using redispy: lock = rc.lock(lock_str) Using python-redis-lock: lock = redis_lock.Lock(rc, lock_str)
type: Question
has title: redis locking: redispy vs python-redis-lock
accepted answer: http://stackoverflow.com/a/52451988
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91708569
favorite count: 0
tagged with: redis
tagged with: python
score: 11

http://stackoverflow.com/a/52320300
has comment: http://stackoverflow.com/comment/91588668
accepted answer of: http://stackoverflow.com/q/52320232
has body: communicate sends the contents of the buffer to standard input then closes the input pipe, which ends up terminating the process. So you cannot do something interactive with that. Moreover, you have to pass stdin argument to Popen or by default nothing is redirected. import subprocess proc = subprocess.Popen('cmd.exe',stdin=subprocess.PIPE) now you can write lines to proc.stdin (don't forget line terminators &amp; binary prefix for python 3 compat.) and see what happens proc.stdin.write(b"cd Documents\n") (okay, you could have used cwd="Documents" for that one, but that's for the sake of the example) In the example, output is not redirected. Which means that you'll see the output in the current console. Don't forget to close standard input or that won't work (probably because buffer isn't flushed and/or pipe is broken when python quits). Then wait for process to finish with wait() Complete example: import subprocess proc = subprocess.Popen('cmd.exe',stdin=subprocess.PIPE) proc.stdin.write(b"cd ..\n") # do some stuff in between... proc.stdin.write(b"cd\n") proc.stdin.close() proc.wait() on my computer it prints (excuse my french) Microsoft Windows [version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. Tous droits réservés. L:\so&gt;cd .. L:\&gt;cd L:\ if you want the process not to terminate, you could use some more tricks: import subprocess,time proc = subprocess.Popen('cmd.exe',stdin=subprocess.PIPE) proc.stdin.write(b"cd ..\n") proc.stdin.write(b"cd\n") proc.stdin.flush() time.sleep(1) input("press return") proc.stdin.write(b"cd\n") proc.stdin.flush() proc.stdin.close() proc.wait() this sends commands, flushes standard input (but doesn't close it) then waits for the messages to print, and asks for a key to be pressed. You can send more commands after that, as long as you flush each time, and close in the end.
has comment: http://stackoverflow.com/comment/91588098
type: Answer
answers question: http://stackoverflow.com/q/52320232
has comment: http://stackoverflow.com/comment/91590293
has comment: http://stackoverflow.com/comment/91590346
has comment: http://stackoverflow.com/comment/91588551
downvote count: 0
has comment: http://stackoverflow.com/comment/91588087
has comment: http://stackoverflow.com/comment/91588489
score: 3
has comment: http://stackoverflow.com/comment/91588473
has comment: http://stackoverflow.com/comment/91588595
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/135143898
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52273643
has text: @user8395964 ok but according to the link "here" (https://wiki.archlinux.org/index.php/pacman#Querying_package_databases) I though it would be an or. I didn't practice with pamcan since a long time

http://stackoverflow.com/comment/91540756
has text: @DanielR. OMG, i found that falsh csv file and...it works!!!the graphic shows!!! thank you a lot, Daniel :O
comment on: http://stackoverflow.com/q/52295418
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52285933
type: Answer
upvote count: 2
score: 1
has body: help(max) should be your first port of call. Help on built-in function max in module builtins: max(...) max(iterable, *[, default=obj, key=func]) -&gt; value max(arg1, arg2, *args, *[, key=func]) -&gt; value With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the largest argument. max(f) means max with a single argument, [[1],[2],[3]], and the largest element of this is returned. max(*f) means max with three arguments, [1], [2], [3], and the largest of these is returned. Clearly these are equivalent in your example. But in general you should use the former to find the max of an iterable. It's the correct use case. The latter will break for e.g. f = [1]. For your specific problem, you need to flatten the list of lists into a single iterable and pass it to max. Here is a quick way: max(element for row in f for element in row)
downvote count: 1
answers question: http://stackoverflow.com/q/52285862

http://stackoverflow.com/q/52362716
has comment: http://stackoverflow.com/comment/91674292
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91675940
tagged with: python
answer count: 0
tagged with: matplotlib
has title: how to plot in different colors here according to x values?
type: Question
has comment: http://stackoverflow.com/comment/91670969
has body: I need different color for all different x values. My x axis is having categorical data while y axis is having integers. import pandas as pd import numpy as np import matplotlib.pyplot as plt df1 = pd.read_csv('Nissin_sy_1.csv') x = df1['ptno'] y = df1['d']//1000000000 colors = np.where(df1["ptno"]== 'U','r','o') colors[df1["ptno"]== '1234'] = 'g' colors[df1["ptno"]== 'X32133301000'] = 'brown' colors[df1["ptno"]== 'T7943000501'] = 'blue' colors[df1["ptno"]== 'Z1900139901'] = 'yellow' colors[df1["ptno"]== 'T7953000503'] = 'pink' colors[df1["ptno"]== 'L1104105004'] = 'blue' colors[df1["ptno"]== '-1'] = 'blue' colors[df1["ptno"]== 'Z1672502003'] = 'black' colors[df1["ptno"]== 'T7953000505'] = 'cyan' colors[df1["ptno"]== 'Y2323005900'] = 'white' colors[df1["ptno"]== 'Z12129940400'] = 'gray' fig,ax = plt.subplots() fig.tight_layout() plt.scatter(x,y, s = 35 , c =colors ) plt.title("Cycling Duration v. Part_Name") plt.xlabel("Part_Name") plt.xticks(x, rotation= 'vertical') plt.ylabel("Cycling Duration") plt.ylim(0,93209) plt.show() But I get the plot only with blue colors. How to get separate colors for separate x values. I am on python 2.7
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/91675966
tagged with: pandas

http://stackoverflow.com/a/52388002
type: AcceptedAnswer
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52387920
accepted answer of: http://stackoverflow.com/q/52387920
has body: Just feed the Counter a generator expression instead of a list: my_counts = Counter(sum(x) for x in combinations([1,2,3,4,5], 2)) or even shorter (but map only returns a generator in Python3): my_counts = Counter(map(sum, combinations([1,2,3,4,5], 2))) This will not build a list in memory first.

time
tags question: http://stackoverflow.com/q/52354963
tags question: http://stackoverflow.com/q/52412289
tags question: http://stackoverflow.com/q/52358493
tags question: http://stackoverflow.com/q/52333190
tag name: time
tags question: http://stackoverflow.com/q/52389786
tags question: http://stackoverflow.com/q/52342058
tags question: http://stackoverflow.com/q/52311836
type: Tag
tags question: http://stackoverflow.com/q/52389545
tags question: http://stackoverflow.com/q/52401886

http://stackoverflow.com/q/52394976
score: 0
accepted answer: http://stackoverflow.com/a/52395466
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/91735222
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52395466
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52400631
has title: Get span text that has no attribute using Beautiful Soup Python
has body: I'm scrapping a website, and I am having trouble getting the text for a span. I have seen that you can use below to get the text: 9 badges = soup.body.find('div', attrs={'class': 'badges'}) for span in badges.span.find_all('span', recursive=False): print span.attrs['title'] However, the span I am interested in getting the text of has no attributes. How can I get the text? Geolocation: 35.1391, -90.0536
tagged with: beautifulsoup
possible better answer: http://stackoverflow.com/a/52400631

http://stackoverflow.com/comment/91803006
comment on: http://stackoverflow.com/q/52429696
has text: Can't reproduce, using a csv with only your example row, it works (returns: `array([102. , 1.64])`)
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91681423
comment on: http://stackoverflow.com/q/52368495
score: 0
type: Comment
has text: `print('data for date %s to %s' % (x['dates'].min().strftime('%Y-%m-%d'), x['dates'].max().strftime('%Y-%m-%d')))`?
type: QuestionComment

http://stackoverflow.com/a/52416260
downvote count: 0
has comment: http://stackoverflow.com/comment/92438200
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52416118
score: 2
accepted answer of: http://stackoverflow.com/q/52416118
has body: Using replace function: with open("x.csv", "w") as fw: with open("x.dat", "r") as fr: for line in fr: new_line = line.replace("::", ",").replace("F", "2").replace("M", "1") fw.write(new_line) Using re module: import re rep = { "F": "2", "M": "1", "::": ",", } rep = dict((re.escape(k), v) for k, v in rep.iteritems()) pattern = re.compile("|".join(rep.keys())) with open("x.csv", "w") as fw: with open("x.dat", "r") as fr: for line in fr: new_line = pattern.sub(lambda m: rep[re.escape(m.group(0))], line) fw.write(new_line)
type: AcceptedAnswer

http://stackoverflow.com/q/52413123
tagged with: int
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52413267
tagged with: python-3.x
has body: Hello i have a verry simple problem. but i don't understand what cause the problem. I have the following python(3) script. i have numpy 1.13.1(an old one but my problem with dtype should work). according to this the dtype exist in ufunc since 1.6 import numpy as np M=1001 N = 2 ** np.ceil(np.log2(M)) N Out[252]: 1024.0 2 ** np.ceil(np.log2(M),dtype=int) Traceback (most recent call last): File "&lt;ipython-input-253-4b982a04c884&gt;", line 1, in &lt;module&gt; 2 ** np.ceil(np.log2(M),dtype=int) TypeError: No loop matching the specified signature and casting was found for ufunc ceil 2 ** np.ceil(np.log2(M),dtype=float) Out[254]: 1024.0 2 ** np.ceil(np.log2(M),dtype=np.float64) Out[256]: 1024.0 2 ** np.ceil(np.log2(M),dtype=np.float32) Out[257]: 1024.0 2 ** np.ceil(np.log2(M),dtype=np.int64) Traceback (most recent call last): File "&lt;ipython-input-258-9902fa43f3ac&gt;", line 1, in &lt;module&gt; 2 ** np.ceil(np.log2(M),dtype=np.int64) TypeError: No loop matching the specified signature and casting was found for ufunc ceil 2 ** np.ceil(np.log2(M),dtype=np.int32) Traceback (most recent call last): File "&lt;ipython-input-259-8a2f2834384f&gt;", line 1, in &lt;module&gt; 2 ** np.ceil(np.log2(M),dtype=np.int32) TypeError: No loop matching the specified signature and casting was found for ufunc ceil As you can see when i change the dtype to int, int32 or int64 it fails. Probably anything other than float fails. I would guess this shouldn't do that! I can add a small fix so that int(np.ceil(...)) the result is what i want. I want to know what cause this problem? Since i don't read anything in the numpy reference manual about any issue with this(numpy reference ceil). If Possible to do solve this problem that it works the way i started Thanks
tagged with: python
type: AnsweredQuestion
has title: TypeError numpy dtype int
upvote count: 2
score: 1
accepted answer: http://stackoverflow.com/a/52413267
downvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91769950
tagged with: ceil

http://stackoverflow.com/comment/127456931
has text: I get **TypeError: Field 'id' expected a number but got <myModel: strName>.**
comment on: http://stackoverflow.com/a/52315435
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52272555
has title: Python Selenium - Clicking through pages without next button
type: AnsweredQuestion
score: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/91493177
type: Question
accepted answer: http://stackoverflow.com/a/52275513
answer count: 1
downvote count: 0
has body: I would like to retrieve information from multiple webpages by clicking through them (see image 1 &amp; 2). The problem is a) there is not next button and b) even though the page link contains a number for counting through, it does not react to changing the numbering manually (i.e. does not load the next page). This makes the task tricky. Can anyone help on how to solve this? here is what the structure of the link looks like (no functioning page) https://sample.io/address/ID#pageSize=100 UPDATE: Got it to work with help of Robbie W.. The code I am using is: options.add_argument('windows-size = 1200 x 800') browser = webdriver.Chrome(chrome_options = options) browser.get('URL') page_soup_1 = soup(browser.page_source, "lxml") items_1 = page_soup_1.find_all("li", {"class": "page-item" }) LenofPage = pd.DataFrame() count = pd.DataFrame() for item in items_1 : string = str(item) Num = string[string.find('page-item')+23:string.find('\/li')-8] LenofPage = LenofPage.append({'LenofPage': Num}, ignore_index = True) Max_pagenum = LenofPage.max() Max_pagenum_1 = int(Max_pagenum) count = 1 #items_1 = page_soup.find_all("li", {"class": "page-item active" }).next_sibling while count &lt; Max_pagenum_1: link = browser.find_element_by_xpath('//li[contains(@class, "page-item") and contains(@class,"active")]/following-sibling::li/a') link.click() count = count + 1 time.sleep(3) print(count)
has comment: http://stackoverflow.com/comment/91492294
favorite count: 0
has answer: http://stackoverflow.com/a/52275513
tagged with: web-scraping
upvote count: 1
tagged with: python

http://stackoverflow.com/q/52360898
score: 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91666531
has title: How to solve the error message : 'NoneType' object has no attribute 'DataFrame'
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91666282
has body: I copy a section of code from the the official website of 'Bokeh': import numpy as np from bokeh.io import output_file, show from bokeh.plotting import figure from bokeh.transform import linear_cmap from bokeh.util.hex import hexbin n = 50000 x = np.random.standard_normal(n) y = np.random.standard_normal(n) bins = hexbin(x, y, 0.1) p = figure(tools="wheel_zoom,reset", match_aspect=True, background_fill_color='#440154') p.grid.visible = False p.hex_tile(q="q", r="r", size=0.1, line_color=None, source=bins, fill_color=linear_cmap('counts', 'Viridis256', 0, max(bins.counts))) output_file("hex_tile.html") show(p) When i ran this program , i got a error message about this: enter image description here &gt; Traceback (most recent call last): &gt; File "d:\vscode-text-files\hex_tile.py", line 12, in 'module' &gt; bins = hexbin(x, y, 0.1) &gt; File "D:\Program Files\Python37\lib\site-packages\bokeh\util\hex.py", &gt; line 198, in hexbin &gt; df = pd.DataFrame(dict(r=r, q=q)) &gt; AttributeError: 'NoneType' object has no attribute 'DataFrame' How can i solve this problem?
has comment: http://stackoverflow.com/comment/91687235
tagged with: bokeh
has comment: http://stackoverflow.com/comment/91666081
answer count: 0
downvote count: 0
type: UnansweredQuestion
favorite count: 0
type: Question
tagged with: pandas

http://stackoverflow.com/comment/91842162
has text: @IonicSolutions - I have successfully implemented the Fox Agent with a DQN Network! Challenge completed!! But... now I am still stuck on this... When it comes to an agent controlling 1 single solitary piece it is easy.... but when it comes an agent controlling multiple pieces I am still at a loss.... I am going to continue to tirelessly work on this until I get my answer. I have a hypothesis though thanks to my success with the fox that I am going to try out.
score: 0
comment on: http://stackoverflow.com/q/52417056
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52315229
tagged with: python
linked to: http://stackoverflow.com/q/46122846
type: AnsweredQuestion
downvote count: 1
accepted answer: http://stackoverflow.com/a/52315339
type: Question
upvote count: 0
has title: How to compare timestates in two formats (bigint and timestamp)?
tagged with: pyspark
answer count: 1
score: -1
has answer: http://stackoverflow.com/a/52315339
has comment: http://stackoverflow.com/comment/91578814
favorite count: 0
has body: I have two timestamp variables, t1 is bigint and t2 is timestamp. pyspark.sql.utils.AnalysisException: u"cannot resolve '(t2 >= 1536796800000L)' due to data type mismatch: differing types in '(t2 >= 1536796800000L) How can I compare such timestamps in different formats?
linked to: http://stackoverflow.com/q/48427185

http://stackoverflow.com/comment/91748692
type: Comment
has text: edited the code to call the function, but a new error has come up, it says that there is invalid syntax in 'elif '' not in (u, t, a):
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52401802

http://stackoverflow.com/comment/91563083
comment on: http://stackoverflow.com/q/52297627
has text: 'def sketch(img): if img is not None: print("image is present") print(len(img.shape))'
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91695867
type: Comment
has text: Correct, or at least that's the intent. :-)
comment on: http://stackoverflow.com/a/52375474
type: AnswerComment
score: 1

http://stackoverflow.com/comment/91518264
has text: @OkanAydogdu I changed it to the whole program that I can run on my machine. I stripped out some of your logic so you'll have to add some of that back in. I hope it helps
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52283783

http://stackoverflow.com/comment/91596210
type: Comment
comment on: http://stackoverflow.com/a/52322124
has text: Thank you so much sir. I couldn't possibly imagine a better answer than this. It seems to me that query is the best way for the specific purpose I presented in the question as it has the shortest/cleanest code. And somehow on my home laptop `filter` is working. If I may ask one more question which I just thought of as I'm still learning what pandas can do: how to filter/query columns based on certain string that the column names contain? Like for instance, I want to see all the column with names of "...date". Thanks again
type: AnswerComment
score: 0

http://stackoverflow.com/a/52323342
has comment: http://stackoverflow.com/comment/91596180
has comment: http://stackoverflow.com/comment/91594068
has body: No need to use if statements at all return math.sqrt(num) % 2 == 0 or (math.sqrt(num)+1) % 2 == 0
upvote count: 5
has comment: http://stackoverflow.com/comment/91596903
answers question: http://stackoverflow.com/q/52323299
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/136798317
type: Answer

http://stackoverflow.com/comment/91839354
comment on: http://stackoverflow.com/q/52418205
score: 0
type: Comment
type: QuestionComment
has text: @Ulrich Eckhardt Thanks for pointing it out, but doesn't writing back to the first file serialize it back?

http://stackoverflow.com/a/52333902
type: AcceptedAnswer
score: 0
type: Answer
has body: I think you can add new column with shift to have an easy access in apply method to compare with previous group. And use just only first value. Data: data = pd.DataFrame(columns=['date', 'volume'], data = [['2018-04-08 15:52:26.110', 43], ['2018-04-08 15:53:26.110', 17], ['2018-04-08 15:54:26.110', 10], ['2018-04-09 12:40:35.877', 15], ['2018-04-09 12:41:35.877', 16]]) data.date = pd.to_datetime(data.date) data.date = data.date.dt.day Code: data['PercentVolume'] = data.volume.shift(1) def func(df): m = df.PercentVolume.values[0] df.PercentVolume = (df.volume - m) / m * 100 return df data = data.groupby('day').apply(func) Output: date volume day PercentVolume 0 2018-04-08 15:52:26.110 43 8 NaN 1 2018-04-08 15:53:26.110 17 8 NaN 2 2018-04-08 15:54:26.110 10 8 NaN 3 2018-04-09 12:40:35.877 15 9 50.0 4 2018-04-09 12:41:35.877 16 9 60.0 Is it what you want? I hope it helps.
answers question: http://stackoverflow.com/q/52332713
has comment: http://stackoverflow.com/comment/91614854
accepted answer of: http://stackoverflow.com/q/52332713
has comment: http://stackoverflow.com/comment/91615374
has comment: http://stackoverflow.com/comment/91614981

http://stackoverflow.com/comment/91507748
type: Comment
has text: What's With All The Caps?
score: 0
comment on: http://stackoverflow.com/q/52279662
type: QuestionComment

http://stackoverflow.com/comment/91682356
comment on: http://stackoverflow.com/a/52368668
type: Comment
type: AnswerComment
has text: This is true for NP.ARRAY. Here we are talking about NP.MATRIX for which * performs MATRIX MULTIPLICATION.
score: 0

http://stackoverflow.com/a/52299801
score: 1
accepted answer of: http://stackoverflow.com/q/52299690
upvote count: 1
answers question: http://stackoverflow.com/q/52299690
type: AcceptedAnswer
downvote count: 0
has body: As i was saying on the comments, your short url with --data-urlencode which is correct for curl is not valid for python requests, please try this, payload = {'q': 'SHOW DATABASES'} shorturl = 'http://xx.xxx.xx.xxx:8086/query' r = requests.get(shorturl, params=payload) print (r.text) you can learn more on request here http://docs.python-requests.org/en/master/user/quickstart/
has comment: http://stackoverflow.com/comment/91547267
type: Answer

http://stackoverflow.com/q/52378942
tagged with: loss-function
score: -1
has title: binary_corssentropy loss is negative even I normalize the inputs
upvote count: 0
answer count: 1
has body: I try to use U-net to do the semantic segmentation problem. The mask image is binary. But when training, I find out that my loss is negative. Loss here I use binary_crossentropy. Here is my code: X_train = X_train /255 y_train = y_train /255 X_val = X_val/255 y_val = y_val/255 All of them have type np.float32 Then I use the imageDataGenerator to augment the image, the code is below: def image_augmentation(X_train,y_train): # Set hyper parameters for the model. data_gen_args = dict(featurewise_center=True, featurewise_std_normalization=True, rotation_range=90., width_shift_range=0.1, height_shift_range=0.1, zoom_range=0.2, horizontal_flip=True, vertical_flip=True) image_datagen = ImageDataGenerator(**data_gen_args) mask_datagen = ImageDataGenerator(**data_gen_args) seed = 42 image_datagen.fit(X_train, augment=True, seed=seed) mask_datagen.fit(y_train, augment=True, seed=seed) image_generator = image_datagen.flow( X_train,batch_size=8, seed=seed) mask_generator = mask_datagen.flow( y_train, batch_size=8, seed=seed) while True: yield(image_generator.next(),mask_generator.next()) train_generator = image_augmentation(X_train,y_train) pat_init = 50 pat = pat_init learning_rate = 1e-4 ##change the model weight you want file_path = "./model_v1/improvement-{epoch:02d}-{val_my_iou_metric:.5f}.hdf5" checkpoint = ModelCheckpoint(file_path,monitor = 'val_my_iou_metric',verbose=1,save_best_only=True,mode='max') reduce_lr = ReduceLROnPlateau(monitor='val_loss', mode = 'auto',factor=0.5, patience=5, min_lr=1e-9, verbose=1) model.compile(loss='binary_crossentropy', optimizer=Adam(lr=learning_rate), metrics=[my_iou_metric]) # Use the image data Augment below to achieve better result model.fit_generator( train_generator,steps_per_epoch=2000,epochs=300, validation_data=(X_val, y_val), verbose=1, callbacks=[checkpoint,reduce_lr] ) The last layer of My net is defined as follow: output = Conv2D(1,activation='sigmoid', kernel_size=(1,1), padding='same', data_format='channels_last')(x) I am…
tagged with: keras
favorite count: 0
tagged with: semantic-segmentation
tagged with: python
type: UnansweredQuestion
tagged with: machine-learning
has answer: http://stackoverflow.com/a/54282859
downvote count: 1
type: Question

http://stackoverflow.com/q/52283938
downvote count: 0
accepted answer: http://stackoverflow.com/a/52283974
has title: Use regex to filter pandas rows with ~ at beginning AND at end of string
type: Question
score: 3
upvote count: 3
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: python
tagged with: regex
has body: I'm trying to use regular expressions in pandas to filter out rows where there's a ~ at the beginning of the line AND at the end of the line for a given column. For example, take the following pandas Dataframe: import pandas as pd df = pd.DataFrame({'line': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'Unit': ['LF', 'LS~', '~~SF', 'CY', '~SF~', 'PC', '~~', '~LF', '~PC~']}) Here's what I want for output: df[df.Unit.str.contains(MY_EXPRESSION, regex=True)] line Unit 0 1 LF 1 2 LS~ 2 3 ~~SF 3 4 CY 5 6 PC 7 8 ~LF What I've tried so far: MY_EXPRESSION = '^[^~].*[^~]$' This filters anything with a ~ at the beginning OR end of the string. I want to only filter out rows with a ~ at the beginning AND end of the string. MY_EXPRESSION = '^([^~])(.*)([^~])$' This also filters out rows with a ~ at the beginning OR end of a string. Again, I want to only filter out rows with a ~ at the beginning AND end of the string. What is the regular expression that I need (i.e., MY_EXPRESSION in the example) in order to filter the Dataframe the desired way? I'm using pandas v.0.23.4.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52283974

http://stackoverflow.com/comment/91563214
type: AnswerComment
has text: @JulioGomez : read excel doesnot have the feature of reading sheets, if you see my code, I have used the `ExcelFile` feature to read the file which can give you `f.sheet_names`
type: Comment
comment on: http://stackoverflow.com/a/52287447
score: 0

http://stackoverflow.com/a/52311810
type: Answer
downvote count: 0
score: 1
has body: You could make the x axis wider using aspectratio plot_ly(x = kd$x, y = kd$y, z = kd$z) %&gt;% add_surface() %&gt;% layout(scene = list(aspectmode="manual",aspectratio = list( x = 2, y = .5, z = 1)))
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52304003
answers question: http://stackoverflow.com/q/52304003

http://stackoverflow.com/a/55631270
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52298917
upvote count: 2
has body: Try setting 'data_only' parameter to True while loading workbook. wb = load_workbook("example.xlsx", data_only=True) print(sheet['B1'].value) This will print the result after computing formula at B1 cell.
score: 1

http://stackoverflow.com/comment/91762703
type: QuestionComment
has text: @MattCremeens Okay cheers, I'm finding it pretty tricky using this, but if it's the only way I'm sure I'll figure it out
score: 0
comment on: http://stackoverflow.com/q/52408701
type: Comment

http://stackoverflow.com/q/52337953
favorite count: 0
has comment: http://stackoverflow.com/comment/91623271
upvote count: 2
has comment: http://stackoverflow.com/comment/91623229
tagged with: python
tagged with: indexing
score: 2
type: AnsweredQuestion
has title: Indexing with ndarray in the same way as using tuples
has comment: http://stackoverflow.com/comment/91623260
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/52334909
accepted answer: http://stackoverflow.com/a/52338066
has comment: http://stackoverflow.com/comment/91623363
has comment: http://stackoverflow.com/comment/91623283
has body: I'd like to index my 2d-array using a 1d-array of size two in the same way a tuple or basic indexing would be used. I have the indices as np.ndarrays for convenience when it comes to manipulations, but currently I'm converting them back and forth to tuples. a = np.zeros((5, 5)) ix = np.array([3, 2]) &gt;&gt;&gt; a[3, 2] 0.0 &gt;&gt;&gt; a[(3, 2)] 0.0 &gt;&gt;&gt; a[ix] array([[0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]]) I've tried it with reshaping the array a bunch of ways, e.g. shapes (2, 1) and (1, 2), but no luck. Also couldn't find an entry from the documentation. Is there a way?
has answer: http://stackoverflow.com/a/52338066
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/91617100
comment on: http://stackoverflow.com/q/52333812
type: Comment
type: QuestionComment
has text: The only way to debug is: 1) check your HTML source to see if the values (not the visible labels) for each option are correctly set and whether the ` ` field is correctly named. 2) set a breakpoint or print in your view the `request.POST` data to check what is being submitted.
score: 0

http://stackoverflow.com/comment/91763531
has text: Sorry, just to clarify: although increasing the interval has improved the tracking of time problem it is far from a permanent solution since the animation is so poor. Should I open a new question trying to work out why it runs slower on my setup, and how to fix that, rather than continuing the discussion in comments?
comment on: http://stackoverflow.com/a/52405013
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91681275
type: Comment
comment on: http://stackoverflow.com/a/52364378
has text: @tmccaffrey: Yes, very much so. You should wrap both `del()`s in `try:`/`except KeyError:`.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/107100929
type: QuestionComment
comment on: http://stackoverflow.com/q/52354998
score: 0
has text: Did you try checking it with latest versions of TF Hub and latest versions of USE and check if the issue still persists. Also, if possible, please use Tensorflow Version 2.0. Thanks!
type: Comment

http://stackoverflow.com/comment/91611440
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52331667
has text: @PM2Ring, even better indeed.

http://stackoverflow.com/a/52356287
answers question: http://stackoverflow.com/q/52356091
type: Answer
score: 0
has body: In python, when using for a in b: 'a' is not actually a number which can be used as an index, but is instead a pointer to an actual element in list 'b'. Put another way, if I had the following list b = ["Bob", "Jim", "Jane"] Then on the first iteration 'a' would be equal to "Bob", and not 0. When you want to generate index numbers instead of pointers to elements, you can use: for a in range(0, len(b)): instead. Using this, your code should then work. e.g. for element in range(0, len(l)): listSmaller = l[:element] + l[element+1:] for perm in permutations(listSmaller, k-1): result.append([perm] + element) return result

http://stackoverflow.com/comment/91644198
has text: It adds spaces between each character
comment on: http://stackoverflow.com/a/52349410
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52496447
answers question: http://stackoverflow.com/q/52401032
downvote count: 0
has body: The problem was the sessions. Open multiple sessions during the training force the system to instances a new GPU. A solution is to move the with tf.Session() as session before the while True.
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/91604261
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52328581
score: 0
has text: Andersson that worked! Could you make it an answer so I can accept it

http://stackoverflow.com/q/52376475
linked to: http://stackoverflow.com/q/37058016
has title: Pyspark timestamp difference based on column values
has comment: http://stackoverflow.com/comment/91698078
tagged with: python
accepted answer: http://stackoverflow.com/a/52381546
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52381546
type: Question
tagged with: pyspark
answer count: 1
has body: I have a pyspark dataframe with four timestamp columns (clock_in, clock_out, sign_in, and sign_out). I need a third column (duration) that is a difference between two columns, but which two I'm taking the difference of depends on the values of the columns themselves, according to the following rules: If clock_in &gt; clock_out, then duration = clock_in - clock_out Else, if sign_in &gt; clock_out, then duration = sign_out - clock_out Else, if clock_in &gt; sign_in, then duration = clock_in - clock_out Otherwise, duration = 0 I've tried defining a UDF and applying it as follows: from pyspark.sql import * def calc_dur(clock_in, clock_out, sign_in, sign_out): if clock_in &gt; clock_out: return clock_in - clock_out elif sign_out &gt; clock_out: return sign_out - clock_out elif sign_in &lt; clock_in: return clock_in - sign_in else: return 0 dur_udf = udf(calc_dur) df2 = df.withColumn("duration", dur_udf(df.clock_in, df.clock_out, df.sign_in, df.sign_out)) However, this fills my duration column with Timedeltas (e.g., Timedelta: 0 days, 1740 seconds, 0 microseconds (total: 1740 seconds)), and when I try to filter to only rows with non-zero values in the duration column, it returns zero rows. What is the correct way of doing this?
score: 0
tagged with: apache-spark

http://stackoverflow.com/comment/91813869
type: QuestionComment
comment on: http://stackoverflow.com/q/52424126
has text: if it is not so that item of the row must change the color, since according to your numbering the name has the position 0, then comes the total that would be the position 1 and finally checked quantities that is 2, but you compare the 3 with the 5 `row[2] == row[4]` (remember that the position starts from 0)
score: 0
type: Comment

http://stackoverflow.com/q/52284749
has answer: http://stackoverflow.com/a/52570371
has body: There's multiple ways, and not clear tutorials or anything online on how to run a fundamentally basic python script with apache. mod_python? cgi? wsgi? Does something need to be installed with python? It's really confusing. I've been working on it for hours.
tagged with: web
score: 1
favorite count: 0
type: Question
tagged with: python
answer count: 1
has title: How do I use Apache to just basically fundamentally run a python script?
upvote count: 1
tagged with: apache
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/116831427
comment on: http://stackoverflow.com/a/61587091
type: Comment
has text: Would this work on an excel file with images, formulas and formatting?
score: 2
type: AnswerComment

http://stackoverflow.com/q/52295689
has comment: http://stackoverflow.com/comment/95915497
type: Question
has answer: http://stackoverflow.com/a/52295761
answer count: 2
has comment: http://stackoverflow.com/comment/91538988
has title: Integral variable in function not working
score: 0
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52300287
type: UnansweredQuestion
has body: I am trying to make first function, opt1(), make health go down by 50 points however for some reason it doesn’t work. The code works when not in a function. The line that doesn’t work specifically: health = int(health) - 50 import random health = "100" p = "1" def opt1(): print("Du förlorade striden") health = int(health) - 50 print(health) def opt2(): print("hej2") def opt3(): print("hej3") q = [opt1, opt2, opt3] ind = random.randint(0,len(q)-1) print("you have ", p, " potions") print("Your health is ", health,) while True: print("Commands: Add, drink, sleep, fight, quest") a = input("Enter a command: ") if a == "add": health = int(health) p = int(p) + 1 print("you have ", p, " potions") print("Your health is ", health,) if a == "fight": q[ind]()
has comment: http://stackoverflow.com/comment/91539706

http://stackoverflow.com/a/52310012
type: Answer
answers question: http://stackoverflow.com/q/52300861
upvote count: 2
has body: As mentioned in the comments, this behavior has been fixed in later versions of Pandas. From going over the code, it seems to have been fixed for version 0.23 in this commit. In a bit more detail - the code for the function that calculates the delta, _binary_op_method_timedeltalike, contains the condition: elif other is NaT: # (N)ot-(A)-(T)ime, the time equivalent of NaN return NaT But None is not NaT, and that's the reason for the bug: &gt;&gt;&gt; None is NaT False In the later version, a second condition has been added, first converting other to a Timedelta object, and then testing the condition again, so effectively testing: &gt;&gt;&gt; Timedelta(None) is NaT True So now NaT is returned in the case of None + Timedelta.
score: 2
downvote count: 0

http://stackoverflow.com/q/52322905
downvote count: 0
favorite count: 0
has title: Use airflow hive operator and output to a text file
type: UnansweredQuestion
tagged with: python
tagged with: airflow-scheduler
has answer: http://stackoverflow.com/a/52330173
has body: Hi I want to execute hive query using airflow hive operator and output the result to a file. I don't want to use INSERT OVERWRITE here. hive_ex = HiveOperator( task_id='hive-ex', hql='/sql/hive-ex.sql', hiveconfs={ 'DAY': '{{ ds }}', 'YESTERDAY': '{{ yesterday_ds }}', 'OUTPUT': '{{ file_path }}'+'csv', }, dag=dag ) What is the best way to do this? I know how to do this using bash operator,but want to know if we can use hive operator hive_ex = BashOperator( task_id='hive-ex', bash_command='hive -f hive.sql -DAY={{ ds }} &gt;&gt; {{ file_path }} /file_{{ds}}.json', dag=dag )
has answer: http://stackoverflow.com/a/52328509
has comment: http://stackoverflow.com/comment/111246112
type: Question
score: 5
tagged with: airflow
upvote count: 5
answer count: 2

http://stackoverflow.com/a/52402175
has body: Done. Simple function can help to achieve this: @pandas_udf(returnType=StringType()) def convert_id(id): converted = id.map(lambda x : str(bs.a85encode(bytearray.fromhex(str(x).replace("-", ""))))[2:-1]) return converted
answers question: http://stackoverflow.com/q/52401542
type: Answer
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/91748287
has comment: http://stackoverflow.com/comment/91749607
upvote count: 3
has comment: http://stackoverflow.com/comment/91748698
has comment: http://stackoverflow.com/comment/91753680

http://stackoverflow.com/a/52329029
has comment: http://stackoverflow.com/comment/91605966
has comment: http://stackoverflow.com/comment/91606265
has comment: http://stackoverflow.com/comment/91605894
upvote count: 1
answers question: http://stackoverflow.com/q/52328800
has comment: http://stackoverflow.com/comment/91605265
has comment: http://stackoverflow.com/comment/91605159
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/91606380
has comment: http://stackoverflow.com/comment/91605105
score: 1
has body: You can merge them all first, then write them to a csv file: import pprint scores = { 'Id_1': [ ('100001124156327', 0.0), ('100003643614411',0.0)], 'Id_2': [ ('100000435456546',5.7), ('100000234354556',3.5) ] } post_dict = { 'Id_1':[ ('+',100004536) ], 'Id_2' :[ ('-',100035430) ] } comment_dict = { 'Id_1':[ ('+',1023434234) ], 'Id_2':[ ('-',10343534534), ('*',1097963644) ] } merged = { key: { "Score_Ids": value, "Post_Ids": post_dict[key], "Comment_Ids": comment_dict[key] } for key, value in scores.iteritems() } pp = pprint.PrettyPrinter(depth=6) pp.pprint(merged) For reference: https://repl.it/repls/SqueakySlateblueDictionaries

http://stackoverflow.com/a/52320470
score: 1
answers question: http://stackoverflow.com/q/52317507
downvote count: 0
has body: The best way that I found is something like this: set1 = set(['A', 'B', 'C', 'D']) set2 = set(['B', 'C', 'D', 'E']) v = venn2([set1, set2], ('Set1', 'Set2')) v.get_label_by_id('10').set_text('\n A') v.get_label_by_id('01').set_text('\n E') v.get_label_by_id('11').set_text('\n \nB \nC \nD') plt.show() Just create functions that generate the texts from set1 &amp; set2 for set_text on the fly and it's done.
type: Answer
upvote count: 1

http://stackoverflow.com/comment/91588834
type: Comment
type: QuestionComment
has text: Welcome to StackOverflow! It will be very helpful if you provide some sample of your data, your resulting plot and what plots you're trying to get.
comment on: http://stackoverflow.com/q/52320357
score: 0

http://stackoverflow.com/a/52285684
has body: I would probably tackle this with pip. I would do the following: pip install virtualenv Then next in your directory you choose to set up your virtual environment. Then nexxt name your virtual enviornment: virtualenv pymote_env Then after we do that we can call the virtual enviornment as so: pymote_env\Scripts\activate(pymote_env) Then when the virtual environment call the pip command to verify it works pip Then after install django: pip install django Hopefully this is what your looking for. H
has comment: http://stackoverflow.com/comment/91531875
accepted answer of: http://stackoverflow.com/q/52285515
has comment: http://stackoverflow.com/comment/91526173
has comment: http://stackoverflow.com/comment/91519876
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91533624
answers question: http://stackoverflow.com/q/52285515
has comment: http://stackoverflow.com/comment/91519850
type: Answer

tensorflow
tags question: http://stackoverflow.com/q/52347906
tags question: http://stackoverflow.com/q/52403414
tags question: http://stackoverflow.com/q/52392502
tags question: http://stackoverflow.com/q/52271644
tags question: http://stackoverflow.com/q/52399161
tags question: http://stackoverflow.com/q/52310022
tags question: http://stackoverflow.com/q/52317262
tags question: http://stackoverflow.com/q/52363620
tags question: http://stackoverflow.com/q/52299108
tags question: http://stackoverflow.com/q/52327107
tags question: http://stackoverflow.com/q/52377462
tags question: http://stackoverflow.com/q/52394840
tags question: http://stackoverflow.com/q/52289594
tags question: http://stackoverflow.com/q/52340645
tags question: http://stackoverflow.com/q/52369174
tags question: http://stackoverflow.com/q/52353575
tags question: http://stackoverflow.com/q/52399923
tags question: http://stackoverflow.com/q/52271413
tags question: http://stackoverflow.com/q/52426739
tags question: http://stackoverflow.com/q/52282896
tags question: http://stackoverflow.com/q/52362869
tags question: http://stackoverflow.com/q/52375305
tags question: http://stackoverflow.com/q/52317452
tags question: http://stackoverflow.com/q/52325149
tags question: http://stackoverflow.com/q/52371714
tags question: http://stackoverflow.com/q/52400391
tags question: http://stackoverflow.com/q/52392407
tags question: http://stackoverflow.com/q/52374294
tags question: http://stackoverflow.com/q/52350348
tags question: http://stackoverflow.com/q/52346399
tags question: http://stackoverflow.com/q/52365491
tags question: http://stackoverflow.com/q/52284951
tags question: http://stackoverflow.com/q/52397450
tags question: http://stackoverflow.com/q/52357542
tags question: http://stackoverflow.com/q/52364673
tags question: http://stackoverflow.com/q/52402017
tags question: http://stackoverflow.com/q/52299946
tags question: http://stackoverflow.com/q/52411772
tags question: http://stackoverflow.com/q/52408404
tags question: http://stackoverflow.com/q/52299913
tags question: http://stackoverflow.com/q/52424348
tags question: http://stackoverflow.com/q/52371049
tags question: http://stackoverflow.com/q/52370630
tags question: http://stackoverflow.com/q/52306461
tags question: http://stackoverflow.com/q/52280897
tags question: http://stackoverflow.com/q/52328155
tags question: http://stackoverflow.com/q/52418967
tags question: http://stackoverflow.com/q/52273118
tags question: http://stackoverflow.com/q/52362797
tags question: http://stackoverflow.com/q/52320409
tags question: http://stackoverflow.com/q/52416559
tags question: http://stackoverflow.com/q/52288300
tags question: http://stackoverflow.com/q/52284979
tags question: http://stackoverflow.com/q/52287254
tags question: http://stackoverflow.com/q/52306842
tags question: http://stackoverflow.com/q/52355321
tags question: http://stackoverflow.com/q/52323297
tags question: http://stackoverflow.com/q/52424172
tags question: http://stackoverflow.com/q/52405276
tags question: http://stackoverflow.com/q/52285501
tags question: http://stackoverflow.com/q/52422476
tag name: tensorflow
tags question: http://stackoverflow.com/q/52365190
tags question: http://stackoverflow.com/q/52423501
tags question: http://stackoverflow.com/q/52354998
tags question: http://stackoverflow.com/q/52335065
tags question: http://stackoverflow.com/q/52324322
tags question: http://stackoverflow.com/q/52340728
tags question: http://stackoverflow.com/q/52397907
tags question: http://stackoverflow.com/q/52381912
tags question: http://stackoverflow.com/q/52425985
tags question: http://stackoverflow.com/q/52314785
tags question: http://stackoverflow.com/q/52293578
tags question: http://stackoverflow.com/q/52337439
tags question: http://stackoverflow.com/q/52422427
tags question: http://stackoverflow.com/q/52306759
tags question: http://stackoverflow.com/q/52326469
tags question: http://stackoverflow.com/q/52373204
tags question: http://stackoverflow.com/q/52377930
tags question: http://stackoverflow.com/q/52394504

http://stackoverflow.com/q/52281683
score: 1
accepted answer: http://stackoverflow.com/a/52281741
type: Question
possible better answer: http://stackoverflow.com/a/52282452
has comment: http://stackoverflow.com/comment/91511448
has answer: http://stackoverflow.com/a/52281741
tagged with: dataframe
has title: How to iterate over dates in a dataframe?
tagged with: pandas
downvote count: 0
answer count: 4
favorite count: 0
has body: I've got a dataframe that has a column of dates that are formatted like this: "1/1/2016" I would like to create a for-loop that starts from that date and goes to "1/2/2016", "1/3/2016", and so on. I start with this Python code: df = pd.read_csv('myfile.csv') df['dates'] = pd.to_datetime(df['dates']) Which turns the date format to this: '01-01-2016' Next: start_date = '01-01-2016' Finally, the for-loop: for j in range (1,30) start_date + j... But you can't add an integer to that date format, of course. What should I do in the for-loop to just go to the next day?
has answer: http://stackoverflow.com/a/52282452
has answer: http://stackoverflow.com/a/52281768
tagged with: datetime
has answer: http://stackoverflow.com/a/52281771
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/6871016
type: AnsweredQuestion

http://stackoverflow.com/q/52370470
type: Question
tagged with: python
tagged with: rabbitmq
score: 0
has comment: http://stackoverflow.com/comment/91778436
tagged with: ssl
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91703576
has comment: http://stackoverflow.com/comment/91721462
answer count: 0
has comment: http://stackoverflow.com/comment/91691111
has title: Python on Windows: ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed
tagged with: python-3.x
has body: Someone setup rabbitmqadmin on Windows and now when we run the job which shall create the queues, the script fails due do an ssl problem 11:27:12 Traceback (most recent call last): 11:27:12 File "D:\jenkins\home\workspace\RabbitMQ-BUILD\target\classes\rabbitmqadmin", line 535, in http 11:27:12 conn.request(method, path, body, headers) 11:27:12 File "http\client.py", line 1239, in request 11:27:12 File "http\client.py", line 1285, in _send_request 11:27:12 File "http\client.py", line 1234, in endheaders 11:27:12 File "http\client.py", line 1026, in _send_output 11:27:12 File "http\client.py", line 964, in send 11:27:12 File "http\client.py", line 1400, in connect 11:27:12 File "ssl.py", line 401, in wrap_socket 11:27:12 File "ssl.py", line 808, in __init__ 11:27:12 File "ssl.py", line 1061, in do_handshake 11:27:12 File "ssl.py", line 683, in do_handshake 11:27:12 ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:748) 11:27:12 11:27:12 During handling of the above exception, another exception occurred: 11:27:12 11:27:12 Traceback (most recent call last): 11:27:12 File "D:\jenkins\home\workspace\RabbitMQ-BUILD\target\classes\rabbitmqadmin", line 1066, in &lt;module&gt; 11:27:12 main() 11:27:12 File "D:\jenkins\home\workspace\RabbitMQ-BUILD\target\classes\rabbitmqadmin", line 447, in main 11:27:12 method() 11:27:12 File "D:\jenkins\home\workspace\RabbitMQ-BUILD\target\classes\rabbitmqadmin", line 638, in invoke_list 11:27:12 format_list(self.get(uri), cols, obj_info, self.options) 11:27:12 File "D:\jenkins\home\workspace\RabbitMQ-BUILD\target\classes\rabbitmqadmin", line 477, in get 11:27:12 return self.http("GET", "%s/api%s" % (self.options.path_prefix, path), "") 11:27:12 File "D:\jenkins\home\workspace\RabbitMQ-BUILD\target\classes\rabbitmqadmin", line 537, in http 11:27:12 traceback.print_exc(e) 11:27:12 File "traceback.py", line 159, in print_exc 11:27:12 File "traceback.py", line 100, in print_exception 11:27:12 File "traceback.py",…

http://stackoverflow.com/comment/91790072
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52421166
has text: You probably mean one after another : no At the same time and one : yes I want that

http://stackoverflow.com/q/52372624
score: -2
has answer: http://stackoverflow.com/a/65353307
downvote count: 2
answer count: 3
has body: I am having this error when I try to run a Python file. I tried opening a new terminal and importing cv2 worked there in Python but doesn't work in my OpenCV virtual environment. I don't even understand how virtualenvs work but I have to find a solution for this. &gt; (cv) pi@raspberrypi:~/Camerafeed $ python run.py Traceback (most &gt; recent call last): File "run.py", line 2, in &lt;module&gt; &gt; from camerafeed import CameraFeed File "/home/pi/Camerafeed/camerafeed/__init__.py", line 5, in &lt;module&gt; &gt; import cv2 ImportError: No module named 'cv2'
favorite count: 0
has title: No module named cv2 error in Python Raspberry
tagged with: python
has answer: http://stackoverflow.com/a/52372694
accepted answer: http://stackoverflow.com/a/52372694
has answer: http://stackoverflow.com/a/52372702
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/102144706
upvote count: 0
possible better answer: http://stackoverflow.com/a/65353307
type: Question
tagged with: opencv
tagged with: raspberry-pi

http://stackoverflow.com/q/52363163
has comment: http://stackoverflow.com/comment/91670612
has comment: http://stackoverflow.com/comment/91672973
linked to: http://stackoverflow.com/q/5300938
has comment: http://stackoverflow.com/comment/91724855
has comment: http://stackoverflow.com/comment/91672659
upvote count: 0
answer count: 1
has body: I've a .json file which has annotations (in terms of circles and polygons) of objects I want to train my neural network with. The problem is however the traning code only accepts polygons from the .json file, thus giving an error since mine has circles. Does anyone know how to convert circles into polygons? I've already tried some solutions (like below) which did not work: import json from pprint import pprint with open('via_region_data(val).json') as f: data = json.load(f) for attr, val in data.items(): for attr2, val2 in val.items(): if attr2 == 'regions': for attr3, val3 in val2.items(): if val3['shape_attributes']['name'] == 'circle': cx = val3['shape_attributes']['cx'] cy = val3['shape_attributes']['cy'] r = val3['shape_attributes']['r'] all_points_x = [cx, cx - 1.5 * r, cx, cx + 1.5 * r, cx] all_points_y = [cy - 1.5 * r, cy, cy + 1.5 * r, cy, cy - 1.5 * r] val3['shape_attributes']['cx'] = all_points_x val3['shape_attributes']['cy'] = all_points_y val3['shape_attributes']['all_points_x'] = val3['shape_attributes'].pop('cx') val3['shape_attributes']['all_points_y'] = val3['shape_attributes'].pop('cy') val3['shape_attributes']['name'] = 'polygon' pprint(data) with open('via_region_data-val.json', 'w') as f: json.dump(data, f) throwing: Traceback (most recent call last): File "polygon_fixer.py", line 10, in &lt;module&gt; for attr3, val3 in val2.items(): AttributeError: 'list' object has no attribute 'items' Any thoughts? P.S: Well apparently some people didn't understand that it is a .JSON file which I am trying to operate with. So here it is.
favorite count: 0
tagged with: geometry
accepted answer: http://stackoverflow.com/a/52406569
has title: Converting circles into polygons in a .json file
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/91670611
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
downvote count: 2
has comment: http://stackoverflow.com/comment/91670654
type: Question
has comment: http://stackoverflow.com/comment/91675397
has answer: http://stackoverflow.com/a/52406569

http://stackoverflow.com/comment/91625237
has text: Seems like a missing parenthesis issue but I cannot see it. I just copied this query into MS Access and it saved without issue. Access does NOT save queries with syntax errors. Did you make any changes from this post anywhere in Python? I am seeing *Pa_RaM000*. Is that a parameter?
type: AnswerComment
comment on: http://stackoverflow.com/a/52338372
score: 0
type: Comment

http://stackoverflow.com/a/59954494
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52423018
has body: I think what you're looking to do is detach the Process you're creating - in that case I would recommend trying the double-fork approach from this answer. https://stackoverflow.com/a/49123627/6410635

http://stackoverflow.com/a/52346731
upvote count: 1
has comment: http://stackoverflow.com/comment/91639149
downvote count: 0
has comment: http://stackoverflow.com/comment/91639123
type: Answer
has body: A function is able to "return" a value back to the scope that called it. If this variable is not stored or passed into another function, it is lost. For instance: def f(x): return x + 1 f(5) will not print anything since nothing is done with the 6 returned from the f(5) call. To output the value returned from a function, we can pass it to the print() function: print(f(5)) or in your case: print(filter_list(original_list, 3))
answers question: http://stackoverflow.com/q/52346711
score: 1

wikipedia-api
tag name: wikipedia-api
tags question: http://stackoverflow.com/q/52283962
type: Tag

http://stackoverflow.com/q/52287216
tagged with: python
answer count: 0
has body: So I am having trouble with my script below, code runs and compiles, but there are some issues. I am not sure if my issue is a calculation issue or if its formatting issue. I am not even sure if I am on the right track, I feel like I am but I am new to python, I am all ears to any advice or input would be awesome! Stuck on the following: 1) The K_means class does not assign centroids to clusters at all 2) The K_means class does not perform any recalculations to re-center the centroids Below is my code, I just pasted my functions since i think that is where the problem lies: class K_means(): def __init__(self,k, lines, **kwargs): self.k = k self.lines = lines self.index = [] self.distance = [] self.elements = [] self.points = [] for keys, values in kwargs.items(): setattr(self, keys, values) def determineDistance(self, centroids, new_dict): for keys, points in new_dict.items(): self.points.append(points) for elements in range(len(centroids)): self.elements.append(elements) distance = abs(points - centroids[elements]) self.distance.append(distance) def assign_to_clusters(self, lines, clusters, centroids, point_assignments, distance, new_dict): for index, points in new_dict.items(): closest_index = (self.k + 1) for elements in range(len(centroids)): distance = self.determineDistance(centroids, new_dict) if distance &lt; closest_index: closest_index = distance index = elements clusters[index].append(points) point_assignments[index] = closest_index return point_assignments def update_location(self, clusters, centroids): for keys, values in clusters.items(): new_centroids ={keys:sum(values)/float(len(values))} centroids.update(new_centroids) return centroids
type: UnansweredQuestion
type: Question
has title: K-Means Clustering issue regarding Centroids
has comment: http://stackoverflow.com/comment/91522229
tagged with: k-means
score: 0
has comment: http://stackoverflow.com/comment/91522468

http://stackoverflow.com/comment/91973194
comment on: http://stackoverflow.com/a/52458365
type: Comment
score: 0
type: AnswerComment
has text: assume your script or module being tested is `server.py`, and you `import logging`, use `patch('scripts.sever.logging.getLogger.info') as mock_info`, you could then `self.server.obj.logger.info.assert_called_with('xxx')` @Amit

http://stackoverflow.com/q/52332915
type: UnansweredQuestion
has title: Function Arguments - Clarification
tagged with: python
downvote count: 6
has comment: http://stackoverflow.com/comment/91612571
has body: Q - Write a function consonant(ch) that returns whether or not the string ch is a consonant letter. You can assume ch is a string containing only alphabetical characters. My code: l = ['a','e','i','o','u'] def consonant(ch): if ch in l: return False else: return True x = consonant(g) # Doesn't work NameError g is not defined print(x) It gives a NameError: name 'g' is not defined. However if I give the argument as a string(character), it works: x = consonant('g') # Works I can not understand why is it not transferring the value g to ch in the first case like it is in the second case.
type: Question
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91612600
upvote count: 0
has answer: http://stackoverflow.com/a/52332972
answer count: 1
score: -6
favorite count: 0
has comment: http://stackoverflow.com/comment/91612626
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91612622

http://stackoverflow.com/comment/91541806
type: Comment
type: QuestionComment
has text: What is a "slice output" of a 3D image? What do you mean by "pack them back"? What is the definition of "optimal" for you?
comment on: http://stackoverflow.com/q/52296803
score: 0

http://stackoverflow.com/comment/91523467
has text: what you are expecting ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52287883
score: 1

http://stackoverflow.com/comment/91649297
type: AnswerComment
score: 0
type: Comment
has text: Check the update. Check also the print, it's a little debug and you can comment it when you know that the code does what you expected.
comment on: http://stackoverflow.com/a/52352111

http://stackoverflow.com/a/52359125
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52359008
type: Answer
has body: The resolution is controlled by two parameters figsize which accepts a tuple that represents the size of the figure in inches and dpi controls the dots-per-inch of the figure. These two would go into your subplots argument: ax, fig = plt.subplots(figsize=(x, y), dpi=z) where x and y would be the desired width and height of the figure and z would be the desired dpi. As for the colors, you need to select a different colormap. First choose the colormap you want (matplotlib available colormaps can be found here). Then pass it into the cmap argument of imshow, like this: ax.imshow(H1, cmap=c) where c is a string containing the name of the colormap.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52359008

http://stackoverflow.com/comment/91574939
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52310455
has text: Thanks Martin and @meowgoesthedog. I tried sorting and also removed the unnecessary lists. But that isnt solving the issue of O(N**2). May be I havent got the approach yet. But nevertheless, your inputs were very helpful.

http://stackoverflow.com/comment/91671508
type: QuestionComment
comment on: http://stackoverflow.com/q/52363569
score: 0
has text: I think you should "native" grep from python... the issue is missing `shell=True`
type: Comment

http://stackoverflow.com/comment/91668795
score: 0
has text: @Alexis svm = SVC(kernel='linear') svm.fit(X, y) X_train, X_test = X[:splitNum], X[splitNum:] y_train, y_test = y[:splitNum], y[splitNum:] y_pred = svm.predict(X_test) accuracy = metrics.accuracy_score(y_test, y_pred)
comment on: http://stackoverflow.com/q/52294663
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52291187
tagged with: python
duplicate of: http://stackoverflow.com/q/51632716
has comment: http://stackoverflow.com/comment/91546112
has body: I am starting to use the Keras. However, I am confused about the difference between Keras.layers.Concatenate and keras.backend.concatenate. It seems different. For example, when I use the Keras.layers.Concatenate, there is no error. But, when I use the keras.backend.concatenate, it will report the error: RuntimeError: Graph disconnected: cannot obtain value for tensor Tensor("concat_1:0", shape=(?, 227, 227, 3), dtype=float32) at layer "input_2_art" The code as followed: input_nc_tensor = Input(shape=(227, 227, 1), name='NC_input') input_nc_tensor_3channel = keras.layers.Concatenate(axis=-1)([input_nc_tensor, input_nc_tensor, input_nc_tensor]) input_nc_tensor_3channel = keras.backend.concatenate([input_nc_tensor, input_nc_tensor, input_nc_tensor], axis=-1) input_art_tensor = Input(shape=(227, 227, 1), name='ART_input') input_art_tensor_3channel = keras.layers.Concatenate(axis=-1)([input_art_tensor, input_art_tensor, input_art_tensor]) input_art_tensor_3channel = keras.backend.concatenate([input_art_tensor, input_art_tensor, input_art_tensor], axis=-1) input_pv_tensor = Input(shape=(227, 227, 1), name='PV_input') input_pv_tensor_3channel = keras.layers.Concatenate(axis=-1)([input_pv_tensor, input_pv_tensor, input_pv_tensor]) input_pv_tensor_3channel = keras.backend.concatenate([input_pv_tensor, input_pv_tensor, input_pv_tensor], axis=-1)
score: 1
linked to: http://stackoverflow.com/q/51632716
tagged with: tensorflow
type: Question
upvote count: 1
tagged with: keras
favorite count: 0
tagged with: deep-learning
has title: Keras, What's the difference between keras.backend.concatenate and Keras.layers.Concatenate
answer count: 0
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91530937
type: QuestionComment
has text: So essentially you want to achieve something like `$10^{2}$` outside of math mode. I don't know if that is possible. But if you find a way to do it in pure latex, it would be possible to adapt the formatter accordingly; if not, there is nothing matplotlib can do. I think usually people try to use a math font which looks similar enough to their text font in such cases.
score: 0
comment on: http://stackoverflow.com/q/52277797
type: Comment

http://stackoverflow.com/comment/91626439
type: QuestionComment
comment on: http://stackoverflow.com/q/52339274
has text: I don't want to offend you, but probably it would be better for you meantime to solve more basic problems. Honestly, it's written between lines of your code. Then you may return to this problem.
score: 0
type: Comment

http://stackoverflow.com/a/52379271
type: Answer
score: 2
downvote count: 0
has body: Use array.sum(axis=0) a = np.array([[10., 12., 15., 20., 24., 20.], [40., 48., 60. ,20., 24., 20.]]) a.sum(axis=0) Or np.sum(a,axis=0) Both gives array([50., 60., 75., 40., 48., 40.])
answers question: http://stackoverflow.com/q/52379158
upvote count: 2
has comment: http://stackoverflow.com/comment/91702756

http://stackoverflow.com/comment/91758484
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52406496
has text: @YilunZhang Ok, I get an idea, I will re-add the id into the result and do the sort. Thx

http://stackoverflow.com/comment/106144885
comment on: http://stackoverflow.com/a/52313946
has text: If you want to implement the moving average this way, you have to set `a` to the length of `b`, so the window sum is divided and the result is the average, otherwise you end up multiplying the input by the window length.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52277711
tagged with: python-3.x
tagged with: python-multithreading
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
upvote count: 1
has title: Threading in a complex application which uses Popen, Serial and MQTT
type: Question
has body: I am creating a python3 module which takes into consideration: MQTT Library from paho.mqtt.client Reading GPS data and parsing using pynmea2 and serial reading particular information from Popen and PIPE subprocesses reading/writing application to InfluxDB structure . |-- myApp | |-- mqtt | |-- db | |-- gps | |-- n2k |-- main.py In mqtt I have created a wrapper class for the mqtt.Client where in the above mentioned main.py one needs to only use: client = myMqtt() client.run() # &lt;--- run() has `loop_forever()` loop_forever() code from paho.mqtt for gps and db I am thinking of creating similar wrappers for my app. For n2k I have a simple wrapper, which calls pre-installed binaries (actisense-serial and analyzer) on /dev/ttyUSB0 port as follows: class N2KParser: def __init__(self, parser=None): self.cfg = get_configuration('n2k') # this has all the configuration (/dev/ttyUSB0) self.actisense_process = Popen(['actisense-serial', '-r', self.cfg['port']], stdout=PIPE) self.analyzer_proc = Popen(['analyzer', '-json'], stdin=self.actisense_process.stdout, stdout=PIPE, stderr=PIPE) def read(self): logger.info('Reading NMEA2000 via Actisense-NGT1 Gateway') while self.analyzer_proc.poll() is None: n2k_data = self.analyzer_proc.stdout.readline().decode('utf-8') try: n2k_dict = json.loads(n2k_data) except Exception as e: raise e self.actisense_process.close() self.analyzer_proc.close() def close(): logger.info('Closing the Parser for N2K') self.actisense_process.close() self.analyzer_proc.close() In the main.py file similar to mqtt I add an instance of n2k after the client.run() from myApp.cloud.Client import CloudMqtt from myApp.db.dbClient import influxInstance from myApp.nmea2k.n2kClient import N2KParser import time if __name__ == '__main__': try: db = influxInstance() except Exception as e: raise e try: client = CloudMqtt() rc = client.run() except Exception as e: raise e db.close() client.loop_stop() client.disconnect() try: parser = N2KParser() # &lt;--- this is not exec…
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/91686199
type: QuestionComment
has text: Not the problem, but you shouldn't iterate over `range(len(something))`. Iterate over the thing itself; in this case you should zip together urls and titles. `for url, title in zip(urls, titles):`
score: 3
comment on: http://stackoverflow.com/q/52370748
type: Comment

http://stackoverflow.com/comment/91800505
comment on: http://stackoverflow.com/q/52428472
score: 0
has text: @DanielRoseman Mikhail pointed out the mistake. Just me being a derp.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52377783
has comment: http://stackoverflow.com/comment/91700195
has comment: http://stackoverflow.com/comment/91700734
downvote count: 0
answer count: 1
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52378088
has body: Essentially, the alphabets in the input string are cyclically rotated by k and the rest of the characters retains their form. I'm puzzled by a mismatch. For my code: import math import os import random import re import sys # Complete the caesarCipher function below. def caesarCipher(s, k): st = [] for i in range(0,len(s)): if 65&lt;=ord(s[i])&lt;=90: temp = ord(s[i])+k if (temp&gt;90): temp-=26 st.append(chr(temp)) elif 97&lt;=ord(s[i])&lt;=122: temp = ord(s[i])+k if (temp&gt;122): temp-=26 st.append(chr(temp)) else: st.append(s[i]) return ''.join(st) if __name__ == '__main__': s = input() k = int(input()) result = caesarCipher(s, k) The output always fails by one, like My: okffng-Qwvc Expected: okffng-Qwvb My:Fqcfex-Qttp-ts-ymj-Gwnlmy-Xnij-tk-Qnkj Expected: Fqbfdx-Qttp-ts-ymj-Gwnlmy-Xnij-tk-Qnkj I can't seem to detect the bug.
tagged with: python
has comment: http://stackoverflow.com/comment/91700298
has comment: http://stackoverflow.com/comment/91700363
tagged with: caesar-cipher
upvote count: 1
accepted answer: http://stackoverflow.com/a/52378088
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91700352
has comment: http://stackoverflow.com/comment/91700441
has title: Single character mismatch in Caesar Cipher: Python
type: Question

http://stackoverflow.com/q/52322523
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91592676
has body: pI'm [2, 4, 2300, 4],[3, 6, 7500, 3],[2, 4, 4100, 7],[2, 4, 2800, 5],[2, 4, 5800, 2], [2, 4, 4800, 8], [2, 4, 2750, 4]] cars = [[2, 4, 2300, 4],[3, 6, 7500, 3],[2, 4, 4100, 7],[2, 4, 2800, 5],[2, 4, 5800, 2], [2, 4, 4800, 8], [2, 4, 2750, 4]]
has title: pI'm trying to What am I doing wrong here?
type: Question
has answer: http://stackoverflow.com/a/52322580
answer count: 2
tagged with: function
has answer: http://stackoverflow.com/a/52322585
score: 0
has comment: http://stackoverflow.com/comment/91592669
tagged with: python
tagged with: list

http://stackoverflow.com/comment/91651586
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52352511
has text: Does the list comprehension work? You won't get anything faster or simpler,

http://stackoverflow.com/comment/91867505
score: 0
has text: Ty @Kenpachi!! I really appreciate your time!
type: AnswerComment
comment on: http://stackoverflow.com/a/52417273
type: Comment

http://stackoverflow.com/a/52276475
type: Answer
score: 0
has body: You can use a nested comprehension: d = {i.get('from', i.get('id')) for b in output['all_paths'] for i in b['path']} Output: {'LWbARpjEjpZae3DZ', 'eEo7aB0vgkdRO02V', 'AyD8rYemY6er47Vk', '4Po9aW3oxoNaAQzW'}
answers question: http://stackoverflow.com/q/52276345

http://stackoverflow.com/q/52348148
has comment: http://stackoverflow.com/comment/91641730
downvote count: 0
answer count: 1
has title: Delete Messages with Python Discord bot?
has comment: http://stackoverflow.com/comment/91642129
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91642069
tagged with: discord
has body: I'm trying to make a Python Discord Bot that firstly can delete messages within a channel. I wanted it to be Terminator 3 themed so it would start out by the user saying Skynet then the bot asks to activate Y or N? and when the user types Y it would delete all the messages in the channel if the user typed N it would say judgment day is inevitable. any help would be greatly appreciated. import discord from discord.ext.commands import Bot from discord.ext import commands import asyncio token = 'Token' Client = discord.Client() client = commands.Bot(command_prefix = '!') @client.event async def on_ready(): print("Skynet Online") @client.event async def on_message(message): if message.content == 'skynet': await client.send_message(message.channel, 'Execute Y/N?') @asyncio.coroutine async def delete_messages(messages): if message.content == 'Y': await client.delete_messages() client.run('Token')
type: UnansweredQuestion
upvote count: 1
type: Question
tagged with: discord.py
tagged with: bots
score: 1
has answer: http://stackoverflow.com/a/52348260

http://stackoverflow.com/q/52295963
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52296162
tagged with: python
upvote count: 6
type: AnsweredQuestion
score: 6
has title: Calculate difference between values in rows by group
type: Question
accepted answer: http://stackoverflow.com/a/52296162
has body: I have df like this: I need to calculate difference between X1, X2, X3, X4 and X5 for each company, but I know only how to calculate difference between whole column. df['dX1'] = df['X1'].shift(-1) - df['X1'] df['dX2'] = df['X2'].shift(-1) - df['X2'] df['dX3'] = df['X3'].shift(-1) - df['X3'] ... It's bad approach because it's substracting X1 on line 74 with X1 on line 73 (and that's 2 different companies, that makes no sense). My question is, how to calculate difference between row values but for every period and for every company. E.g. (I can load csvs one by one and calculate diff for each company, then merge all into one list, but it will take 2 days because i have 700 csv files).
tagged with: pandas

http://stackoverflow.com/a/52414647
type: Answer
answers question: http://stackoverflow.com/q/52413535
score: 0
has comment: http://stackoverflow.com/comment/91802639
has comment: http://stackoverflow.com/comment/91811169
has body: You are using python. Then you can make use of pandas package to process your data. import pandas as pd import numpy as np Convert the file into pandas' dataframe. df = pd.read_table('path_to_your_file', delimiter = " ", header=None) You will get something like: | 0 1 2 3 --|------------ 0 | x x x x 1 | x x x x 2 | x x x x Create function def create_new(df): new_row = 0 mid = df.shape[1]//2 for i in range(0, mid): new_row += np.sqrt(df[i]**2+df[i+mid]**2) return new_row df['n+1'] = df.apply(create_new, axis=1) It will create a new column named n+1 containing the calculation of each rows. | 0 1 2 3 n+1 --|------------------ 0 | x x x x y 1 | x x x x y 2 | x x x x y

http://stackoverflow.com/comment/91645963
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52350334
has text: Still doesn't work. It shouldn't matter as I am not accessing the `axx[0]`. Something is wrong with the for-loop and list assignment.
score: 0

http://stackoverflow.com/comment/91731392
comment on: http://stackoverflow.com/q/52350801
score: 0
type: QuestionComment
type: Comment
has text: @Iguananaut, im not an intelligent moron that posts something without debugging.Yes I added and removed parts(header, proxy). I've done this in 2-3 different ways. This is where I am, the proxy and header are not working. It sends MY ip, and MY own browser header.

http://stackoverflow.com/a/62119508
type: Answer
has body: Since Dani Mesejo's answer, the subtract method (docs) has been added for keeping negative counts in Counter objects (only inplace however), i.e. the following is a more succinct solution: from collections import Counter D1 = Counter({'A': 2, 'B': 1, 'C': 4, 'D': 5, 'E': 5}) D2 = Counter({'A': 3, 'B': 4, 'C': 4, 'D': 7, 'E': 3}) R1 = D1 &amp; D2 print(R1) D2.subtract(D1) print(D2) Output: Counter({'D': 5, 'C': 4, 'E': 3, 'A': 2, 'B': 1}) Counter({'B': 3, 'D': 2, 'A': 1, 'C': 0, 'E': -2})
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/52323957
downvote count: 0

http://stackoverflow.com/comment/91630422
comment on: http://stackoverflow.com/a/52341441
score: 0
type: AnswerComment
type: Comment
has text: I know what you mean, but it only returns one value, I want get a parameter(model.a) with the same structure as the origin parameter(model.distance). Anyway, thankyou so much!

http://stackoverflow.com/q/52349029
has title: Calling a function a second time with only slight changes
possible better answer: http://stackoverflow.com/a/52349099
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52349099
has body: I have a function called get_next_train: def get_next_train(params): res =requests.get(base, params=params) parsed_json = res.json() #Zeiten aus parsed_json extrahieren time_strings = [d["from"]["prognosis"]["departure"] for d in parsed_json["connections"]] #String, um Zeiten in time_strings nach ISO 8601 zu parsen iso_format = "%Y-%m-%dT%H:%M:%S%z" # Time Strings zu datetime Objekten konvertieren times = [datetime.strptime(ts, iso_format) for ts in time_strings if ts is not None] # Checken, ob times leer sind if not times: return None # CHANGE: return None if no times found #Zeitzone der ersten zeit in Times speichern tz = times[0].tzinfo #jetztige Zeit mit Zeitzone tz, Mikrosekunden löschen nowtime = datetime.now(tz).replace(microsecond=0) time = min(t for t in times[0:3] if t &gt; nowtime) # CHANGE: use min return time, time - nowtime I want it to be executed twice: The first time just the way it is now. But the second time, time_strings should be this: time_strings = [d["from"]["departure"] for d in parsed_json["connections"]] I've tried countless ways of doing it but failed every time. The most common error was: name 'parsed_json' is not defined. I could of course just copy paste this whole code and change the bit I need to, but is there any better way of doing this?
has comment: http://stackoverflow.com/comment/91643385
score: 1
type: Question
has answer: http://stackoverflow.com/a/52349057
tagged with: function
downvote count: 0
tagged with: variables
favorite count: 0
has answer: http://stackoverflow.com/a/52349089
answer count: 3
accepted answer: http://stackoverflow.com/a/52349057
upvote count: 1
tagged with: python

http://stackoverflow.com/q/52414426
has comment: http://stackoverflow.com/comment/91772915
has comment: http://stackoverflow.com/comment/91772839
has title: has_path equivalent in Graph-Tool
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52475383
tagged with: graph-tool
type: Question
has answer: http://stackoverflow.com/a/52475383
has body: Does graph-tool have any equivalent function to NetworkX's has_path? I'd like to return True if there's a valid path between any given nodes.
score: 0
answer count: 1

http://stackoverflow.com/a/52280895
type: Answer
has comment: http://stackoverflow.com/comment/91509919
score: 2
has body: The file you are creating is called 'file_differ_functions.py', not 'my_functions.py'. Also you should close files after you open them with fdf.close()
accepted answer of: http://stackoverflow.com/q/52280858
answers question: http://stackoverflow.com/q/52280858
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91509903
downvote count: 0

datetime
tags question: http://stackoverflow.com/q/52293232
tags question: http://stackoverflow.com/q/52294171
tags question: http://stackoverflow.com/q/52285759
tags question: http://stackoverflow.com/q/52351116
tags question: http://stackoverflow.com/q/52428769
tags question: http://stackoverflow.com/q/52277962
tags question: http://stackoverflow.com/q/52346412
tags question: http://stackoverflow.com/q/52304651
tags question: http://stackoverflow.com/q/52329931
tags question: http://stackoverflow.com/q/52349227
tags question: http://stackoverflow.com/q/52293959
tags question: http://stackoverflow.com/q/52339528
tags question: http://stackoverflow.com/q/52279296
tags question: http://stackoverflow.com/q/52359827
tags question: http://stackoverflow.com/q/52296599
tags question: http://stackoverflow.com/q/52298019
tags question: http://stackoverflow.com/q/52301920
tags question: http://stackoverflow.com/q/52395768
tags question: http://stackoverflow.com/q/52281683
tags question: http://stackoverflow.com/q/52404877
tag name: datetime
tags question: http://stackoverflow.com/q/52398383
tags question: http://stackoverflow.com/q/52274356
tags question: http://stackoverflow.com/q/52291519
tags question: http://stackoverflow.com/q/52427651
tags question: http://stackoverflow.com/q/52307091
tags question: http://stackoverflow.com/q/52273375
type: Tag
tags question: http://stackoverflow.com/q/52417231
tags question: http://stackoverflow.com/q/52395820
tags question: http://stackoverflow.com/q/52358779
tags question: http://stackoverflow.com/q/52426130
tags question: http://stackoverflow.com/q/52368202
tags question: http://stackoverflow.com/q/52371705
tags question: http://stackoverflow.com/q/52357460
tags question: http://stackoverflow.com/q/52282197
tags question: http://stackoverflow.com/q/52419519
tags question: http://stackoverflow.com/q/52281633
tags question: http://stackoverflow.com/q/52297308
tags question: http://stackoverflow.com/q/52316001
tags question: http://stackoverflow.com/q/52282194
tags question: http://stackoverflow.com/q/52291141
tags question: http://stackoverflow.com/q/52323069
tags question: http://stackoverflow.com/q/52416332
tags question: http://stackoverflow.com/q/52417195
tags question: http://stackoverflow.com/q/52329570
tags question: http://stackoverflow.com/q/52373931
tags question: http://stackoverflow.com/q/52401886
tags question: http://stackoverflow.com/q/52394909
tags question: http://stackoverflow.com/q/52278966
tags question: http://stackoverflow.com/q/52416191

http://stackoverflow.com/comment/91647963
score: 0
type: Comment
has text: Nice, that fixed it! @cattythegamer
comment on: http://stackoverflow.com/a/52304635
type: AnswerComment

http://stackoverflow.com/comment/91718532
has text: i thought that doing sort in the same line would sort the group by simultaneously. Ok. I did it after the group by and it worked.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52386913
score: 1

http://stackoverflow.com/comment/91555448
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52302134
has text: thanks, but can you rewrite what you mean by I would try is putting what I wrote down after (because you are clearing session with K.clear_session) If__name__=="main": Imgdir="D:/NHQ/coursea_computervision/TensorFlowGPU/training_set - Copy" K.clear_session() with tf.device('/gpu:0'):, actually code is not clear
type: AnswerComment

http://stackoverflow.com/q/52308132
has title: Asynchronous HTTP call inside HTTP cycle of Django Rest Framework
type: UnansweredQuestion
has body: I need to call external service on the get_queryset function of one of my viewsets on views.py, but I don't need to wait for the response of external function. How can I make the following requests.post line just triggered and passed to next line without waiting for the result? class SomeViewSet(viewsets.ModelViewSet): def get_queryset(self): .... requests.post(urlOfApi+token) ..... return Some.objects.all()
tagged with: django-rest-framework
tagged with: python-asyncio
tagged with: asynchronous
has answer: http://stackoverflow.com/a/52311691
favorite count: 0
type: Question
answer count: 2
tagged with: django
linked to: http://stackoverflow.com/q/2846653
tagged with: python
has answer: http://stackoverflow.com/a/52309257
has comment: http://stackoverflow.com/comment/91563683
score: 0
has comment: http://stackoverflow.com/comment/91563574
upvote count: 1
has comment: http://stackoverflow.com/comment/91563437
downvote count: 1

http://stackoverflow.com/a/52302622
downvote count: 0
has comment: http://stackoverflow.com/comment/91553467
type: Answer
has comment: http://stackoverflow.com/comment/91554249
score: 1
accepted answer of: http://stackoverflow.com/q/52302442
upvote count: 1
answers question: http://stackoverflow.com/q/52302442
has comment: http://stackoverflow.com/comment/91553599
has comment: http://stackoverflow.com/comment/91553645
has body: I would handle this while indexing the list. All out of bounds accesses should refer to the last element by default. You'd want to do something of the like: def get_graceful_overflow(lst, idx): return lst[min(idx, len(lst) - 1)] Now substitute calls to commission[i] with get_graceful_overflow(commission, i). And similar for interest.
has comment: http://stackoverflow.com/comment/91554227
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91553436

http://stackoverflow.com/q/52391099
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/91730489
tagged with: python
has comment: http://stackoverflow.com/comment/91730848
tagged with: regex
has comment: http://stackoverflow.com/comment/91727323
has body: Is it possible to use python's regex conditionals in re.sub()? I've tried a number of variations without luck. Here's what I have. import re # match anything: &lt;test&gt; always true a = re.compile('(?P&lt;test&gt;.*)') # return _'yes'_ or 'no' based on &lt;test&gt; a.sub('(?(\g&lt;test&gt;)yes|no)', 'word') '(?(word)yes|no)' I expected either a 'yes' or 'no,' not the actual test. What I get from this is that &lt;test&gt; is seen but the regex conditional isn't being executed. Is there another way of accomplishing this? I tried with re.sub(pat, rep, str) with same results.
upvote count: 1
has answer: http://stackoverflow.com/a/52392221
answer count: 1
tagged with: conditional-statements
has comment: http://stackoverflow.com/comment/91727410
has title: python regex conditional in re.sub - how?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52392221
downvote count: 0

http://stackoverflow.com/a/52335602
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52335505
has body: I feel stupid posting this, and finding the answer right away. I just changed the last url slightly. path('&lt;path&gt;', static.serve, {'document_root': settings.DOCS_ROOT}, name='static.file.serve')
answers question: http://stackoverflow.com/q/52335505

http://stackoverflow.com/a/52355288
has comment: http://stackoverflow.com/comment/91655498
has comment: http://stackoverflow.com/comment/91655339
downvote count: 0
has comment: http://stackoverflow.com/comment/91655859
score: 5
type: Answer
has comment: http://stackoverflow.com/comment/91656100
has body: print() will slow down your loop. That is because you are making a system call and an IO operation each time you call print(). System calls consume a lot of CPU cycles and involves CPU context switch. IO operations will block the main thread of your process for sometime. So the obvious solution is to either eliminate or reduce the number of print() calls. If you really need a mechanism to know the current iteration count of loop, then you can use multi-threading to achieve this. But still, it may involve system calls and thread context switching. But I suppose it will be still faster than print(). The trick is to perform the loop in a background thread while you print the progress in main thread. This way the IO operation in calling print() wont block the thread that runs the loop. To optimize it even further, you can print the progress only when user press a key. import threading lock = threading.Lock() count = 0 def your_method_with_a_loop(): global count with open("f.txt","w") as f: for q in range(1000000): f.write(str(q)+"\n") #your_logic_here #.... lock.acquire() count = count + 1 lock.release() #Run the loop in a background thread t1 = threading.Thread(target=your_method_with_a_loop) t1.start() while t1.isAlive(): print("Press enter to see current loop iteration count\n") #use raw_input() instead if your are using python 2.x. input() #Remove this line if you want to print progress continuously. lock.acquire() current_count = count lock.release() print("Current loop iteration count is ",count,"\n") This solution improves the situation by two ways IO operation is not performed on the worker thread. Yes using locks involves system call. But it is still faster than an IO block. Assuming that the python interpreter uses futex to implement locks, then the cost of aquiring and releasing the lock is very slow, since when compared to worker thread the main thread would rarely hold the lock.
has comment: http://stackoverflow.com/comment/91655454
upvote count: 5
has comment: http://stackoverflow.com/comment/91655499
answers question: http://stackoverflow.com/q/52354963

http://stackoverflow.com/a/52416646
has comment: http://stackoverflow.com/comment/91776872
has comment: http://stackoverflow.com/comment/91776852
score: -1
downvote count: 1
has body: Why not just print before you return? def add(a, b): print(f"{a} is being added...") print(f"{b} is being added..") return a + b c = add(1, 2) print(c) (xenial)vash@localhost:~/python/stack_overflow$ python3.7 strings.py 1 is being added... 2 is being added.. 3 Suggest: print(f'{pdata} "Your file will be ready for download..."') print(f'{pdata} "it will just atake a moment..."') filename = request.form.get('filename') filepath = '/home/nikos/wsgi/static/files/' return send_from_directory( filepath, filename ) Older Python: print(f'{} "Your file will be ready for download..."'.format(pdata)) print(f'{} "it will just atake a moment..."'.format(pdata)) filename = request.form.get('filename') filepath = '/home/nikos/wsgi/static/files/' return send_from_directory( filepath, filename )
has comment: http://stackoverflow.com/comment/91776780
answers question: http://stackoverflow.com/q/52416568
has comment: http://stackoverflow.com/comment/91776664
type: Answer
has comment: http://stackoverflow.com/comment/91776701
upvote count: 0
has comment: http://stackoverflow.com/comment/91776830
has comment: http://stackoverflow.com/comment/91776689
has comment: http://stackoverflow.com/comment/91776729

http://stackoverflow.com/q/52299774
duplicate of: http://stackoverflow.com/q/34881079
has title: How to convert object columns to string and use replace?
linked to: http://stackoverflow.com/q/34881079
tagged with: python
has body: I have some columns ['subject', 'H.period', 'DD.period.t'] etc. Actually all columns are object type. dtype printscreen How can i convert these columns into string type? And how can i use .replace for converting "," into "." in a csv file? I need to use these data in machine learning K Neighbors algorithm.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52299852
type: Question
has answer: http://stackoverflow.com/a/52299977
answer count: 2
possible better answer: http://stackoverflow.com/a/52299977
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52299852
tagged with: string

http://stackoverflow.com/q/52417233
answer count: 1
has body: I have got some video frames with Opencv Python and able to convert it into grayscale. Now I want to do something like this to calculate ssim_multiscale i1 = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) i2 = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY) i1 = np.array(i1, dtype=np.float64) i2 = np.array(i2,dtype=np.float64) print(tf.image.ssim_multiscale(i1,i2,255)) But I got this error shape1 = img1.get_shape().with_rank_at_least(3). AttributeError: 'numpy.ndarray' object has no attribute 'get_shape' I have checked the documentation of np.array and it has get_shape attribute. How should I pass Mat into the ssim_multiscale parameter? tf.image.ssim_multiscale( img1, img2, max_val, power_factors=_MSSSIM_WEIGHTS )
tagged with: python
tagged with: opencv
type: AnsweredQuestion
tagged with: tensorflow
type: Question
has title: how do we pass Mat from opencv into tensorflow tf.image.ssim_multiscale?
has answer: http://stackoverflow.com/a/52547182
accepted answer: http://stackoverflow.com/a/52547182
score: 0

http://stackoverflow.com/q/52307822
has comment: http://stackoverflow.com/comment/91562881
favorite count: 0
has comment: http://stackoverflow.com/comment/91628017
has answer: http://stackoverflow.com/a/52308143
accepted answer: http://stackoverflow.com/a/52308143
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91562982
score: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91563853
tagged with: arrays
has body: I have an array with most of the elements are zero. A = [ 1,0,2 2,3,0 0,0,4 ] I want to save this as rowid[0] colid[0] 1 rowid[0] colid[2] 2 rowid[1] colid[0] 2 rowid[1] colid[1] 3 rowid[2] colid[2] 4 here rowid and colid are arrays which maps the array indices to the actual entries in an original file. How can I do this without using a for loop ?.
tagged with: python-2.7
upvote count: 1
has title: python save numpy array with only non-zero elements
has comment: http://stackoverflow.com/comment/91563368
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/91614750
type: Comment
has text: I made an attempt to clarify it
comment on: http://stackoverflow.com/q/52333540
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91534421
comment on: http://stackoverflow.com/q/52293248
type: Comment
score: 2
has text: @MosheSlavin How does that relate to this question?
type: QuestionComment

http://stackoverflow.com/comment/91616622
type: Comment
type: QuestionComment
has text: Probably I am still learning Python. The files size range from 800kb to 8 Gigs.
score: 0
comment on: http://stackoverflow.com/q/52334602

http://stackoverflow.com/comment/91627127
comment on: http://stackoverflow.com/q/52339907
score: 0
has text: @Mako212 there's no R anywhere
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91557947
type: Comment
type: QuestionComment
score: 0
has text: The first one would make a `NameError`, because from within `test_counts_set_correctly` the name `cls` would not be bound, far as I can tell.
comment on: http://stackoverflow.com/q/52305191

http://stackoverflow.com/comment/109760315
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52397069
has text: @Richard any updates on this ? thanks
score: 0

http://stackoverflow.com/comment/91686652
has text: @JeffC It depends on what you mean by a UI. The browser still processes HTML and CSS to generate a page, it just doesn't render it visibly. Without a UI, there'd be no way to drive it when you send it commands like "click in the coordinates 50,100"
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52316980

http://stackoverflow.com/q/52321660
has body: I am relatively new to pytest at the moment and was curious if there is a way to store the pass/fail results of the test in a variable. Essentially what I want to do is run my full suite of tests and after the tests are run, send the name of the tests run along with the pass/fail result to a server. I understand that pytest provides options such as -r that will output the test run with pass or fail after execution, but is there a way to store those into variables or pass those results along?
score: 1
has comment: http://stackoverflow.com/comment/91591044
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91591147
has answer: http://stackoverflow.com/a/52321779
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91590967
favorite count: 0
tagged with: python
has title: Storing pass/fail result after all tests are run
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52321779
tagged with: pytest

http://stackoverflow.com/a/52506211
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52412516
upvote count: 6
has body: In Python you don't need to make any code changes to use the emulator. Instead, you must have the PUBSUB_EMULATOR_HOST and PUBSUB_PROJECT_ID environmental variables defined. The easiest way to set them is to run $(gcloud beta emulators pubsub env-init) before starting your program. if you are using Google App Engine locally, run that command and then start your app with dev_appserver.py app.yaml --env_var PUBSUB_EMULATOR_HOST=${PUBSUB_EMULATOR_HOST}. This is documented at https://cloud.google.com/pubsub/docs/emulator
score: 6

http://stackoverflow.com/comment/91675701
comment on: http://stackoverflow.com/q/52365723
has text: going by the tag wiki, `.so` files are c++
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91518898
has text: I'm accepting this solution because it is pretty compact and directly applicable to the problem.
type: Comment
score: 2
comment on: http://stackoverflow.com/a/52281733
type: AnswerComment

http://stackoverflow.com/comment/93948349
score: 0
type: QuestionComment
type: Comment
has text: Did you manage to solve that issue? I am also struggling with a similar task.
comment on: http://stackoverflow.com/q/52369925

http://stackoverflow.com/q/52375238
tagged with: postgresql
has body: I understand that I can set search_path for the db role used to log in, but is there a way to specify the schema at the URI level or something to that effect? I may be mistaken due to my PostgreSQL experience being only with the JDBC driver. My current URI fails: postgresql://app_user:pw@localhost/dev_db?currentSchema=app psycopg2 is complaining about currentSchema being an invalid option sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) invalid dsn: invalid connection option "currentSchema" (Background on this error at: http://sqlalche.me/e/f405)
score: 3
tagged with: python
linked to: http://stackoverflow.com/q/9298296
has comment: http://stackoverflow.com/comment/91695958
answer count: 0
upvote count: 3
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/9298296
type: Question
has title: How to target PostgreSQL schema in SQLAlchemy DB URI?
has comment: http://stackoverflow.com/comment/91696862
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/91696008
downvote count: 0
has comment: http://stackoverflow.com/comment/91695882
favorite count: 0
linked to: http://stackoverflow.com/q/11873959

http://stackoverflow.com/comment/91666171
comment on: http://stackoverflow.com/q/52360537
score: 1
has text: @AdamSmith In the course I am enrolled in, over the first two weeks we hit Excel and VBA. We started python in the third week, the first example program being a simple 'Hello World' (*mostly for checking we had things installed properly*) and f-strings were already being used in the following example. We have since been covering pandas and matplotlib. It is both helpful and hurtful at times to be learning just through examples and activities without the use of a textbook.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52371463
answers question: http://stackoverflow.com/q/52370799
type: Answer
has body: This can happen if the element in question is not in the view port of the browser. This can be fixed by executing some script or using an ActionChain to scroll to the element. From this SO question: driver.execute_script("arguments[0].scrollIntoView();", element)
accepted answer of: http://stackoverflow.com/q/52370799
score: 0
has comment: http://stackoverflow.com/comment/91689920
type: AcceptedAnswer

http://stackoverflow.com/a/52424763
score: 1
has comment: http://stackoverflow.com/comment/91792311
type: Answer
accepted answer of: http://stackoverflow.com/q/52424640
answers question: http://stackoverflow.com/q/52424640
has body: You could try using the ThreadPool class from multiprocessing.pool import ThreadPool threadp = ThreadPool(processes=1) res = threadp.apply_async(publishIAmFree, ()) # () has the arguments for function return_val = res.get() print return_val
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52393823
has comment: http://stackoverflow.com/comment/91732967
accepted answer: http://stackoverflow.com/a/52426369
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91733047
tagged with: javascript
tagged with: iot
type: Question
has body: I have implemented an accelerometer Reader in python and I want to execute a function in a javascript file when a new value is read that will: 1 - update the value in a database 2 - broadcast the new value to all connected client ( via Socket.io) I was wondering how to do it? I checked PyV8 but it seems not maintained and only working with Python 2.7. My files structure looks like --JScode ----MyJSCode --PythonCode ----MyPythonCode
has comment: http://stackoverflow.com/comment/91732803
linked to: http://stackoverflow.com/q/8284765
tagged with: pyv8
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52426369
has comment: http://stackoverflow.com/comment/91732910
has comment: http://stackoverflow.com/comment/91732906
tagged with: python
has title: Run python from javascript
score: 2
has comment: http://stackoverflow.com/comment/91732854
upvote count: 2
has comment: http://stackoverflow.com/comment/91732824

http://stackoverflow.com/comment/91625910
has text: Forget about Python for a second -- can you clearly put into words how you would go about doing it by hand? You seem to be trying to write code before you really understand just what you are trying to do.
type: Comment
type: QuestionComment
score: 8
comment on: http://stackoverflow.com/q/52339274

variables
tag name: variables
tags question: http://stackoverflow.com/q/52349029
tags question: http://stackoverflow.com/q/52397388
tags question: http://stackoverflow.com/q/52286085
tags question: http://stackoverflow.com/q/52350412
tags question: http://stackoverflow.com/q/52379803
tags question: http://stackoverflow.com/q/52366175
tags question: http://stackoverflow.com/q/52335181
tags question: http://stackoverflow.com/q/52331065
tags question: http://stackoverflow.com/q/52282824
type: Tag
tags question: http://stackoverflow.com/q/52333927
tags question: http://stackoverflow.com/q/52396169
tags question: http://stackoverflow.com/q/52413337
tags question: http://stackoverflow.com/q/52377789
tags question: http://stackoverflow.com/q/52306592
tags question: http://stackoverflow.com/q/52363569
tags question: http://stackoverflow.com/q/52296794
tags question: http://stackoverflow.com/q/52335332
tags question: http://stackoverflow.com/q/52350373
tags question: http://stackoverflow.com/q/52350642
tags question: http://stackoverflow.com/q/52320942
tags question: http://stackoverflow.com/q/52344871

http://stackoverflow.com/q/52423280
type: UnansweredQuestion
tagged with: python
has title: Plotting histogram in pandas?
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52423619
upvote count: 0
score: -1
tagged with: pandas
answer count: 1
has body: I have a dataframe like this and wish to make a frequency histogram. 1.19714 1.04872 0.188158 1 1.02339 1 1 1 0.38496 1.31858 1 1.33654 0.945736 1.00877 0.413445 0.810127 1 0.625 0.492857 0.187156 0.95847 I want to plot a frequency histogram, with x axis bins from -1 to 1. How can I do this in pandas?
favorite count: 0

http://stackoverflow.com/comment/91609276
type: QuestionComment
comment on: http://stackoverflow.com/q/52330667
has text: The linked answers already explain it in far more detail than we can do again. There's also another dupe: https://stackoverflow.com/a/6260097/4799172 that illustrates the issue, which you could get to from the initial dupe I linked
score: 0
type: Comment

http://stackoverflow.com/comment/91664303
comment on: http://stackoverflow.com/q/52358923
score: 0
has text: Any help to resolve recursive call ?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91674292
type: QuestionComment
has text: Hello @Shir your example is working correctly when I specify the colors , In my codes when I specify colors in `plt.scatter(x,y, s = 35 , c =colors )` I am getting `ValueError: c of shape (530,) not acceptable as a color sequence for x with size 530, y with size 530 ` as error. Any idea to resolve this
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52362716

http://stackoverflow.com/q/52428685
has comment: http://stackoverflow.com/comment/91810675
tagged with: python
has comment: http://stackoverflow.com/comment/91801369
has title: Python generated file does not execute properly
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/91804590
type: UnansweredQuestion
tagged with: cmake
tagged with: sh
has comment: http://stackoverflow.com/comment/91803854
type: Question
has comment: http://stackoverflow.com/comment/91801420
has comment: http://stackoverflow.com/comment/91808705
has comment: http://stackoverflow.com/comment/91806625
has body: I have a problem with files I generated with Python. I have some files (.sh-files) that I want to create dynamically. The files themselves can be executed properly and do what they are supposed to. The Python generated files however are IDENTICAL, the diff command in Linux has an empty result! But when I execute the generated .sh scripts, they give me random errors. Here is my normal file (for example): OBJDUMP=`which riscv32-unknown-elf-objdump` OBJCOPY=`which riscv32-unknown-elf-objcopy` COMPILER=`which riscv32-unknown-elf-gcc` RANLIB=`which riscv32-unknown-elf-ranlib` VSIM=`which vsim` echo $VSIM TARGET_C_FLAGS="-O3 -m32 -g" #TARGET_C_FLAGS="-O2 -g -falign-functions=16 -funroll-all-loops" # if you want to have compressed instructions, set this to 1 RVC=0 # if you are using zero-riscy, set this to 1, otherwise it uses RISCY USE_ZERO_RISCY=0 # set this to 1 if you are using the Floating Point extensions for riscy only RISCY_RV32F=0 # zeroriscy with the multiplier ZERO_RV32M=0 # zeroriscy with only 16 registers ZERO_RV32E=0 # riscy with PULPextensions, it is assumed you use the ETH GCC Compiler GCC_MARCH="IMXpulpv2" #compile arduino lib ARDUINO_LIB=1 PULP_GIT_DIRECTORY=../../ SIM_DIRECTORY="$PULP_GIT_DIRECTORY/vsim" #insert here your post-layout netlist if you are using IMPERIO PL_NETLIST="" cmake "$PULP_GIT_DIRECTORY"/sw/ \ -DPULP_MODELSIM_DIRECTORY="$SIM_DIRECTORY" \ -DCMAKE_C_COMPILER="$COMPILER" \ -DVSIM="$VSIM" \ -DRVC="$RVC" \ -DRISCY_RV32F="$RISCY_RV32F" \ -DUSE_ZERO_RISCY="$USE_ZERO_RISCY" \ -DZERO_RV32M="$ZERO_RV32M" \ -DZERO_RV32E="$ZERO_RV32E" \ -DGCC_MARCH="$GCC_MARCH" \ -DARDUINO_LIB="$ARDUINO_LIB" \ -DPL_NETLIST="$PL_NETLIST" \ -DCMAKE_C_FLAGS="$TARGET_C_FLAGS" \ -DCMAKE_OBJCOPY="$OBJCOPY" \ -DCMAKE_OBJDUMP="$OBJDUMP" And here is the python generated one. OBJDUMP=`which riscv32-unknown-elf-objdump` OBJCOPY=`which riscv32-unknown-elf-objcopy` COMPILER=`which riscv32-unknown-elf-gcc` RANLIB=`which riscv32-unknown-elf-ranlib` VSIM=`which vsim` TARGET_C_FL…
has comment: http://stackoverflow.com/comment/91804274
has comment: http://stackoverflow.com/comment/91807998

http://stackoverflow.com/q/52305454
tagged with: tkinter
tagged with: oop
answer count: 0
score: 0
type: Question
has comment: http://stackoverflow.com/comment/91558398
has body: I'm working on a program that takes data from a spreadsheet and enters it into a contract template, then converts it into a PDF. I've created a simple GUI using tkinter, and I'd like to have a button that opens a new window, allowing users to select the .xlsx file they'd like to work from. I can't seem to figure out how to get my program to run without calling the importSpread method right when the program starts. Here are the relevant portions of my code: import os from tkinter import * from tkinter import filedialog class GUI: def __init__(self, master): self.master = master self.root = os.path.dirname(os.path.abspath(__file__)) + '\\' self.importButton = Button(master, text = 'Import Spreadsheet', command = self.importSpread, height = 1, width = 20) self.importButton.grid(row = 1, column = 2, sticky = W) def importSpread(self): my_filetypes = [('excel files', '.xlsx')] fileName = filedialog.askopenfilename(parent = self.master, initialdir = self.root, title = "Please select a file:", filetypes = my_filetypes) return fileName window = Tk() myGUI = GUI(window) fileName = self.importSpread() window.mainloop() It seems as though as soon as I instantiate the myGUI object by saying myGUI = GUI(window), the importSpread method is automatically called. I'd also like importSpread to return the fileName to be used later. How do I retain the value the method returns without calling the method itself? I want the program to start and remain static until the user presses the "Import Spreadsheet" button. I'm fairly new to python and GUIs in general, so I could be missing something basic. Any guidance would be much appreciated.
has comment: http://stackoverflow.com/comment/91558345
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91559212
has title: method automatically calls when starting the program
tagged with: python

http://stackoverflow.com/a/52340670
upvote count: 8
type: Answer
score: 8
has body: Before everything, check [SO]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer) for a common pitfall when working with CTypes (calling functions). The CTypes home page (also listed in the above URL): [Python.Docs]: ctypes - A foreign function library for Python I changed your code "a bit". code00.py: #!/usr/bin/env python import ctypes as cts import ctypes.wintypes as wts import sys LF_FACESIZE = 32 STD_OUTPUT_HANDLE = -11 class CONSOLE_FONT_INFOEX(cts.Structure): _fields_ = ( ("cbSize", wts.ULONG), ("nFont", wts.DWORD), ("dwFontSize", wts._COORD), ("FontFamily", wts.UINT), ("FontWeight", wts.UINT), ("FaceName", wts.WCHAR * LF_FACESIZE) ) def main(*argv): kernel32 = cts.WinDLL("Kernel32.dll") GetLastError = kernel32.GetLastError GetLastError.argtypes = () GetLastError.restype = wts.DWORD GetStdHandle = kernel32.GetStdHandle GetStdHandle.argtypes = (wts.DWORD,) GetStdHandle.restype = wts.HANDLE GetCurrentConsoleFontEx = kernel32.GetCurrentConsoleFontEx GetCurrentConsoleFontEx.argtypes = (wts.HANDLE, wts.BOOL, cts.POINTER(CONSOLE_FONT_INFOEX)) GetCurrentConsoleFontEx.restype = wts.BOOL SetCurrentConsoleFontEx = kernel32.SetCurrentConsoleFontEx SetCurrentConsoleFontEx.argtypes = (wts.HANDLE, wts.BOOL, cts.POINTER(CONSOLE_FONT_INFOEX)) SetCurrentConsoleFontEx.restype = wts.BOOL # Get stdout handle stdout = GetStdHandle(STD_OUTPUT_HANDLE) if not stdout: print("{:s} error: {:d}".format(GetStdHandle.__name__, GetLastError())) return # Get current font characteristics font = CONSOLE_FONT_INFOEX() font.cbSize = cts.sizeof(CONSOLE_FONT_INFOEX) res = GetCurrentConsoleFontEx(stdout, False, cts.byref(font)) if not res: print("{:s} error: {:d}".format(GetCurrentConsoleFontEx.__name__, GetLastError())) return # Display font information print("Console information for {:}".format(font)) for field_name, _ in font._fields_: field_data = getattr(font, field_name) if field_name == "dwFontSize": print(" {:s}: {{X: {:d}, Y: {:d}}}".format(field_name,…
answers question: http://stackoverflow.com/q/52336257
accepted answer of: http://stackoverflow.com/q/52336257
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91676175
type: QuestionComment
has text: have you included the css in the html.. ?
comment on: http://stackoverflow.com/q/52365584
score: 0
type: Comment

http://stackoverflow.com/a/52372410
has comment: http://stackoverflow.com/comment/91691016
answers question: http://stackoverflow.com/q/52372214
type: Answer
has comment: http://stackoverflow.com/comment/91691879
has comment: http://stackoverflow.com/comment/91690138
has comment: http://stackoverflow.com/comment/91691269
has body: According to https://anaconda.org/anaconda/anaconda-client/files, the available version for anaconda-client is 1.7.2, while https://pypi.org/project/anaconda-client/ lists 1.2.2 &amp; non updated homepage http://github.com/Anaconda-client/anaconda-client (instead of their current repo https://github.com/Anaconda-Platform/anaconda-client) My suggestion is to use pip to install the stable version (or whichever version you're after) from github .git instead of pypi.
has comment: http://stackoverflow.com/comment/91690532
has comment: http://stackoverflow.com/comment/91692616
score: 0

http://stackoverflow.com/q/52417680
accepted answer: http://stackoverflow.com/a/52418378
has comment: http://stackoverflow.com/comment/91784096
favorite count: 0
tagged with: python-3.x
downvote count: 0
has answer: http://stackoverflow.com/a/52418378
has title: reticulate: Unable to configure python3
type: AnsweredQuestion
score: 3
tagged with: reticulate
type: Question
answer count: 1
tagged with: http://stackoverflow.com/tag/r
upvote count: 3
has body: I'm using reticulate R package and want to configure python3 with it, however not able to do it. I tried the following code library(reticulate) packageVersion("reticulate") # [1] ‘1.10.0.9002’ use_python(python = "/usr/bin/python", required = TRUE) py_config() # python: /usr/bin/python # libpython: /usr/lib/python2.7/config-x86_64-linux-gnu/libpython2.7.so # pythonhome: /usr:/usr # version: 2.7.15rc1 (default, Apr 15 2018, 21:51:34) [GCC 7.3.0] # numpy: /usr/lib/python2.7/dist-packages/numpy # numpy_version: 1.13.3 # # NOTE: Python version was forced by use_python function Sys.which("python3") # python3 # "/usr/bin/python3" use_python(python = "/usr/bin/python3", required = TRUE) py_config() # python: /usr/bin/python # libpython: /usr/lib/python2.7/config-x86_64-linux-gnu/libpython2.7.so # pythonhome: /usr:/usr # version: 2.7.15rc1 (default, Apr 15 2018, 21:51:34) [GCC 7.3.0] # numpy: /usr/lib/python2.7/dist-packages/numpy # numpy_version: 1.13.3 # # NOTE: Python version was forced by use_python function Any hints, please.
tagged with: python

http://stackoverflow.com/q/52300242
downvote count: 1
has comment: http://stackoverflow.com/comment/91642902
tagged with: jupyter
has comment: http://stackoverflow.com/comment/91696774
has answer: http://stackoverflow.com/a/69809251
favorite count: 0
has answer: http://stackoverflow.com/a/68024597
has answer: http://stackoverflow.com/a/73967758
has answer: http://stackoverflow.com/a/77476702
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52382663
has answer: http://stackoverflow.com/a/73465762
has answer: http://stackoverflow.com/a/64590729
upvote count: 63
linked to: http://stackoverflow.com/q/36916093
has answer: http://stackoverflow.com/a/74812501
tagged with: xelatex
has answer: http://stackoverflow.com/a/67065167
has answer: http://stackoverflow.com/a/72599981
type: Question
has answer: http://stackoverflow.com/a/55499329
score: 62
has title: Solving "500: Internal Server Error, nbconvert failed: xelatex not found in PATH"
has comment: http://stackoverflow.com/comment/91641082
answer count: 16
has body: Whenever I try to export a Jupyter notebook as a PDF I get the following error in a separate window: 500 : Internal Server Error The error was: nbconvert failed: xelatex not found on PATH, if you have not installed xelatex you may need to do so. Find further instructions at https://nbconvert.readthedocs.io/en/latest/install.html#installing-tex. I am running macOS Sierra 10.12.6. Things I have tried: Re-installing nbconvert through pip (in the Jupyter notebook) and conda (terminal) Installing xelatex for Mac Re-installing Mactex Installing pandoc (both through pip and through "conda install -c conda-forge pandoc") Running !echo $PATH Yields: /Users/ed/anaconda/bin:/Users/ed/anaconda/bin:/usr/bin:/bin:/usr/sbin:/sbin I located the directory containing xelatex as per @einsweniger suggestion here: /usr/local/texlive/bin/x86_64-darwin. I copied and pasted XeLatex into the bin directory above, and get a new error: nbconvert failed: PDF creating failed, captured latex output: warning: kpathsea: configuration file texmf.cnf not found in these directories: /Users/e/anaconda/bin:/Users/ed/anaconda/bin/share/texmf-local/web2c:/Users/ed/anaconda/bin/share/texmf-dist/web2c:/Users/ed/anaconda/bin/share/texmf/web2c:/Users/ed/anaconda/bin/texmf-local/web2c:/Users/ed/anaconda/bin/texmf-dist/web2c:/Users/ed/anaconda/bin/texmf/web2c:/Users/ed/anaconda:/Users/edefilippis/anaconda/share/texmf-local/web2c:/Users/e/anaconda/share/texmf-dist/web2c:/Users/ed/anaconda/share/texmf/web2c:/Users/ed/anaconda/texmf- This is XeTeX, Version 3.14159265-2.6-0.99999 (TeX Live 2018) (preloaded format=xelatex) kpathsea: Running mktexfmt xelatex.fmt I can't find the format file `xelatex.fmt'! I also put xelatex.fmt in the directory, but am still getting the error.
has answer: http://stackoverflow.com/a/66936771
has answer: http://stackoverflow.com/a/70903167
has answer: http://stackoverflow.com/a/78009420
has answer: http://stackoverflow.com/a/52453922
has answer: http://stackoverflow.com/a/52347865

http://stackoverflow.com/a/64226489
score: 5
downvote count: 0
type: Answer
has body: Even though Django's official starter tutorial suggests that we can use '0' as a shortcut for IP '0.0.0.0' the command runserver throws an error Error: [Errno 11001] getaddrinfo failed when the shortcut is used with it. Use python manage.py runserver 0.0.0.0:8000 to listen on all available public IPs on port 8000 instead of python manage.py runserver 0:8000
upvote count: 5
answers question: http://stackoverflow.com/q/52345050

http://stackoverflow.com/q/52360686
duplicate of: http://stackoverflow.com/q/35523635
has title: Pandas - count on specific column and get top N as list
score: 0
tagged with: pandas
has body: I got a Pandas dataframe and want to groupby and count on 'animal' column to fetch the top 3 as a list: &gt; df animal age weight length 0 hamster 5 13 2 1 hamster 14 11 4 2 cat 3 14 4 3 cat 5 6 4 4 snake 7 14 8 5 cat 4 12 5 6 hamster 11 12 9 7 snake 14 9 7 8 hamster 1 5 9 9 alligator 4 13 2 10 snake 12 7 6 11 hamster 14 10 2 12 snake 7 14 7 13 alligator 4 10 2 &gt; df.groupby("animal")['animal'].count().nlargest(3) animal hamster 5 snake 4 cat 3 Is this an efficient way and also how do I go about convert the resulting top 3 to an ordered list ie, ['hamster', 'snake', 'cat']?
has comment: http://stackoverflow.com/comment/91665737
linked to: http://stackoverflow.com/q/35523635
tagged with: python
tagged with: list
answer count: 0
has comment: http://stackoverflow.com/comment/91665898
type: UnansweredQuestion
type: Question
tagged with: performance

http://stackoverflow.com/a/54028872
downvote count: 0
answers question: http://stackoverflow.com/q/52287254
type: Answer
upvote count: 1
score: 1
has body: It can't be implemented in the static graph mode of TensorFlow without significant tradeoffs because the topology of the neural networks in the population changes. Static graphs are suited for models whose architecture doesn't change during training. However, it can be done in TensorFlow Eager or PyTorch because they support dynamic computation graphs. Check this implementation in TensorFlow Eager: https://github.com/crisbodnar/TensorFlow-NEAT

http://stackoverflow.com/a/52353819
answers question: http://stackoverflow.com/q/52353686
score: 3
downvote count: 0
type: AcceptedAnswer
upvote count: 3
type: Answer
has body: itertools.product will generate all the possible values. Instead, what you want is to pick n random characters from chrs and concatenate them: import random chrs = 'abcdef0123456789' # Change your required characters here n = 6 # Change your word length here print(''.join(random.choices(chrs, k=5)))
accepted answer of: http://stackoverflow.com/q/52353686
has comment: http://stackoverflow.com/comment/91653864

http://stackoverflow.com/a/52433887
answers question: http://stackoverflow.com/q/52416824
type: Answer
score: 1
upvote count: 1
downvote count: 0
has body: One possibility is to issue the statement "set transaction read only" as in the following code: import cx_Oracle conn = cx_Oracle.connect("cx_Oracle/welcome") cursor = conn.cursor() cursor.execute("set transaction read only") cursor.execute("insert into c values (1, 'test')") That will result in the following error: ORA-01456: may not perform insert/delete/update operation inside a READ ONLY transaction Of course you'll have to make sure that you create a Connection class that calls this statement when it is first created and after each and every commit() and rollback() call. And it can still be circumvented by calling a PL/SQL block that performs a commit or rollback. The only other possibility that I can think of right now is to create a restricted user or role which simply doesn't have the ability to insert, update, delete, etc. and make sure the application uses that user or role. This one at least is fool proof, but a lot more effort up front!

http://stackoverflow.com/q/52319436
answer count: 2
upvote count: 16
has answer: http://stackoverflow.com/a/52319500
has body: I found a strange behavior with the semicolon ";" in Python. &gt;&gt;&gt; x=20000;y=20000 &gt;&gt;&gt; x is y True &gt;&gt;&gt; x=20000 &gt;&gt;&gt; y=20000 &gt;&gt;&gt; x is y False &gt;&gt;&gt; x=20000; &gt;&gt;&gt; y=20000 &gt;&gt;&gt; x is y False Why does the first test return "True", and the others return "False"? My Python version is 3.6.5.
downvote count: 0
duplicate of: http://stackoverflow.com/q/35275026
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52319522
favorite count: 0
score: 16
linked to: http://stackoverflow.com/q/34147515
type: Question
tagged with: python
has title: Why does adding a semicolon in Python change the result?
duplicate of: http://stackoverflow.com/q/34147515

http://stackoverflow.com/q/52408910
has title: Python - Pairwise intersection of multiple lists, then sum up all duplicates
tagged with: python
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52409587
tagged with: overlap
accepted answer: http://stackoverflow.com/a/52409364
type: Question
has answer: http://stackoverflow.com/a/52409364
score: -2
tagged with: pairwise
tagged with: intersection
has body: a = [1,2,3] b = [2,3,4] c = [1,2,4] d = [1,3,6] Hi, all, I have the above lists, I'd like to show pairwise intersection/overlap (# of duplicated integers) of the each two lists like the following format. Any one knows how to achieve this? (any method would be great, but just curious is iterative/loop the only method to achieve this?) a b c d a 3 2 2 2 b 2 3 2 1 c 2 2 3 1 d 2 1 1 3 The true goal is more difficult for me, I need to sum up all duplicated number in each two list. For example, list a and list b are duplicated in number 2 and 3, thus I need 5 here. The ultimate goal is like below: a b c d a 6 5 3 4 b 5 9 6 3 c 3 6 7 1 d 4 3 1 10
upvote count: 2
downvote count: 4
possible better answer: http://stackoverflow.com/a/52409587
answer count: 3
has answer: http://stackoverflow.com/a/52409980
favorite count: 0

http://stackoverflow.com/a/52306148
upvote count: 1
score: 1
has body: Ideally module should go into your site packages. Do you see it there? If its there then check your package path. You package may be steplib, but have you checked if you are importing right package and module there. For example within your steplib folder you might have additional package and module within it. Say package is X and module is Y. Then you can import it as below. from X import Y Make sure you have init.py in your package to qualify that as a package.
answers question: http://stackoverflow.com/q/52306124
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91679566
comment on: http://stackoverflow.com/q/52362605
score: 0
type: Comment
type: QuestionComment
has text: That's a good point @DizietAsahi. The only issue is choosing the appropriate number of bins

http://stackoverflow.com/q/52340101
has answer: http://stackoverflow.com/a/52340417
score: 4
has title: Tensor.name is meaningless in eager execution
upvote count: 4
answer count: 2
has answer: http://stackoverflow.com/a/52691654
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52691654
tagged with: tensorflow
type: Question
has body: I was doing some exercise in tensorflow in google colab and trying something under eager execution. When I was practicing on the tf.case by running the code below: x = tf.random_normal([]) y = tf.random_normal([]) op = tf.case({tf.less(x,y):tf.add(x,y), tf.greater(x,y):tf.subtract(x,y)}, default = tf.multiply(x,y), exclusive = True) I have followed the example in the tf.case carefully but it just keeps reporting an attribute error: AttributeError: Tensor.name is meaningless when eager execution is enabled. I am new to python and TF as well as deep learning. Can anyone try to run the code above and help me figure out? Thank you
possible better answer: http://stackoverflow.com/a/52340417

http://stackoverflow.com/a/52347361
type: AcceptedAnswer
has body: This works perfectly: from bs4 import BeautifulSoup import requests url = 'https://www.hauntedplaces.org/state/Alabama' r = requests.get(url) soup = BeautifulSoup(r.text, 'lxml') for link in soup.select('div.description a'): print(link['href'])
has comment: http://stackoverflow.com/comment/91641037
has comment: http://stackoverflow.com/comment/91641624
type: Answer
has comment: http://stackoverflow.com/comment/91641641
accepted answer of: http://stackoverflow.com/q/52346180
answers question: http://stackoverflow.com/q/52346180
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91641078
upvote count: 1

http://stackoverflow.com/q/52360875
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/6122957
type: Question
has title: how to move page to another page in python
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52360928
has body: I'm new in python web development and not playing with some web frameworks like django in python for now. Now, is there a way like PHP (e.g. header("Location: page.target.php")) that to move the page to another in python?
has comment: http://stackoverflow.com/comment/91666109
has comment: http://stackoverflow.com/comment/91687957
tagged with: python
tagged with: python-3.x

http://stackoverflow.com/comment/115609727
has text: @Marialena I see. So what makes it different then your previous tries? The fact that it's in try/except exception? Thanks again.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52426031
type: Comment

http://stackoverflow.com/comment/91786610
has text: Have you read the error message? It appears you're trying to insert a string into a database field that is set only to take integers
comment on: http://stackoverflow.com/q/52421672
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91629721
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52341432
type: Comment
has text: Also can not be done, in general case, and the reason is the same - subclasses can override any behavior of parent.

http://stackoverflow.com/comment/91690138
score: 0
comment on: http://stackoverflow.com/a/52372410
type: AnswerComment
type: Comment
has text: pip install git+https://github.com/Anaconda-Server/anaconda-client It didn't work for me. I tried the other suggestions on the page (pip and conda install) still nothing.

http://stackoverflow.com/comment/91661182
comment on: http://stackoverflow.com/q/52358290
type: Comment
type: QuestionComment
score: 0
has text: You've defined circle as an instance method and are treating it as a class attribute, but neither really makes sense; shouldn't a circle be a *subclass* of a general shape class? Also don't override `object`.

http://stackoverflow.com/comment/91712592
type: AnswerComment
has text: I think you are trying to solve a problem (not having the exact url) which you will regret later. I'd prefer using explicit urls over a multitude of places where urls are composed. I suggest adding `get_absolute_url` to your models and add the explicit url to the table rows using the `row_attrs` attribute/argument of the django-tables2 table.
type: Comment
comment on: http://stackoverflow.com/a/52374960
score: 2

http://stackoverflow.com/comment/91689827
score: 0
type: QuestionComment
type: Comment
has text: @CharlesDuffy Thank you!!! I have been struggling to get the formatting right on StackOverflow. I will follow this advice!
comment on: http://stackoverflow.com/q/52372038

http://stackoverflow.com/comment/91589796
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52320929
has text: The except handles if there's an `IPaddress` and `DTO` key, if there isn't then it just gives "not found" if there is then the logic explained will check if it's an empty list, if it is it will give "not found", if there are values then it will do what you want. API is nothing more than a response, and generally JSON is pretty much just a simple parse.

http://stackoverflow.com/a/52326463
score: 2
answers question: http://stackoverflow.com/q/52324800
downvote count: 0
type: Answer
has body: Not sure why you think you need to do this twice: a = np.random.rand(100,3)*10 tree = KDTree(a) neighbors = tree.query_radius(a, 1) %timeit counts = tree.query_radius(a, 1, count_only = 1) 1000 loops, best of 3: 231 µs per loop %timeit counts = np.array([arr.size for arr in neighbors]) The slowest run took 5.66 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 22.5 µs per loop It's significantly faster to just find the size of the array objects in neighbors than to redo tree.query_radius
upvote count: 2

http://stackoverflow.com/a/52428691
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52428601
has body: You can try itertools.product: &gt;&gt;&gt; from itertools import product &gt;&gt;&gt; &gt;&gt;&gt; [list(i) for i in product(range(4), range(4))] [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3], [3, 0], [3, 1], [3, 2], [3, 3]]
type: Answer

classification
tags question: http://stackoverflow.com/q/52412767
tag name: classification
tags question: http://stackoverflow.com/q/52337985
tags question: http://stackoverflow.com/q/52312164
tags question: http://stackoverflow.com/q/52374311
tags question: http://stackoverflow.com/q/52343540
tags question: http://stackoverflow.com/q/52358505
tags question: http://stackoverflow.com/q/52346584
type: Tag
tags question: http://stackoverflow.com/q/52355409
tags question: http://stackoverflow.com/q/52407321

http://stackoverflow.com/q/52283976
linked to: http://stackoverflow.com/q/22937618
has comment: http://stackoverflow.com/comment/91516624
duplicate of: http://stackoverflow.com/q/22937618
accepted answer: http://stackoverflow.com/a/52284283
downvote count: 5
score: -3
has title: What does this regex mean in python?
has comment: http://stackoverflow.com/comment/91516216
type: AnsweredQuestion
favorite count: 0
type: Question
upvote count: 2
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52284283
tagged with: regex
has answer: http://stackoverflow.com/a/52284061
has body: I am new to Python and I am trying to understand this regex: pattern = r"^[A-Z0-9._%+-]+@[A-Z0-9.-]{2,200}$" What does %+- and .- mean?
has comment: http://stackoverflow.com/comment/91517249
possible better answer: http://stackoverflow.com/a/52284061

http://stackoverflow.com/q/52429844
tagged with: super
score: 1
type: Question
tagged with: closures
accepted answer: http://stackoverflow.com/a/52429982
linked to: http://stackoverflow.com/q/36993577
has title: Why does assigning to the __class__ cell break `super`?
answer count: 1
downvote count: 0
has body: I've read Why is Python 3.x&#39;s super() magic? and understand that using super or __class__ in a method will automagically create a __class__ cell variable for that method: class Demo: def meth(self): super().meth() &gt;&gt;&gt; Demo.meth.__closure__ (&lt;cell at 0x7f4572056138: type object at 0x564bda0e5dd8&gt;,) &gt;&gt;&gt; Demo.meth.__closure__[0].cell_contents &lt;class '__main__.Demo'&gt; And as far as I know, cells are used to hold closure variables and can be freely modified: def outer(): x = 3 def inner(): print(x) x = 5 return inner inner = outer() inner() # output: 5 &gt;&gt;&gt; inner.__closure__ (&lt;cell at 0x7f2183a5e138: int object at 0x7f2184600460&gt;,) But trying to reassign the value of the __class__ cell makes super throw a strange error: class Demo: def meth(self): __class__ = Demo super().meth() Demo().meth() Traceback (most recent call last): File "untitled.py", line 8, in &lt;module&gt; Demo().meth() File "untitled.py", line 6, in meth super().meth() RuntimeError: super(): __class__ cell not found Why does this happen? Why can't __class__ be reassigned like other closure variables?
linked to: http://stackoverflow.com/q/19608134
favorite count: 0
has comment: http://stackoverflow.com/comment/91803413
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52429982
type: AnsweredQuestion

http://stackoverflow.com/comment/91734427
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52279258
has text: Can anybody help me send error output to the browser? Its really annoying logging via ssh and checking error_log with 'tail -f' each time.....

http://stackoverflow.com/comment/91656462
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52344889
score: 0
has text: Your are missing the point here. I have used Anaconda in many professional projects....my question was more about the use of optimized Intel libraries and their installation from the official python package manager.

http://stackoverflow.com/comment/91736210
comment on: http://stackoverflow.com/q/52394833
score: 0
has text: At that point, there is no instance, the instance is loaded *in* the view.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52302590
answers question: http://stackoverflow.com/q/52301785
accepted answer of: http://stackoverflow.com/q/52301785
type: AcceptedAnswer
score: 0
has body: Your pattern says you're passing a slug: path("add_items/&lt;slug:pizza_name&gt;/" , views.add_items , name="add_items") But you're passing in a string. If you don't have an option to make a slug field, change the URL conf. Off-hand, I think this would work: path("add_items/&lt;pizza_name&gt;/", views.add_items, name="add_items")
type: Answer
has comment: http://stackoverflow.com/comment/91559793

http://stackoverflow.com/comment/91587682
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52319954
has text: Even the python method isn't optimised because you could be using `executemany`. I suspect your benchmark is flawed

http://stackoverflow.com/q/52390253
type: Question
has body: I have a dataset which looks like this: val 1 1 3 4 6 6 9 ... I can't load it into pandas dataframe due to it's huge size. So I aggregate data using Spark to form: val occurrences 1 2 3 1 4 1 6 2 9 1 ... and load it into pandas dataframe. "val" column is not above 100, so it doesn't take much memory. My problem is, I can't operate easily on such structure, e.g. find mean or median using pandas nor plot a boxplot with seaborn. I can do it only using explicit formulas written by me, but not ready builtin methods. Is there a pandas structure or any other way, which allows to cope with such data? For example: 1,1,3,4,6,6,9 would be: df = pd.DataFrame({'val': [1,3,4,6,9], "occurrences" : [2,1,1,2,1]}) Median is 4. I'm looking for a method to extract median directly from given df.
linked to: http://stackoverflow.com/q/26102867
tagged with: pandas
upvote count: 1
has title: How to work with aggregated data in pandas?
answer count: 1
has answer: http://stackoverflow.com/a/52391089
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91727060
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91725453

http://stackoverflow.com/a/52422539
has comment: http://stackoverflow.com/comment/91794767
score: 0
has comment: http://stackoverflow.com/comment/91808753
type: Answer
answers question: http://stackoverflow.com/q/52420470
has comment: http://stackoverflow.com/comment/91807540
has body: This should do the trick df.groupby('Country', as_index=True)['x-axis','y-axis'].apply(linregress) EDIT To plot data by categories in subplots, seaborn has intuitive syntax. import seaborn as sn sns.set(style="ticks", color_codes=True) sns.catplot(x="x-axis", y="y-axis", col="Country", aspect=.6, data=df); plt.show()
has comment: http://stackoverflow.com/comment/91793922
has comment: http://stackoverflow.com/comment/91794223
has comment: http://stackoverflow.com/comment/91794300
has comment: http://stackoverflow.com/comment/91792415
has comment: http://stackoverflow.com/comment/91795038
has comment: http://stackoverflow.com/comment/91794257

http://stackoverflow.com/comment/91676884
type: Comment
type: QuestionComment
has text: Nobody has an idea?
comment on: http://stackoverflow.com/q/52330535
score: 0

http://stackoverflow.com/q/52306261
answer count: 2
score: -2
tagged with: python
favorite count: 0
tagged with: python-3.x
has body: I want to start the indexing from 1 not 0 for list so that it helps for further coding. Is there anyway to do that? I see many posts to do the same for data frames but not for lists.
type: UnansweredQuestion
upvote count: 1
has title: Start indexing from 0 for lists in python
has comment: http://stackoverflow.com/comment/91559780
has answer: http://stackoverflow.com/a/52306364
has comment: http://stackoverflow.com/comment/91559770
has answer: http://stackoverflow.com/a/52306641
downvote count: 3
type: Question

http://stackoverflow.com/comment/91555755
has text: My test would be to enter `-1, -2, -3, -999`
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52304087

http://stackoverflow.com/q/52312211
has title: Mean of only two consecutive rows with conditional statements
type: Question
accepted answer: http://stackoverflow.com/a/52313208
tagged with: dataframe
tagged with: pandas
answer count: 1
has body: After having searched for similar questions I found out with this and this questions. Unfortunately neither of them works with me. The first works on all the columns, the second does not work on my column of True and False and returns error (I also have not understood it completely). Here's a description of the problem: I am working with a dataframe of ~54k rows. Here's an example of 24 values: +----+---------------------+---------------------+----------------------+--------------------+-------+ | | date | omegasr | omega | omegass | isday | +----+---------------------+---------------------+----------------------+--------------------+-------+ | 1 | 2012-03-27 00:00:00 | -1.5707963267948966 | -3.32335035194977 | 1.5707963267948966 | False | | 2 | 2012-03-27 01:00:00 | -1.5707963267948966 | -3.0615509641506207 | 1.5707963267948966 | False | | 3 | 2012-03-27 02:00:00 | -1.5707963267948966 | -2.799751576351471 | 1.5707963267948966 | False | | 4 | 2012-03-27 03:00:00 | -1.5707963267948966 | -2.5379521885523215 | 1.5707963267948966 | False | | 5 | 2012-03-27 04:00:00 | -1.5707963267948966 | -2.2761528007531724 | 1.5707963267948966 | False | | 6 | 2012-03-27 05:00:00 | -1.5707963267948966 | -2.014353412954023 | 1.5707963267948966 | False | | 7 | 2012-03-27 06:00:00 | -1.5707963267948966 | -1.7525540251548732 | 1.5707963267948966 | False | | 8 | 2012-03-27 07:00:00 | -1.5707963267948966 | -1.4907546373557239 | 1.5707963267948966 | True | | 9 | 2012-03-27 08:00:00 | -1.5707963267948966 | -1.2289552495565745 | 1.5707963267948966 | True | | 10 | 2012-03-27 09:00:00 | -1.5707963267948966 | -0.9671558617574253 | 1.5707963267948966 | True | | 11 | 2012-03-27 10:00:00 | -1.5707963267948966 | -0.7053564739582756 | 1.5707963267948966 | True | | 12 | 2012-03-27 11:00:00 | -1.5707963267948966 | -0.44355708615912615 | 1.5707963267948966 | True | | 13 | 2012-03-27 12:00:00 | -1.5707963267948966 | -0.1817576983599767 | 1.5707963267948966 | True | | 14 | 2012-03-27 13:00:00 | -1.570796326…
linked to: http://stackoverflow.com/q/36269323
tagged with: python
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/39477393
has answer: http://stackoverflow.com/a/52313208

http://stackoverflow.com/comment/91730326
score: 2
has text: @shafigh: Copy & paste the actual text of the error. Do not post images of text.
comment on: http://stackoverflow.com/q/52392227
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52402735
answers question: http://stackoverflow.com/q/52361174
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Core Reporting API provides paging fields in a response object so you can access the next report page based on response token https://developers.google.com/analytics/devguides/reporting/core/v4/basics#pagination Also if you're sure that your report wouldn't exceed 10 000 rows you may manually set the limit value with your request with pageSize filed: body={ 'reportRequests': [ { 'viewId': VIEW_ID, 'pageSize': 10000, 'dateRanges': [{'startDate': start , 'endDate': end }], 'metrics': [{'expression': 'ga:totalEvents'}], 'dimensions': [{ 'name': 'ga:eventLabel' }], ... } Make sure to check the description of pageSize and pageToken in the docs: https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet#ReportRequest
type: Answer
accepted answer of: http://stackoverflow.com/q/52361174

http://stackoverflow.com/a/52278705
upvote count: 9
has body: Use: animal_data = a_pd.merge(f_pd, on='name', how='left', suffixes=('_x','')).drop('food_x', axis=1) Output: animal name brand food 0 dog freddy doggys dog dog mix 1 cat dexter fish fishy fussy cat mix 2 dog lou lou i was a cow bones Or a_pd'animal','name'.merge(f_pd, how='left') Output: animal name brand food 0 dog freddy doggys dog dog mix 1 cat dexter fish fishy fussy cat mix 2 dog lou lou i was a cow bones
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52278630
type: Answer
score: 8
answers question: http://stackoverflow.com/q/52278630
downvote count: 1

http://stackoverflow.com/q/52358248
accepted answer: http://stackoverflow.com/a/52358353
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/52358293
has title: Pandas: Sum of the Max 3 Column Values in Each Row
possible better answer: http://stackoverflow.com/a/52358293
score: 6
has body: Sample data: 0 1 2 3 4 Sum_max_3 0 591949 2575703 22479693 2202865 499835 27258261 1 2705 11426 339913 5438 1016 356777 2 18 119 4162 18 0 4299 3 264 1213 14999 246 116 16476 4 0 35 1292 10 0 1337 5 0 0 1442 0 0 1442 6 0 28 5596 20 0 5644 7 0 10 102 56 0 168 8 33 0 1224 17 0 1274 9 39 198 9505 62 35 9765 I want to get the sum of the 3 columns with the largest values in the row. These are different columns for every row (Sum_max_3). I have many many columns so I need to do this automatically for all of them.
has answer: http://stackoverflow.com/a/52358353
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: python
upvote count: 6

http://stackoverflow.com/comment/91646282
type: Comment
type: AnswerComment
has text: @Modelmat, please read through the lenses of the word 'scetch'. It is intended to give you idea of what needs to be done - place \_\_init\_\_ and self accordingly.
score: 0
comment on: http://stackoverflow.com/a/52350376

http://stackoverflow.com/a/52288250
downvote count: 0
has comment: http://stackoverflow.com/comment/91714173
has body: Filter by boolean indexing with iat for select first matched value: #if always matched all values matched_categories = [df.loc[df['words'].str.contains(x), 'category'].iat[0] for x in A] print (matched_categories) ['finance', 'mercedez', 'bugatti', 'politics', 'music', 'music', 'politics'] More general solution if some value is not matched - then return not matched value: #added last aaa value A = ['loans','s-class','veyron','trump','rihana','drake','election','aaa'] matched_categories = [next(iter(df.loc[df['words'].str.contains(x),'category']),'not matched') for x in A] print (matched_categories) ['finance', 'mercedez', 'bugatti', 'politics', 'music', 'music', 'politics', 'not matched']
has comment: http://stackoverflow.com/comment/91720841
has comment: http://stackoverflow.com/comment/91708821
has comment: http://stackoverflow.com/comment/91708570
score: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91713976
upvote count: 5
accepted answer of: http://stackoverflow.com/q/52288130
type: Answer
has comment: http://stackoverflow.com/comment/91720439
answers question: http://stackoverflow.com/q/52288130
has comment: http://stackoverflow.com/comment/91714215

http://stackoverflow.com/comment/91551965
type: Comment
has text: If there are many type parameters such that the type hints are little long to cross the PEP recommended line size of 120 as in this case. What is the recommended way to split the type hint?
comment on: http://stackoverflow.com/a/52297496
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91958460
has text: Still confused.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/52416796
type: Comment

http://stackoverflow.com/q/52358507
has title: How to count certain elements of a string in a large array?
type: UnansweredQuestion
has body: I'm not sure if this is possible but I have a very large array containing dates a = ['Fri, 19 Aug 2011 19:28:17 -0000',....., 'Wed, 05 Feb 2012 11:00:00 -0000'] I'm trying to find if there is a way to count the frequency of the days and months in the array. In this case I'm trying to count strings for abbreviations of months or days (such as Fri,Mon, Apr, Jul)
upvote count: 1
score: 1
type: Question
answer count: 2
tagged with: arrays
downvote count: 0
tagged with: string
has answer: http://stackoverflow.com/a/52358578
favorite count: 0
has answer: http://stackoverflow.com/a/52360090
has comment: http://stackoverflow.com/comment/91661493
has comment: http://stackoverflow.com/comment/91661537
tagged with: count
tagged with: python

http://stackoverflow.com/comment/91761513
has text: Where do ``user_name`` and ``user_password`` come from? Does the csv file *literally* say ``['dom', 'enter password']`` or is it ``dom,enter_password``?
score: 0
comment on: http://stackoverflow.com/q/52408463
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91660934
type: QuestionComment
has text: You mean a dictionary where for example: `my_dict["ABC,_XYZ"] = [45.1976844, -69.458819]`, i.e. the letters are the keys and the two numbers are the values for that key, right?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52357733

http://stackoverflow.com/a/52376353
has body: The standard way to do this is with boolean indexing: mask = df['b'].apply(lambda x: x == [1, 2]) df[mask] returns a b 0 1 [1, 2] 1 2 [1, 2] If you are new to pandas, the new user tutorial is a good place to start and will cover questions like this.
has comment: http://stackoverflow.com/comment/91698873
downvote count: 0
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52376306

http://stackoverflow.com/q/52429435
score: 2
answer count: 0
upvote count: 2
tagged with: pip
has title: List popular version of a PyPI package
tagged with: pypi
linked to: http://stackoverflow.com/q/31020861
type: Question
has body: Is it possible to get the popular version of a PyPI package and also if possible list of different versions of a package in terms of number of downloads? I have read this discussion but I am looking for different versions of a package.
has comment: http://stackoverflow.com/comment/91804520
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/52353810
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/91657559
score: 1
has body: Ok, the code you have written, in the nicest possible way, is not good. def LinearCong (x,x2): if i == 1: randomvalue = (22695477*x+1)%2**31 else: randomvalue = (22695477*x2+1)%2**31 return randomvalue x2 = randomvalue i+=1 This function should not be placed into a while loop, or any loop for that matter. For now I would advise to forget about using functions i.e def function(): While the syntax of what you have written is somewhat correct, It is not implemented correctly in the slightest bit. Here is my interpretation of what you were trying to do in a simpler form. i =1 number_of_moves = 10 x = 10000 #problem understanding #included a randomvalue variable here becaause you want it to be assigned to var x2 #unless randomvalue is declared here the else statement would never work randomvalue = (22695477*x+1)%2**31 x2 = randomvalue while i &lt;= number_of_moves: print("") print("Choose your move number", i ,"(0 or 1)") move_selection = int(input()) if move_selection == 1: randomvalue = (22695477*x+1)%2**31 break else: #here you are asking for var x2 which would have no value unless declared above #randomvalue as a variable is created here so x2 would have nothing to refer to randomvalue = (22695477*x2+1)%2**31 #in this case, we are reassigning our already declared variable break print(randomvalue) There are big problems with this code I've written, but I don't fully understand what it is you are trying to achieve. Maybe more information about the game would help.
downvote count: 0
has comment: http://stackoverflow.com/comment/91652555
has comment: http://stackoverflow.com/comment/91652503
answers question: http://stackoverflow.com/q/52353499

http://stackoverflow.com/comment/91513756
type: QuestionComment
has text: I guess it is because the date variables are saved as mmddyy8. or mmddyy10. in sasdata file. But not sure how to fix it.
comment on: http://stackoverflow.com/q/52282538
score: 0
type: Comment

http://stackoverflow.com/comment/91629829
has text: yep, `np.nan` is a better option here.
comment on: http://stackoverflow.com/a/52338490
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52369846
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: web-scraping
has answer: http://stackoverflow.com/a/52370090
accepted answer: http://stackoverflow.com/a/52370090
type: Question
has body: I've written a script in python to scrape the description within Plot from a webpage. The thing is the description are within several p tags. There are other p tags as well which I do not wish to scrape. As soon as my script is done parsing the description of Plot, It should stop. However, my below script parses all the p tags through the end starting from Plot section. How can I limit my script to parse the description of the Plot only? This what I've written: import requests from bs4 import BeautifulSoup url = "https://en.wikipedia.org/wiki/Alien_(film)" with requests.Session() as s: s.headers={"User-Agent":"Mozilla/5.0"} res = s.get(url) soup = BeautifulSoup(res.text,"lxml") plot = [item.text for item in soup.select_one("#Plot").find_parent().find_next_siblings("p")] print(plot)
has comment: http://stackoverflow.com/comment/91684374
answer count: 2
has title: Can't limit my script to parse a specific section from a webpage
upvote count: 1
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52370223
has answer: http://stackoverflow.com/a/52370223
has comment: http://stackoverflow.com/comment/91684280

http://stackoverflow.com/q/52371125
has body: I have strings like: first = '2018-09-16 15:00:00' second = '1900-01-01 09:45:55.500597' I want to compare them. All methods I found like Convert string date to timestamp in Python requires to know the format of the string. I don't know the format of the strings (see differences between first and second) all I know is that they can be converted to timestamps. How can I convert them in order to compare them? Edit: The "largest" string that I can get is: 1900-01-01 09:45:55.500597 but I can also get: 1900-01-01 1900-01-01 09:45 1900-01-01 09:45:55 etc.. It's always YYYY-MM-DD HH-MM....
linked to: http://stackoverflow.com/q/9637838
type: Question
upvote count: 2
answer count: 2
tagged with: string
has comment: http://stackoverflow.com/comment/91686996
possible better answer: http://stackoverflow.com/a/52371244
favorite count: 0
has title: How to convert strings to TimeStamps for compare?
has comment: http://stackoverflow.com/comment/91686879
linked to: http://stackoverflow.com/q/13258554
has answer: http://stackoverflow.com/a/52371309
has comment: http://stackoverflow.com/comment/91686991
accepted answer: http://stackoverflow.com/a/52371309
tagged with: python
has answer: http://stackoverflow.com/a/52371244
score: 2
has comment: http://stackoverflow.com/comment/91686878
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/91696273
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52374807
type: QuestionComment
has text: Your question is a sort of XY problem: because you are not familiar with dictionaries you tried to do something, that is much simpler to do with a dictionary, using list of lists, leading to some serious complications. Other answers addressed this XY side of your question, suggesting the use of dictionaries. [My answer below](https://stackoverflow.com/a/52375469/2749397) takes your question at its face value and shows a simple way to solve your problem using a list of lists.

http://stackoverflow.com/comment/91645528
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52331133
has text: Please don't edit your question to add a solution or ask a new question. Post your solution as an answer to your question. A new or further question should be asked as a separate question.
type: Comment

http://stackoverflow.com/q/52291971
has comment: http://stackoverflow.com/comment/91531953
type: UnansweredQuestion
tagged with: regression
tagged with: python
has title: Least Squares SVR regression in Python
score: 4
tagged with: svm
downvote count: 1
type: Question
has body: I'm looking for a library in Python which models the Least Squares Support Vector Machines Regression algorithm (LS-SVR). I know there exists one for classification, see https://pypi.org/project/FukuML/, but I'm interested in one for the regression case. Does anyone have any ideas?
upvote count: 5
has comment: http://stackoverflow.com/comment/91532067
tagged with: least-squares
favorite count: 0
answer count: 0

http://stackoverflow.com/q/52428416
has title: Polymorphism based function returns None
type: UnansweredQuestion
tagged with: class
score: 1
tagged with: polymorphism
favorite count: 0
type: Question
upvote count: 2
has body: I've been trying to test out Polymorphism in Python and for some reason my function returns None. Can you see the reason in the following code? Thanks in advance class Animal: __name = "" __height = 0 __weight = 0 __sound = 0 def __init__(self, name, height, weight, sound): self.__name = name self.__height = height self.__weight = weight self.__sound = sound def set_name(self, name): self.__name = name def get_name(self): return self.__name def get_sound(self): return self.__sound def toString(self): return "{} is {} cm tall {} kg and says {}".format(self.__name, self.__height, self.__weight, self.__sound) cat = Animal("Whiskers", 33, 10, "Meow") -- Dog Class: class Dog(Animal): __owner = "" def __init__(self, name, height, weight, sound, owner): self.__owner = owner super(Dog, self).__init__(name, height, weight, sound) def set_owner(self, owner): self.__owner = owner def get_owner(self): return self.__owner def get_sound(self): return "Woff!" def toString(self): return "Overriden" shnitzel = Dog("Shnitzel", 10, 15, 0, "CodingCode") Testing Class: class AnimalTesting: def get_sound(self, animal): animal.get_sound() test_animals = AnimalTesting() print test_animals.get_sound(cat) The line: print test_animals.get_sound(cat) returns None Thanks again all!
tagged with: python
answer count: 1
downvote count: 1
tagged with: oop
has answer: http://stackoverflow.com/a/52428489

http://stackoverflow.com/comment/91646433
comment on: http://stackoverflow.com/q/52350171
type: Comment
type: QuestionComment
has text: You are mixing up two different types of request. The `requests` package is a pythonpackage for making HTTP requests. The Django `messages` framework requires a Django [`HttpRequest` object](https://docs.djangoproject.com/en/2.1/ref/request-response/#django.http.HttpRequest), which is a completely different thing. How exactly are you trying to render messages? Are you doing this from a view?
score: 5

http://stackoverflow.com/q/52303771
has answer: http://stackoverflow.com/a/52304316
has comment: http://stackoverflow.com/comment/91555514
type: UnansweredQuestion
answer count: 4
has answer: http://stackoverflow.com/a/52304077
tagged with: pandas
has body: I've got a JSON file that contains the parameters/options for pandas' read_excel function. I'm having trouble passing them into that function call. JSON file is structured similar to this: { "io": "~/home/test.xlsx", "sheet_name": "Sheet1", "header": 0, "usecols": 2, "engine": "xlrd", "converters": { "col1": "np.float64", "col2": "np.float64" } } And I call it in my Python script like this: import pandas as pd import numpy as np import json with open('json.json', 'r') as opened: options = json.loads(opened.read()) import_pd_df = pd.read_excel(**options) print(import_pd_df) When I have the options declared as a dictionary within the Python script and remove the double quotes that are around np.float64, the script works. But when I move the options to the JSON file, it fails while trying to parse the np.float64. The error I get is: TypeError: 'str' object is not callable Is there a way to properly format the JSON to be used as options in the function?
has answer: http://stackoverflow.com/a/52303999
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/52304231
has comment: http://stackoverflow.com/comment/91556279
tagged with: python
has title: What's the proper way to format and pass a json file as an object of parameters into a pandas function?
score: 0
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/91619659
has text: @GeorgeTsertsvadze you can force an encoding type by putting `# -*- coding: <encoding name> -*-` at the top of your python script (without the <>)
comment on: http://stackoverflow.com/q/52335920
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91551256
has text: `writer.writerow('test123')` is creating as many columns as there are characters; You need to pass a list.
comment on: http://stackoverflow.com/q/52301696
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52307414
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91562172
has comment: http://stackoverflow.com/comment/91562772
tagged with: python
has comment: http://stackoverflow.com/comment/91562138
has answer: http://stackoverflow.com/a/52307531
accepted answer: http://stackoverflow.com/a/52307531
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/91562021
has title: Python Web Scrape: Remove excess HTML tags in output. All data are from a page table, get_text and pretiffy doesnt work
type: AnsweredQuestion
has body: Newbie here. I am just practicing python all by my self. My problem is this: I am web scraping this ramdom site and i wanted to get the filename and the filedate and print them together. But excess html tags is still there and i cant get rid of them even if i am using get_text and prettify. Sorry noob question. Just needed help. Thanks in advance. This is my code: from bs4 import BeautifulSoup import requests source = requests.get('https://1337x.to/popular-tv').text soup = BeautifulSoup(source, 'lxml') tvhead = soup.find('tbody') for tv in tvhead.find_all('tr'): filename = tv.find_all('td' , class_='coll-1 name') filedate = tv.find_all('td', class_='coll-date') print(filename) print(filedate) print() output is this: [ Castle.Rock.S01E10.Romans.720p.HULU.WEB-DL.AAC2.0.H.264-NTb[eztv] ] [ 7am Sep. 12th ] [ Castle.Rock.S01E10.Romans.480p.HULU.WEB-DL.AAC2.0.H.264-BTW[ettv] ] [ 7am Sep. 12th ] [ The.Outpost.S01E08.WEB.h264-TBS[ettv] ] [ 9am Sep. 12th ] Expected output should be just the title and the date like: TV Series title Date
type: Question

http://stackoverflow.com/comment/113432886
has text: Thank you, @totalhack! Added a warning to the answer.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52412796

http://stackoverflow.com/comment/91749731
comment on: http://stackoverflow.com/a/52400246
score: 0
type: AnswerComment
has text: Glad to be of help. Can you mark this answer as accepted if you find it to be correct? (Click on the grey check mark next to the question to accept.)
type: Comment

http://stackoverflow.com/a/52418373
type: Answer
has body: Here is a tip, how to get a full path to adirectory of a file: import path script_dir = path.dirname(path.abspath(__file__)) Then you can use join or concatination to get a full path to your file or subdirectory: file_path = script_dir.join("\\the_name_of_file_or_directory") # file_path = script_dir + "\\the_name_of_file_or_directory"
score: 0
answers question: http://stackoverflow.com/q/52417927

http://stackoverflow.com/q/52341165
tagged with: python
has comment: http://stackoverflow.com/comment/91631417
has body: I am attempting to call a bash script via the subprocess Popen function passes in a for loop. My intent is that with each iteration, a new string commit from an array out is passed as an argument to the Popen command. The command invokes a bash script that outputs a text identified by the variable commit and greps certain lines from that particular text. However, I can't get the output to flush out in the Python for loop. Right now, only the grepped data from the final commit in out is being passed into my final data structure (a pandas dataframe). accuracy_dictionary = {} for commit in out: accuracy_dictionary.setdefault(commit, {}) p2 = subprocess.Popen(['~/Desktop/find_accuracies.sh', commit], encoding='utf-8', shell=True, stdout=subprocess.PIPE) outputstring = p2.stdout.read() # This part below is less critical to the problem at hand # I'm putting the data from each file in a dictionary for acc_type_line in outputstring.split('\n'): accuracy = acc_type_line.split(': ') if accuracy != ['']: acc_type = accuracy[0] value = accuracy[1] accuracy_dictionary[commit][acc_type] = float(value) acc_data = pd.DataFrame.from_dict(accuracy_dictionary).T Here is the bash script that is being called: "find_accuracies.sh": #!/bin/sh COMMIT=$1 git show $COMMIT:blahblahfolder/blahblah.txt | grep --line-buffered 'accuracy' acc_data returns a dataframe of nrows=len(out) populated by unique commits, but the value is the exact same for all rows for each acc_type For example, my output looks like this: How can I call the file "find_accuracies.sh" with the subprocess command and have it flush the unique values of each file for each commit?
has comment: http://stackoverflow.com/comment/91631401
tagged with: subprocess
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52344650
linked to: http://stackoverflow.com/q/107705
score: 0
tagged with: bash
tagged with: for-loop
answer count: 1
has title: Calling Python subprocess with variable in for loop
tagged with: io
accepted answer: http://stackoverflow.com/a/52344650

http://stackoverflow.com/q/52327107
answer count: 0
has comment: http://stackoverflow.com/comment/91666915
upvote count: 1
has comment: http://stackoverflow.com/comment/91616079
tagged with: tensorflow
tagged with: caffe
has body: I am working on Neural Style Transfer(NST). I got this github link which help me to understand Real Time NST. Now, I want to convert tensorflow code to caffe, after converting code my output is not matching. tubingen.jpg Tensorflow Code import tensorflow as tf import scipy import scipy.misc import utils import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np %matplotlib inline ##### laod and Preprocess Image image_path = "tubingen.jpg" img=mpimg.imread(image_path) plt.imshow(img) img = scipy.misc.imread(image_path) content_image = img.astype("float32") reshaped_content_height = (content_image.shape[0] - content_image.shape[0] % 4) reshaped_content_width = (content_image.shape[1] - content_image.shape[1] % 4) reshaped_content_image = content_image[:reshaped_content_height, :reshaped_content_width, :] reshaped_content_image = np.ndarray.reshape(reshaped_content_image, (1,) + reshaped_content_image.shape) ##### Run Tensorflow Code with tf.Session() as sess: img_placeholder = tf.placeholder(tf.float32, shape=reshaped_content_image.shape,name='img_placeholder') reshaped_content_image = reshaped_content_image / 255.0 weights_init = tf.Variable(tf.truncated_normal([9, 9, 3, 32], stddev=0.1, seed=1), dtype=tf.float32) net = tf.nn.conv2d(reshaped_content_image, weights_init, [1,1,1,1], padding='SAME') sess.run(tf.global_variables_initializer()) prediction = sess.run(net, feed_dict={img_placeholder:reshaped_content_image}) ####### Predict print(prediction[0].shape) prediction[0].flatten()[0:10] Tensorflow Output (768, 1024, 32) array([-0.60970634, 0.12403676, -0.35182738, 0.13260028, -0.30444232, -0.03567056, 0.58853114, -0.25797656, -0.15773779, 0.09053704], dtype=float32) Caffe Code import tensorflow as tf import transform import scipy import scipy.misc import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import caffe from caffe import layers from caffe import params caffe.set_random_seed(1) %matplotlib inline #####…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91667753
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
has title: Convert Tensorflow code to Caffe using python

http://stackoverflow.com/comment/91764438
type: AnswerComment
comment on: http://stackoverflow.com/a/52410384
type: Comment
score: 3
has text: if this is the answer, then it's a super-classic duplicate you should refrain answering to

http://stackoverflow.com/comment/91701946
has text: this code returns only the number of subjects, not the subject number attached to it.
comment on: http://stackoverflow.com/a/52378671
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52335181
has body: So I made a game and I'm trying to create an inventory for the player, and I can't change a variable called "equipped_weapon". I've tried everything and or I get an Exception or when printing the player's inventory it shows the previous weapon. I'm a beginner too so if I'm missing something please tell me. # Existing items # Need a funtion to create a random item with random stats and a random name within a certain range. yes_list = ["yes", "yeah", "sure", "why not"] add_attack = "Attack:" add_defense = "Defense:" add_HP = "HP added:" rarity = "Rarity" weapon_rusty_sword = { "Name:": "Rusty Sword", add_attack: 1, add_defense: 0, rarity: 1 } weapon_sword_wooden = { "Name:": "Wooden Sword", add_attack: 1.5, add_defense: 0, rarity: 1 } weapon_sword_iron = { "Name:": "Iron Sword", add_attack: 2, add_defense: 0, rarity: 2 } armor_chest_rusty_mail = { "Name:": "Rusty Mail", add_attack: 0, add_defense: 1, rarity: 1 } armor_legs_adventurers = { "Name:": "Adventurer's Leggings", add_attack: 0, add_defense: 1, rarity: 1 } armor_legs_rash_leggings = { "Name:": "Rash Leggings", add_attack: 0, add_defense: 0.5, rarity: 1 } armor_head_rusty_cap = { "Name:": "Rusty Cap", add_attack: 0, add_defense: 0.5, rarity: 1 } potion_hp = { "Name:": "HP Potion,", add_HP: 4 } class Person: #global equipped_weapon equipped_weapon = weapon_rusty_sword ui_equipped_weapon = {"Equipped Weapon: {}".format(weapon_rusty_sword): ""} equipped_armor = { "Head Protection:": {"Name": armor_head_rusty_cap["Name:"], "Defense": armor_head_rusty_cap[add_defense]}, "Chest Protection:": {"Name": armor_chest_rusty_mail["Name:"], "Defense": armor_chest_rusty_mail[add_defense]}, "Legs Protection:": {"Name": armor_legs_rash_leggings["Name:"], "Defense": armor_legs_rash_leggings[add_defense]}, } ATTACK = 1 + equipped_weapon[add_attack] DEFENSE = 1 HP = 20 gold = 10 potions = {"Potions: ": [potion_hp["Name:"]]} ui_gold = {"Gold: ": gold} def __init__(self): self.name = "Cavalex" inv = [ equipped_armor, ui_equipped_wea…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91618383
score: 1
has title: Can't change class variable with outside function in Python
has comment: http://stackoverflow.com/comment/91617520
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52335255
tagged with: class
answer count: 1
downvote count: 0
tagged with: variables
favorite count: 0
accepted answer: http://stackoverflow.com/a/52335255
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/q/52385810
answer count: 4
tagged with: python-3.x
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52386060
has answer: http://stackoverflow.com/a/52387040
type: Question
has answer: http://stackoverflow.com/a/52386973
has title: Python Compare Two Lists of Objects and Append to One List
has body: I am trying to compare two lists of objects to see if a persons name matches in both lists. list1 = ('Name', 'Kilometers Driven') list1 example = ('John Doe', 500),('Jane Doe', 200) list2 = ('Id','Name','Kilometers Walked','Total Events') list2 example = (2,'Joe Doe',20,2),(3,'Frank Kelly',32,4) If the person is present in both lists I want to take the Kilometers Driven and add it to the second list for that person. Thanks for the help
possible better answer: http://stackoverflow.com/a/52386552
downvote count: 0
has answer: http://stackoverflow.com/a/52386552
has comment: http://stackoverflow.com/comment/91715764
favorite count: 0
has answer: http://stackoverflow.com/a/52386060

http://stackoverflow.com/a/52415536
type: Answer
has comment: http://stackoverflow.com/comment/91807214
score: 2
has body: parsing without the py_mini_racer. I could not install py_mini_racer on my python 3.7 d = { "body": '{\n carrierName = "AT&amp;T";\n dateRecieved = "2018-08-07 20:29:56 +0000";\n \n}' } def parseD(d): import re def makeD(l): # make dict from 2 element list return dict(s.strip().replace('"','') for s in l) finalD = {} for di in [makeD(x) for x in [s.split('=') for s in re.findall(r'(\w+\s+=.*);', list(d.values())[0])]]: finalD.update(di) return finalD parseD(d) {'carrierName': 'AT&amp;T', 'dateRecieved': '2018-08-07 20:29:56 +0000'} d = parseD(d) d['carrierName'] 'AT&amp;T' d['dateRecieved'] '2018-08-07 20:29:56 +0000'
downvote count: 0
answers question: http://stackoverflow.com/q/52414766
has comment: http://stackoverflow.com/comment/91805760
upvote count: 2
has comment: http://stackoverflow.com/comment/91805237

http://stackoverflow.com/a/52382116
upvote count: 2
has body: But the age verification "window" is just a div that gets hidden when you press the button, not a real separate window: &lt;div class="age-check-modal" id="age-check-modal"&gt; You can use the browser's Network tab in developer tools to see that no new info is uploaded or sent when you press the button. So everything is already loaded when you request a page. The "popup" is not even a popup, just an element whose display is changed to none when you click the button. So Scrapy doesn't really care what's meant to be displayed as long as all html is loaded. If the elements are loaded, they are accessible. Or have you seen some information being unavailable without pressing the button? You should inspect the html code more to see what each website does, this might make your scraping tasks easier. Edit: After inspecting the original html you can see the following: &lt;div class="products-list"&gt; &lt;div class="products-container-block"&gt; &lt;div class="products-container"&gt; &lt;div id="hits" class='row'&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; You can also see a lot of JS script tags. The browser element inspector shows us the following: The ::before part gives away that this was manipulated by JS, as you cannot do this with simple CSS. See Granitosaurus' answer for details on this. What this means is that you need to somehow execute the arbitrary JS code on those pages. So you either need a solution with Scrapy, or just use Selenium, as many do, and as you already have.
has comment: http://stackoverflow.com/comment/91709476
has comment: http://stackoverflow.com/comment/91708555
has comment: http://stackoverflow.com/comment/91718370
has comment: http://stackoverflow.com/comment/91709524
answers question: http://stackoverflow.com/q/52380423
has comment: http://stackoverflow.com/comment/91710387
has comment: http://stackoverflow.com/comment/91709799
downvote count: 0
has comment: http://stackoverflow.com/comment/91711184
type: Answer
has comment: http://stackoverflow.com/comment/91710169
has comment: http://stackoverflow.com/comment/91710304
has comment: http://stackoverflow.com/comment/91710352
has comment: http://stackoverflow.com/comment/91710523
score: 2

http://stackoverflow.com/comment/91757423
comment on: http://stackoverflow.com/q/52405435
has text: you gotta debug it buddy try to send hardcode value first if that works Employee_data.query.filter_by(team = 1001).all()
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91546342
has text: @jpp - Great! I didn't find that question while I was searching before asking. Thanks.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52299082

http://stackoverflow.com/q/52314401
has title: xgboost.plot_tree: binary feature interpretation
has comment: http://stackoverflow.com/comment/131626992
downvote count: 0
answer count: 1
tagged with: xgboost
favorite count: 0
has comment: http://stackoverflow.com/comment/91586818
upvote count: 25
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79216115
tagged with: python
score: 25
has body: I've built an XGBoost model and seek to examine the individual estimators. For reference, this was a binary classification task with discrete and continuous input features. The input feature matrix is a scipy.sparse.csr_matrix. When I went to examine an individual estimator, however, I found difficulty interpreting the binary input features, such as f60150 below. The real-valued f60150 in the bottommost chart is easy to interpret - its criterion is in the expected range of that feature. However, the comparisons being made for the binary features, <X> < -9.53674e-07 doesn't make sense. Each of these features is either 1 or 0. -9.53674e-07 is a very small negative number, and I imagine this is just some floating-point idiosyncrasy within XGBoost or its underpinning plotting libraries, but it doesn't make sense to use that comparison when the feature is always positive. Can someone help me understand which direction (i.e. yes, missing vs. no corresponds to which true/false side of these binary feature nodes? Here is a reproducible example: import numpy as np import scipy.sparse from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import CountVectorizer from xgboost import plot_tree, XGBClassifier import matplotlib.pyplot as plt def booleanize_csr_matrix(mat): ''' Convert sparse matrix with positive integer elements to 1s ''' nnz_inds = mat.nonzero() keep = np.where(mat.data > 0)[0] n_keep = len(keep) result = scipy.sparse.csr_matrix( (np.ones(n_keep), (nnz_inds[0][keep], nnz_inds[1][keep])), shape=mat.shape ) return result ### Setup dataset res = fetch_20newsgroups() text = res.data outcome = res.target ### Use default params from CountVectorizer to create initial count matrix vec = CountVectorizer() X = vec.fit_transform(text) # Whether to "booleanize" the input matrix booleanize = True # Whether to, after "booleanizing", convert the data type to match what's returned by `vec.fit_transform(text)` to_int = True if booleanize and to_int: …
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/91576833
type: Question

http://stackoverflow.com/q/52426055
has body: I have made a small project. User first logs in then he is redirected to the home page. But if a user has not logged in then also that homepage is opening if we paste the url of that home page. I have tried many things given on net but it's not working. This is my urls.py from django.conf.urls import url from django.contrib import admin from blog import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.login, name='login'), url(r'^register/$', views.register, name='register'), url(r'^home/$', views.home, name='home'), url(r'^javaq/$', views.javaq, name='javaq'), url(r'^javar/$', views.javar, name='javar'), url(r'^csq/$', views.csq, name='csq'), url(r'^csr/$', views.csr, name='csr'), url(r'^cq/$', views.cq, name='cq'), url(r'^cr/$', views.cr, name='cr'), url(r'^cppq/$', views.cppq, name='cppq'), url(r'^cppr/$', views.cppr, name='cppr'), url(r'^pythonq/$', views.pythonq, name='pythonq'), url(r'^pythonr/$', views.pythonr, name='pythonr'), url(r'^mini/$', views.mini, name='mini'), ] This is my view.py from django.shortcuts import render from .models import logininfo,CSTEST,CTEST,CPPTEST,JAVATEST,PYTHONTEST,result from django.http import HttpResponse from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.views.decorators.cache import cache_control import datetime def login(request): if request.method=="POST": user_name=request.POST.get("username") sid=request.POST.get("sid") password=request.POST.get("password") article = logininfo() article.user_name = user_name article.sid = sid article.password = password article.save() return render(request,'login.html') def home(request): if request.method=="POST": sid=request.POST.get("sid") password=request.POST.get("password") request.session['sd'] = sid user_obj=logininfo.objects.filter(sid=sid,password=password) if user_obj.count()==0: return HttpResponse("Sorry wrong password try again") return render(request,'home.html') def register(request): return re…
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/91795148
has answer: http://stackoverflow.com/a/52428417
has answer: http://stackoverflow.com/a/52426762
has comment: http://stackoverflow.com/comment/91796284
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52426732
possible better answer: http://stackoverflow.com/a/52428417
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91796401
accepted answer: http://stackoverflow.com/a/52426762
type: Question
has title: page opening even if not logged in, Django

http://stackoverflow.com/q/52329396
has comment: http://stackoverflow.com/comment/91607230
has title: Taking triple integral for a function with more than 3 parameters using tplquad
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91606373
has answer: http://stackoverflow.com/a/52331757
tagged with: scipy
linked to: http://stackoverflow.com/q/1708510
type: Question
accepted answer: http://stackoverflow.com/a/52331757
score: 0
answer count: 1
has body: I want to take this triple integral over func(eps,e,p,M): The integral is over eps, e and p and the code is here: def Probability(eps,e,p,M): prob=eps*e*(e**2-p**2)*function(M) return prob a=0 b=np.inf def gfun(): return 0.25 def hfun(): return 0.5 def qfun(e): return -e def rfun(e): return 3*e-1 def n(M): n=integrate.tplquad(Probability, 0, np.inf,gfun,hfun,qfun,rfun,args=(M)) return n but I get this error: integrate() argument after * must be an iterable, not float I don't know what's the problem, and the other question: is the ordering of parameters in function Probability True?

http://stackoverflow.com/comment/91754438
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52405340
score: 1
has text: What `stdout`? Did you forget to include something?

http://stackoverflow.com/comment/91764251
score: 0
type: Comment
type: QuestionComment
has text: @CharlesDuffy, i don't understood `mkdir $'$(rm -rf ~)\'$(rm -rf ~)\''` you conveyed into your comment , I'm agreed opening `shell=True` code becomes extremely likely to be vulnerable as shell provides the ability to pipe things around without buffering them in memory, and allows a malicious user to chain additional commands after a legitimate command is run.
comment on: http://stackoverflow.com/q/52408841

http://stackoverflow.com/tag/csv
type: Tag
tags question: http://stackoverflow.com/q/52428921
tags question: http://stackoverflow.com/q/52325100
tags question: http://stackoverflow.com/q/52334568
tags question: http://stackoverflow.com/q/52368027
tags question: http://stackoverflow.com/q/52303121
tags question: http://stackoverflow.com/q/52289386
tags question: http://stackoverflow.com/q/52290160
tags question: http://stackoverflow.com/q/52393787
tags question: http://stackoverflow.com/q/52307209
tags question: http://stackoverflow.com/q/52408463
tags question: http://stackoverflow.com/q/52381020
tags question: http://stackoverflow.com/q/52372635
tags question: http://stackoverflow.com/q/52345338
tag name: csv
tags question: http://stackoverflow.com/q/52333724
tags question: http://stackoverflow.com/q/52285705
tags question: http://stackoverflow.com/q/52279296
tags question: http://stackoverflow.com/q/52362750
tags question: http://stackoverflow.com/q/52410452
tags question: http://stackoverflow.com/q/52387812
tags question: http://stackoverflow.com/q/52415754
tags question: http://stackoverflow.com/q/52299780
tags question: http://stackoverflow.com/q/52325044
tags question: http://stackoverflow.com/q/52285092
tags question: http://stackoverflow.com/q/52415167
tags question: http://stackoverflow.com/q/52312736
tags question: http://stackoverflow.com/q/52314621
tags question: http://stackoverflow.com/q/52297210
tags question: http://stackoverflow.com/q/52364306
tags question: http://stackoverflow.com/q/52396638
tags question: http://stackoverflow.com/q/52293475
tags question: http://stackoverflow.com/q/52400408
tags question: http://stackoverflow.com/q/52296365
tags question: http://stackoverflow.com/q/52277410
tags question: http://stackoverflow.com/q/52335750
tags question: http://stackoverflow.com/q/52328800
tags question: http://stackoverflow.com/q/52280487
tags question: http://stackoverflow.com/q/52273375
tags question: http://stackoverflow.com/q/52411267
tags question: http://stackoverflow.com/q/52428845
tags question: http://stackoverflow.com/q/52417661
tags question: http://stackoverflow.com/q/52342504
tags question: http://stackoverflow.com/q/52395550
tags question: http://stackoverflow.com/q/52301123
tags question: http://stackoverflow.com/q/52386872
tags question: http://stackoverflow.com/q/52338946
tags question: http://stackoverflow.com/q/52287070
tags question: http://stackoverflow.com/q/52272345
tags question: http://stackoverflow.com/q/52361128
tags question: http://stackoverflow.com/q/52309986
tags question: http://stackoverflow.com/q/52315920
tags question: http://stackoverflow.com/q/52370166
tags question: http://stackoverflow.com/q/52401433
tags question: http://stackoverflow.com/q/52426360
tags question: http://stackoverflow.com/q/52371578
tags question: http://stackoverflow.com/q/52387191
tags question: http://stackoverflow.com/q/52359159
tags question: http://stackoverflow.com/q/52387440
tags question: http://stackoverflow.com/q/52297890
tags question: http://stackoverflow.com/q/52426808
tags question: http://stackoverflow.com/q/52331628
tags question: http://stackoverflow.com/q/52282194
tags question: http://stackoverflow.com/q/52335593
tags question: http://stackoverflow.com/q/52390457
tags question: http://stackoverflow.com/q/52295024
tags question: http://stackoverflow.com/q/52356732
tags question: http://stackoverflow.com/q/52393904
tags question: http://stackoverflow.com/q/52378570
tags question: http://stackoverflow.com/q/52319008
tags question: http://stackoverflow.com/q/52428025
tags question: http://stackoverflow.com/q/52332756
tags question: http://stackoverflow.com/q/52271619
tags question: http://stackoverflow.com/q/52369437
tags question: http://stackoverflow.com/q/52371378
tags question: http://stackoverflow.com/q/52359827
tags question: http://stackoverflow.com/q/52353566
tags question: http://stackoverflow.com/q/52296825
tags question: http://stackoverflow.com/q/52381242
tags question: http://stackoverflow.com/q/52301696

http://stackoverflow.com/q/52364483
has comment: http://stackoverflow.com/comment/91673076
has body: The problem is the string in the db has '\' in it and I want to read this string ,modify it and save it back to the DB. SQL automatically removes any escape characters . So \ is removed from the string and saved in the DB. eg: config = '{"Settings":"{\"On\"}"}' sql= "INSERT INTO file (configuration, id) VALUES('%s', '%s')" % (config, cursor.execute(sql) and in the DB {"Settings":"{"On"}"} is saved.
has comment: http://stackoverflow.com/comment/91673460
has comment: http://stackoverflow.com/comment/91673057
tagged with: python
has comment: http://stackoverflow.com/comment/91673287
has title: I want to get a string from MySQL db and modify it and save it back to the DB
has comment: http://stackoverflow.com/comment/91673082
answer count: 0
type: UnansweredQuestion
score: 0
tagged with: django
has comment: http://stackoverflow.com/comment/91673342
type: Question
tagged with: mysql

http://stackoverflow.com/q/52424172
has comment: http://stackoverflow.com/comment/91826388
accepted answer: http://stackoverflow.com/a/52585008
score: 0
has title: Keras and TensorFlow: I'm getting an InvalidArgumentError
has comment: http://stackoverflow.com/comment/92104725
answer count: 1
tagged with: keras
has comment: http://stackoverflow.com/comment/91791709
has comment: http://stackoverflow.com/comment/91825644
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91826562
tagged with: anaconda
has body: I am just starting out with Keras and TensorFlow and I have started by following the tutorial (https://machinelearningmastery.com/tutorial-first-neural-network-python-keras/) Unfortunately when I run the finished code (I'm using Anaconda - not sure if this is relevant) I get the following error: Here is the code: # Create your first MLP in Keras from keras.models import Sequential from keras.layers import Dense import numpy # fix random seed for reproducibility numpy.random.seed(7) # load pima indians dataset dataset = numpy.loadtxt("D:\Applications\Python Apps\pima-indians-diabetes.csv", delimiter=",") # split into input (X) and output (Y) variables X = dataset[:,0:8] Y = dataset[:,8] # create model model = Sequential() model.add(Dense(12, input_dim=8, activation='relu')) model.add(Dense(8, activation='relu')) model.add(Dense(1, activation='sigmoid')) # Compile model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # Fit the model model.fit(X, Y, epochs=150, batch_size=10) # evaluate the model scores = model.evaluate(X, Y) print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100)) Here is the error: InvalidArgumentError: Input to reshape is a tensor with 10 values, but the requested shape has 0 [[Node: training/Adam/gradients/loss/dense_3_loss/Mean_1_grad/Reshape = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _class=["loc:@training/Adam/gradients/loss/dense_3_loss/Mean_1_grad/truediv"], _device="/job:localhost/replica:0/task:0/device:GPU:0"](training/Adam/gradients/loss/dense_3_loss/mul_grad/Sum, training/Adam/gradients/loss/dense_3_loss/Mean_1_grad/DynamicStitch/_75)]] Here is an image of the entire thing which is a bit easier to read - https://i.sstatic.net/s7qUU.jpg If someone is able to assist with this I would really appreciate it. Thanks Glen
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/91791742
has answer: http://stackoverflow.com/a/52585008

http://stackoverflow.com/comment/91565808
comment on: http://stackoverflow.com/a/52299569
score: 0
type: AnswerComment
has text: Basically is there anything I need to add to your code? As I copied it but throws errors
type: Comment

http://stackoverflow.com/a/52378693
type: Answer
answers question: http://stackoverflow.com/q/52378615
score: 0
has body: Try with this my_subjects = {"Autumn": {37315:"Data", 34567:"Sci"}, "Spring": {23456:"Eng", 45879:"Math"}} for season, data in my_subjects.items(): print("\n Autumn Subject Numbers", season) for key in data: print(key)
has comment: http://stackoverflow.com/comment/91701991

http://stackoverflow.com/comment/91639473
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52346652
has text: See [here](http://pandas.pydata.org/pandas-docs/stable/cookbook.html#pivot)
score: 0

http://stackoverflow.com/q/52371378
answer count: 1
has comment: http://stackoverflow.com/comment/91687359
accepted answer: http://stackoverflow.com/a/52371492
has body: I am having difficulty with presenting the top 5 scores from a csv file. This is my current code: def leaderboards(): with open('userData.csv', 'r') as data: reader = csv.reader(data) for idx, row in enumerate(reader): print('{} | {} | {}'.format(str(idx), row[0], row[2])) This is what I currently get: &gt;&gt;&gt; leaderboards() 0 | Name | Score 1 | Ryan | 3 2 | Liam | 12 3 | Steve | 3 4 | Donald | 3 5 | Alan | 3 6 | Harry | 1 There are two main elements that I would like to implement but don't know how. They are to sort the score so that the highest score is at the top, and to limit the number of players the leaderboards show to 5. Current code: with open('userData.csv', 'r') as data: reader = csv.DictReader(data) newList = sorted(reader, key=lambda row: row['Score'], reverse=False)[0:5] print (' | Name | Score') for i, r in enumerate(newList): print('{} | {} | {}'.format(str(i), r['Name'], r['Score'])) Current result: | Name | Score 0 | Liam | 12 1 | Harry | 2 2 | Ryan | 3 3 | Steve | 3 4 | Donald | 3 It works for the most part, however, the 2 is higher up than the 3. I'm not really sure why but maybe you might realise something. Once again, thank you so much and I'm sorry that I'm just asking so much but this is out of my league in terms of coding knowledge. :D
score: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3348460
type: Question
has title: Top 5 scores using csv
has answer: http://stackoverflow.com/a/52371492

http://stackoverflow.com/comment/91644442
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52349597
has text: `df = df['Net Profit'].groupby(df['release_year']).nlargest(10).mean()`

http://stackoverflow.com/q/52346652
has title: How to create a pivot in anaconda python in below format from given data using pivot _table
score: 0
has comment: http://stackoverflow.com/comment/91645967
has answer: http://stackoverflow.com/a/52677538
answer count: 1
tagged with: pivot-table
type: UnansweredQuestion
has body: This is the input data want to create pivot in below format: I need output of pivot table in below format:
has comment: http://stackoverflow.com/comment/91639473
tagged with: python
tagged with: anaconda
type: Question

http://stackoverflow.com/comment/91618171
has text: Do you run this code by using Development Endpoints such as Zeppelin Notebook?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52322381

http://stackoverflow.com/comment/91518377
type: QuestionComment
comment on: http://stackoverflow.com/q/52284965
has text: `dataVar` is an invalid attribute in HTML. Make it `data-var` and get its value with `var numberVariable = element.dataset.var` instead of `var numberVariable = element.getAttribute('dataVar');`
score: 0
type: Comment

http://stackoverflow.com/comment/91612729
type: AnswerComment
score: 0
type: Comment
has text: Interesting! Does the `_` have a special meaning?
comment on: http://stackoverflow.com/a/52333005

http://stackoverflow.com/comment/91653065
comment on: http://stackoverflow.com/a/52354233
type: AnswerComment
score: 0
type: Comment
has text: That's exactly what I was looking for. Thank you!

http://stackoverflow.com/q/52353954
answer count: 2
has answer: http://stackoverflow.com/a/52361530
tagged with: histogram
has body: Having the following Data Frame: name value count total_count 0 A 0 1 20 1 A 1 2 20 2 A 2 2 20 3 A 3 2 20 4 A 4 3 20 5 A 5 3 20 6 A 6 2 20 7 A 7 2 20 8 A 8 2 20 9 A 9 1 20 ---------------------------------- 10 B 0 10 75 11 B 5 30 75 12 B 6 20 75 13 B 8 10 75 14 B 9 5 75 I would like to pivot the data, grouping each row by the name value, then create columns based on the value &amp; count columns aggregated into bins. Explanation: I have 10 possible values, range 0-9, not all the values are present in each group. In the above example group B is missing values 1,2,3,4,7. I would like to create an histogram with 5 bins, ignore missing values and calculate the percentage of count for each bin. So the result will look like so: name 0-1 2-3 4-5 6-7 8-9 0 A 0.150000 0.2 0.3 0.2 0.150000 1 B 0.133333 0.0 0.4 0.4 0.066667 For example for bin 0-1 of group A the calculation is the sum of count for the values 0,1 (1+2) divided by the total_count of group A name 0-1 0 A (1+2)/20 = 0.15 I was looking into hist method and this StackOverflow question, but still struggling with figuring out what is the right approach.
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52361530
tagged with: pivot-table
possible better answer: http://stackoverflow.com/a/52354190
tagged with: python
has answer: http://stackoverflow.com/a/52354190
type: AnsweredQuestion
type: Question
linked to: http://stackoverflow.com/q/50540256
has title: Python - Pivot and create histograms from Pandas column, with missing values

http://stackoverflow.com/a/52293182
accepted answer of: http://stackoverflow.com/q/52293079
has comment: http://stackoverflow.com/comment/91540597
has comment: http://stackoverflow.com/comment/91538679
has comment: http://stackoverflow.com/comment/91540132
has comment: http://stackoverflow.com/comment/91538628
has comment: http://stackoverflow.com/comment/91539381
has comment: http://stackoverflow.com/comment/91538702
has comment: http://stackoverflow.com/comment/91537749
score: 0
has comment: http://stackoverflow.com/comment/91538801
has body: I believe need assign list back: datadf['new'] = matchlist Or use list comprehension instead loop solution: datadf = pd.DataFrame({ 'ItemName': ['as','asds','as','aa','ssb','ab','sb'] }) print (datadf) ItemName 0 as 1 asds 2 as 3 aa 4 ssb 5 ab 6 sb #convert to list is not necessary L = datadf['ItemName'] datadf['new'] = [difflib.get_close_matches(i, L, 3, 0.6) for i in L] print (datadf) ItemName new 0 as [as, as, asds] 1 asds [asds, as, as] 2 as [as, as, asds] 3 aa [aa] 4 ssb [ssb, sb] 5 ab [ab] 6 sb [sb, ssb] EDIT: If need check between 2 columns of different DataFrames: datadf = pd.DataFrame({ 'Fruits':pd.Categorical(['apple','orange', 'apple', 'pineapple']), 'Juices':pd.Categorical(['apple','orange smash','apple1','milkshake']), 'Year': pd.Categorical([2011, 2011, 2012, 2012])}) print (datadf) Fruits Juices Year 0 apple apple 2011 1 orange orange smash 2011 2 apple apple1 2012 3 pineapple milkshake 2012 data_df_splitone = datadf[(datadf['Year'] == 2011)].copy() data_df_splittwo = datadf[(datadf['Year'] == 2012)].copy() L1 = data_df_splitone['Juices'] L2 = data_df_splittwo['Juices'] data_df_splitone['new'] = [difflib.get_close_matches(i, L2, 3, 0.6) for i in L1] print (data_df_splitone) Fruits Juices Year new 0 apple apple 2011 [apple1] 1 orange orange smash 2011 []
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91538239
has comment: http://stackoverflow.com/comment/91566921
answers question: http://stackoverflow.com/q/52293079
has comment: http://stackoverflow.com/comment/91540948
type: Answer
has comment: http://stackoverflow.com/comment/91538651
has comment: http://stackoverflow.com/comment/91538021

http://stackoverflow.com/comment/91741909
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52398598
has text: At PC now. Can you give a representative input and output that I can test against please?

http://stackoverflow.com/q/52325949
has answer: http://stackoverflow.com/a/55846923
has answer: http://stackoverflow.com/a/56492696
type: Question
has answer: http://stackoverflow.com/a/71160178
has answer: http://stackoverflow.com/a/62466685
has answer: http://stackoverflow.com/a/56730223
has answer: http://stackoverflow.com/a/61750899
has answer: http://stackoverflow.com/a/53319648
score: 10
has answer: http://stackoverflow.com/a/52326093
has answer: http://stackoverflow.com/a/61303935
upvote count: 11
answer count: 19
has comment: http://stackoverflow.com/comment/91598900
has answer: http://stackoverflow.com/a/71853428
has answer: http://stackoverflow.com/a/61718229
has answer: http://stackoverflow.com/a/70662850
downvote count: 1
has body: Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given scores. Store them in a list and find the score of the runner-up. Input Format The first line contains N. The second line contains an array of N integers each separated by a space. I found this solution n = int(input()) nums = map(int, input().split()) print(sorted(list(set(nums)))[-2]) can someone explain me why we are using map function here ? Also if someone can explain me this line : nums = map(int, input().split())
has title: Find the Runner-Up Score >> Explanation
favorite count: 0
has answer: http://stackoverflow.com/a/65068142
has answer: http://stackoverflow.com/a/53958550
has comment: http://stackoverflow.com/comment/91598877
has answer: http://stackoverflow.com/a/52326030
tagged with: python
has answer: http://stackoverflow.com/a/62636347
has answer: http://stackoverflow.com/a/53577515
has answer: http://stackoverflow.com/a/67849322
linked to: http://stackoverflow.com/q/10973766
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52326075

http://stackoverflow.com/comment/91726917
comment on: http://stackoverflow.com/a/52390527
score: 1
type: AnswerComment
type: Comment
has text: Thanks this worked for me. Only difference is the ```right=DF2'datetime','col2'```

http://stackoverflow.com/comment/91577735
score: 1
has text: So need subtract all columns values without first?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52311583

http://stackoverflow.com/a/52348664
downvote count: 1
answers question: http://stackoverflow.com/q/52348454
has body: Easiest way is to use a multiline regex along with its sub() method and giving it a count of 1: import re r = re.compile("^replace me$", re.M) s = """ #replace me #replace me replace me replace me """ r.sub("replaced!", s, 1) Gives #replace me #replace me replaced! replace me Online demo here
score: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/91630911
comment on: http://stackoverflow.com/q/52342217
type: Comment
type: QuestionComment
has text: Have you tried iterating through the outer `List`, and for each element (in this case, the inner `List`), apply a way to reverse? This way the scope of the problem becomes simpler -- how to make `[1, 2, 3]` as `[3, 2, 1]`, and repeat from first element of the outer List to the last.
score: 0

http://stackoverflow.com/q/52411745
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91767331
has comment: http://stackoverflow.com/comment/91780217
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91767926
has comment: http://stackoverflow.com/comment/91807555
has title: Python: subclasses with the same sets of methods v.s. multiple dispatches
has body: I was writing a class with the set of methods that work as expected for both numpy arrays and scipy.sparse matrices. I then realized that all my methods starts with an if-statement to check if the underlying matrix is dense or sparse e.g. def standardize_columns(self): if self.issparse(): … else: … def multiply_by_diagonal_matrix(self, diag_vector, from_='right'): if self.issparse(): … else: … It seems somewhat silly (and not pythonic) to have such if-else statements everywhere. I have so far found two possible ways around this: 1. create an abstract class with pre-specified set of methods and make subclasses (https://pythonspot.com/polymorphism/, https://docs.python.org/3/library/abc.html), or 2. create a set of functions with multiple dispatch (https://github.com/mrocklin/multipledispatch). Which of the two approach (or any other) would be better and why?
tagged with: polymorphism
has comment: http://stackoverflow.com/comment/91768951
has comment: http://stackoverflow.com/comment/91767278
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52412164
tagged with: scipy

http://stackoverflow.com/a/52357929
score: 2
downvote count: 0
has body: That isn’t possible with XlsxWriter. You can only close and save the file once.
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52357675
has comment: http://stackoverflow.com/comment/91660530

http://stackoverflow.com/comment/91703655
has text: what is the code (for rename movie files)?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52378386
score: 0

http://stackoverflow.com/q/52359432
downvote count: 0
answer count: 1
has body: I have a model where I am using Enum for choices: class Agreement(models.Model): class Category(enum.Enum): EULA = 0 PROVIDER = 1 created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) category = models.IntegerField( choices=[(choice.name, choice.value) for choice in Category]) title = models.CharField(max_length=128) content = models.TextField() I register it using simple admin site registration: admin.site.register(Agreement) When admin site renders the object it doesn't allow me to save it? Has anyone had a similar issue?
favorite count: 0
has answer: http://stackoverflow.com/a/52359497
upvote count: 2
tagged with: django
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: django-orm
accepted answer: http://stackoverflow.com/a/52359497
type: Question
tagged with: django-admin
tagged with: django-models
has title: Django choices in Admin when Enum is used

http://stackoverflow.com/q/52402783
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/64758608
has answer: http://stackoverflow.com/a/52410860
tagged with: pickle
has title: Pickle class definition in module with dill
tagged with: python
linked to: http://stackoverflow.com/q/32363312
downvote count: 0
tagged with: dill
has answer: http://stackoverflow.com/a/52425223
upvote count: 8
type: Question
answer count: 3
has body: My module contains a class which should be pickleable, both instance and definition I have the following structure: MyModule |-Submodule |-MyClass In other questions on SO I have already found that dill is able to pickle class definitions and surely enough it works by copying the definition of MyClass into a separate script and pickling it there, like this: import dill as pickle class MyClass(object): ... instance = MyClass(...) with open(..., 'wb') as file: pickle.dump(instance, file) However, it does not work when importing the class: Pickling: from MyModule.Submodule import MyClass import dill as pickle instance = MyClass(...) with open(.., 'wb') as file: pickle.dump(instance, file) Loading: import dill as pickle with open(..., 'rb') as file: instance = pickle.load(file) &gt;&gt;&gt; ModuleNotFoundError: No module named 'MyModule' I think the class definition is saved by reference, although it should not have as per default settings in dill. This is done correctly when MyClass is known as __main__.MyClass, which happens when the class is defined in the main script. I am wondering, is there any way to detach MyClass from MyModule? Any way to make it act like a top level import (__main__.MyClass) so dill knows how to load it on my other machine? Relevant question: Why dill dumps external classes by reference no matter what
favorite count: 0
score: 8
tagged with: python-3.x
tagged with: serialization
linked to: http://stackoverflow.com/q/69859147
linked to: http://stackoverflow.com/q/31884640

http://stackoverflow.com/comment/91602660
type: Comment
has text: Thanks Hari, I tried that before and I thought I wrote something wrong. I'm still getting the same error. I really don't get it :( `TypeError: list indices must be integers or slices, not str`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52326257

http://stackoverflow.com/comment/91803459
type: QuestionComment
comment on: http://stackoverflow.com/q/52429508
type: Comment
has text: That is certainly cmd.exe my friend.
score: 0

http://stackoverflow.com/a/52422267
score: 0
type: Answer
has body: Stackoverflow is for code related queries. I suggest you try some code and share your results and your problems before posting anything here. That being said, you can start with object detection tutorials like this and then do tracking with sort. Many pre trained models are available that include the cars class so you won't even need to train a new model.
answers question: http://stackoverflow.com/q/52422060

http://stackoverflow.com/comment/91681943
has text: @ggdx yes I tried login:index too, but the result is negative
type: Comment
comment on: http://stackoverflow.com/q/52368607
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91795900
comment on: http://stackoverflow.com/q/52426319
has text: you can print the available keys with seen.keys() to get a better understanding of where the error is occurring :)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91583672
type: Comment
type: QuestionComment
has text: Windows does not allow `:` in file names
comment on: http://stackoverflow.com/q/52318123
score: 0

http://stackoverflow.com/q/52353800
tagged with: python-standalone
has body: I've recently started writing python scripts and I'm still newbie to the language. I'm stuck with a problem: My script requires the 'requests' library(and the other packages that comes with it when using pip) to be installed by pip for the script to work(and some folders like the 'database', where I store a sqlite3 file) and I need to install the script in a lot of machines, that have different Ubuntu versions, therefore different Python versions, and I want my script to run 'standalone' and to not have to install/update Python, pip and the 'requests' package every time I setup the script in a new machine. I'm developing in a virtualenv on my machine that is currently setuped with all the necessary packages to run the script. Can I make a make a 'copy' of my virtualenv so it can be moved with my Python script to other computers, including my database folder, without having to install/update python and pip on every machine, instead using this standalone version of python? All the machines are Linux. I already tried to copy my virtualenv to my project folder but the virtualenv crashed when I tried running my script using the python interpreter inside it in the shebang line, even when using the --relocatable argument, so I guess it's not the case. I've also tried using PyInstaller, no success.
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52353901
upvote count: 1
tagged with: python-requests
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91652423
accepted answer: http://stackoverflow.com/a/52353901
has title: Python script "standalone"
has comment: http://stackoverflow.com/comment/91652440
score: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/91654231
comment on: http://stackoverflow.com/q/52352118
type: Comment
type: QuestionComment
has text: @stovfl I am but still requests catches some of urlib3 exepction and raise them as request exceptions. None of the docs in the lib explains how to solve this. If you have a solution I'll be happy to hear
score: 0

http://stackoverflow.com/comment/91624817
type: Comment
comment on: http://stackoverflow.com/q/52338795
score: 3
type: QuestionComment
has text: Did you mean `sentence.replace(...)`. The error is telling you that `replace` is just a `str`, which it is because you defined it on line `3`.

http://stackoverflow.com/comment/91666424
type: Comment
has text: Thank you for the detailed explanation!! Now I'm clear about that XD !!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52360943

http://stackoverflow.com/comment/91832997
score: 0
type: AnswerComment
has text: Where exactly? I put it in my `FilterView` but it didn't work.
comment on: http://stackoverflow.com/a/52444764
type: Comment

http://stackoverflow.com/q/52336811
type: Question
has body: Right now I have the following model called model1: Layer (type) Output Shape Param # Connected to ================================================================================================== input_3 (InputLayer) (None, 101, 101, 1) 0 __________________________________________________________________________________________________ up_sampling2d_2 (UpSampling2D) (None, 202, 202, 1) 0 input_3[0][0] __________________________________________________________________________________________________ zero_padding2d_36 (ZeroPadding2 (None, 256, 256, 1) 0 up_sampling2d_2[0][0] __________________________________________________________________________________________________ conv2d_3 (Conv2D) (None, 256, 256, 3) 6 zero_padding2d_36[0][0] __________________________________________________________________________________________________ u-resnet34 (Model) (None, 256, 256, 1) 24453178 conv2d_3[0][0] __________________________________________________________________________________________________ input_4 (InputLayer) (None, 1, 1, 1) 0 __________________________________________________________________________________________________ cropping2d_2 (Cropping2D) (None, 202, 202, 1) 0 u-resnet34[1][0] __________________________________________________________________________________________________ lambda_3 (Lambda) (None, 1, 1, 1) 0 input_4[0][0] __________________________________________________________________________________________________ max_pooling2d_2 (MaxPooling2D) (None, 101, 101, 1) 0 cropping2d_2[0][0] __________________________________________________________________________________________________ lambda_4 (Lambda) (None, 101, 101, 1) 0 lambda_3[0][0] __________________________________________________________________________________________________ concatenate_10 (Concatenate) (None, 101, 101, 2) 0 max_pooling2d_2[0][0] lambda_4[0][0] __________________________________________________________________________________________________ conv2d_14 (Conv2D) (None, 101, …
has comment: http://stackoverflow.com/comment/91625374
has comment: http://stackoverflow.com/comment/91626055
has comment: http://stackoverflow.com/comment/91625816
has comment: http://stackoverflow.com/comment/91625695
has comment: http://stackoverflow.com/comment/91621407
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/91625840
accepted answer: http://stackoverflow.com/a/52337379
tagged with: python
type: AnsweredQuestion
score: 2
has title: How can I expose the layers of a child model from the summary of the parent model in keras?
has answer: http://stackoverflow.com/a/52337379
upvote count: 2

http://stackoverflow.com/comment/91663416
type: Comment
type: QuestionComment
has text: If you just need a simple linear Ordinary Least Squares regression then you can do that with [`np.polyfit`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html), and then you can 'predict' the result with [`np.polyval`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyval.html#numpy.polyval)
score: 3
comment on: http://stackoverflow.com/q/52359471

http://stackoverflow.com/a/52294681
has comment: http://stackoverflow.com/comment/91537207
upvote count: 2
has body: You already got all td elements. You can iterate through all of them: for td in soup.find_all('td'): if td.text.startswith('http'): print(td, td.text) # https://test.com https://test.com If you want, you can be a bit less explicit by searching for the td element with "highlight" class and find the next sibling, but this is more error prone in case the DOM will change: for td in soup.find_all('td', {'class': 'highlight'}): print(td.find_next_sibling()) # https://test.com
has comment: http://stackoverflow.com/comment/91537076
answers question: http://stackoverflow.com/q/52294620
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/91600599
type: Comment
has text: I didn't wrote that. If you want to repeat the `grep`, add a third entry to the `command` dictionary.
comment on: http://stackoverflow.com/a/52307563
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91602768
comment on: http://stackoverflow.com/q/52326071
score: 0
type: Comment
type: QuestionComment
has text: I think you need to explain exactly what you are trying to do. "Sending a request to Django from the server itself" doesn't sound like something you should do.

http://stackoverflow.com/comment/91637140
type: Comment
comment on: http://stackoverflow.com/a/52345480
has text: Thanks a lot! I now have a course where Python is considered as prior knowledge but I had never coded before :)
score: 0
type: AnswerComment

http://stackoverflow.com/q/52278105
tagged with: xgboost
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91505581
tagged with: python
has comment: http://stackoverflow.com/comment/91505466
answer count: 0
has comment: http://stackoverflow.com/comment/91506553
has comment: http://stackoverflow.com/comment/91505109
has comment: http://stackoverflow.com/comment/91504620
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/91504881
type: Question
tagged with: time-series
has body: I'm using XGBoost for a time series forecasting problem. I've been performing gridsearch with time series cross validation. Oddly, the gridsearch is repeatedly converging on a high number of trees and minimum child weight. Here's my code scaler = StandardScaler() X_scaled = scaler.fit_transform(X) tscv = TimeSeriesSplit(n_splits=3, max_train_size = 1500) model = xgboost.XGBRegressor() grid_search = GridSearchCV(model, param_grid = param_grid, cv = tscv.split(X_scaled), n_jobs = -1, scoring = 'explained_variance', verbose=True) grid_search.fit(X_scaled, y) print (grid_search.best_params_) My parameter grid is param_grid = {'learning_rate': [0.01, 0.1], 'max_depth': [4,8,12], 'min_child_weight': [3,5,10,20,35,50], 'subsample': [0.5, 0.75], 'colsample_bytree': [0.5, 0.75], 'n_estimators': [100, 300], } The gridsearch converges on {'colsample_bytree': 0.5, 'learning_rate': 0.01, 'max_depth': 12, 'min_child_weight': 50, 'n_estimators': 300, 'subsample': 0.5} Are there any clear reasons as to why the tree depth and min child weight are both so high? Unfortunately I cannot release my dataset. I'm just looking for general reasons as to why this might be occuring, and if the converged parameters are reasonable.
has comment: http://stackoverflow.com/comment/91504316
has title: XGBoost converging on high depth and child weight
tagged with: hyperparameters
score: 0
has comment: http://stackoverflow.com/comment/91507456

http://stackoverflow.com/comment/91628182
score: 0
type: AnswerComment
has text: Thanks a lot, @John Rotenstein, This is working exactly in a fine way. The owners= self, helped me a lot to get images owned by me. I need to know the difference between boto3.client('ec2') VS boto3.resource('ec2'). how it works
type: Comment
comment on: http://stackoverflow.com/a/52339387

http://stackoverflow.com/a/52338452
accepted answer of: http://stackoverflow.com/q/52338342
answers question: http://stackoverflow.com/q/52338342
has body: You can find the CAGR directly by applying formula cagr = (df2/df)**(1/5) - 1 Age Census_Tract_001 Census_Tract_002 0 NaN 0.319508 -0.09712 To find the in between dfs, define a function f = lambda c: c + c*cagr And compound it by call it using function composition &gt;&gt;&gt; f(df) Age Census_Tract_001 Census_Tract_002 0 NaN 131.950791 541.728271 &gt;&gt;&gt; f(f(df)) Age Census_Tract_001 Census_Tract_002 0 NaN 174.110113 489.115866
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91624944
upvote count: 2
has comment: http://stackoverflow.com/comment/91624922
type: Answer
score: 2

http://stackoverflow.com/q/52364406
favorite count: 0
linked to: http://stackoverflow.com/q/44652776
has comment: http://stackoverflow.com/comment/91673039
has comment: http://stackoverflow.com/comment/91673737
tagged with: curve-fitting
tagged with: python
has comment: http://stackoverflow.com/comment/91673275
type: AnsweredQuestion
has body: I'm trying to do a linear combination of different temperature sensors and curve it them with a strain sensor. What I did is I can fit one temperature sensor with one strain sensor. But I don't know how to do linear combination of different temperature sensors over one strain sensor. Here is my attempt: def process_data_curve_fitting(temperature, strain): #mean_T = (temperature[[i for i in temperature.columns.tolist() if str(i)[:2] == 'TW']].mean(axis=1)) print("process data") T1 = temperature['T1'].tolist() T2 = temperature['T2'].tolist() T3 = temperature['T3'].tolist() T4 = temperature['T4'].tolist() T5 = temperature['T5'].tolist() T6 = temperature['T6'].tolist() T7 = temperature['T7'].tolist() T8 = temperature['T8'].tolist() T9 = temperature['T9'].tolist() T10 = temperature['T10'].tolist() df = pd.DataFrame(list(zip(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10))) mean_T = df.mean(axis = 1) print(mean_T) Sensor_Names = [ 'W_A1', 'W_A2', 'W_F1', 'W_F2', 'W_F4', 'W_S1', 'W_S2', 'W_S3', 'W_S4', 'W_KF1', 'W_KF2', 'W_KF3', 'W_KF4', 'W_DB1', 'W_DB2'] ys = [] for i in range(len(strain)): cof = np.polyfit(mean_T, strain[i], 2) poly = np.polyval(cof, mean_T) ys.append(poly) print (cof) print (poly) for i in range(len(strain)): fig = plt.figure() plt.scatter(mean_T, strain[i],s=0.1) # fig.savefig(r'c:\\ahmed\\'+Sensor_Names[i]+'.png') plt.plot(mean_T, ys[i], color='r') fig.savefig(r'c:\\ahmed\\'+"Curve_fitting__" + Sensor_Names[i]+'.png',dpi=300) plt.ylabel('strain' + Sensor_Names[i]) plt.xlabel('temperature') Please look at the equation
score: 1
has comment: http://stackoverflow.com/comment/91673199
upvote count: 1
has answer: http://stackoverflow.com/a/52386157
accepted answer: http://stackoverflow.com/a/52386157
type: Question
has comment: http://stackoverflow.com/comment/91714857
has comment: http://stackoverflow.com/comment/91673103
has comment: http://stackoverflow.com/comment/91673147
has comment: http://stackoverflow.com/comment/91673243
tagged with: pandas
answer count: 1
downvote count: 0
has title: Linear combination of temperature sensors curve fitting
has comment: http://stackoverflow.com/comment/91688695

http://stackoverflow.com/comment/91542760
type: AnswerComment
has text: That's fantastic! Thanks
type: Comment
comment on: http://stackoverflow.com/a/52297352
score: 1

http://stackoverflow.com/comment/115809675
score: 0
type: AnswerComment
has text: [I can't install pyaudio on Windows? How to solve “error: Microsoft Visual C++ 14.0 is required.”?](https://stackoverflow.com/a/57731053/5033247)
type: Comment
comment on: http://stackoverflow.com/a/57319569

http://stackoverflow.com/comment/91589585
type: AnswerComment
type: Comment
score: 0
has text: it's not though because that's not taking into consideration all of the salary outputs before it.it's supposed to double the salary every day so that the output would be: day 1: 0.03 cents day 2: 0.09 cents day 3: 0.27 etc... and then at the end add all of those values up
comment on: http://stackoverflow.com/a/52321032

http://stackoverflow.com/comment/91557418
score: 0
type: Comment
type: QuestionComment
has text: I am building a bit map index of person vs videos, where I have a lot of videos(more than 1000) for a limited set of people (about 100). So each cell represents whether that person appears in the video(1) or not(0). This table is stored in a file. Now when I want to know if two people appear in a video together or not, then I read the corresponding row for those two people and do a bitwise 'AND' operation to get the result and locate the indices where there is '1'. So do this bitwise 'AND', I need to convert the binary list into integers first and then compute the result.
comment on: http://stackoverflow.com/q/52303407

http://stackoverflow.com/a/55894811
answers question: http://stackoverflow.com/q/52403414
downvote count: 1
score: -1
has body: This happened to me too. I moved anaconda from a drive to another. It turns out on installation the path is written into the exe file for tensorborad.exe and you can fix it by opening the file into notepad or any other text editor then finding and replacing faulty path into correct path
upvote count: 0
type: Answer

http://stackoverflow.com/comment/91690521
has text: @Nand it works thank you very much.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52372635

http://stackoverflow.com/comment/91762898
comment on: http://stackoverflow.com/q/52409379
type: Comment
has text: You should create an issue here and CLI team will help you to figure out what is happening: https://github.com/Azure/azure-cli/issues. Also, you don't confirm how you installed the CLI is the first place. Pip? Howebrew? Something else? Please update your post with installation details.
score: 0
type: QuestionComment

http://stackoverflow.com/a/52354219
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52354098
type: Answer
has body: You are using the MLPClassifier model which (as its name suggests) is designed for classification problem where you have fixed number of possible target values in the training data (for example identifying if an image contains a cat or a dog). But you are working with a regression problem, where the model needs to predict the Concrete compressive strength which is a quantitative variable. You should try to use the MLPRegressor model instead of MLPClassifier
accepted answer of: http://stackoverflow.com/q/52354098

http://stackoverflow.com/q/52349380
tagged with: python
has answer: http://stackoverflow.com/a/52349711
has body: here is my problem, I have this very simple graph Or as I'm writing my script in python, here it is as a dict (child as key and parent as value): {'b':'a', 'c':'a', 'd':'c', 'e':'c'} Now, I know that with the wonderful toposort module I can unroll this graph into a list so that visiting each node in the list starting from the first will respect the graph relationship between parents and children. It works great and in this case I would get: ['a', 'b', 'c', 'd', 'e'] Now the problem is that in my case each node has also a priority which tells me what node I should visit BEFORE provided that all its parents have already been visited. Here is an example dict for priorities (key is node, value is priority for which the greater is the most important): {'a':1, 'b':2, 'c':3, 'e':4, 'd':1} So I would like to have an algorithm which spits out something like this: ['a', 'c', 'e', 'b', 'd'] Or any other equivalent solution (well, I'm guessing solutions will not be unique, but I may be wrong). In other words, I need something that take the relationship between nodes as first thing to be considered to define the chain and then the priority. Is there anything out here I can use? Or how can I leverage the toposort module in python to achieve this? Thanks in advance!
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52349711
has title: Topological sort of a graph with prioritized nodes
type: Question
tagged with: graph
score: 0
answer count: 1

http://stackoverflow.com/q/52322812
type: Question
has title: Appending values in rows into new columns?
answer count: 1
has body: I have this data in a CSV: first, middle, last, id, fte Alexander,Frank,Johnson,460700,1 Ashley,Jane,Smith,470000,.5 Ashley,Jane,Smith,470000,.25 Ashley,Jane,Smith,470000,.25 Steve,Robert,Brown,460001,1 I need to find the rows of people with the same ID numbers, and then combine the FTEs of those rows into the same line. I'll also need to add 0s for the rows that don't have duplicates. For example (using data above): first, middle, last, id, fte1, fte2, fte3, fte4 Alexander,Frank,Johnson,460700,1,0,0,0 Ashley,Jane,Smith,470000,.5,.25,.25,0 Steve,Robert,Brown,460001,1,0,0,0 Basically, we're looking at the jobs people hold. Some people work one 40-hour per week job (1.0 FTE), some work two 20-hour per week jobs (.5 and .5 FTEs), some might work 4 10-hour per week jobs (.25, .25, .25, and .25 FTEs), and some may have other combinations. We only get one row of data per employee, so we need the FTEs on the same row. This is what we have so far. Right now, our current code only works if they have two FTEs. If they have three or four, it just overwrites them with the last two (so if they have 3, it gives us 2 and 3. If they have 4, it gives us 3 and 4). f = open('data.csv') csv_f = csv.reader(f) dataset = [] for row in csv_f: dictionary = {} dictionary["first"] = row[2] dictionary["middle"] = row[3] dictionary["last"] = row[4] dictionary["id"] = row[10] dictionary["fte"] = row[12] dataset.append(dictionary) def is_match(dict1, dict2): return (dict1["id"] == dict2["id"]) def find_match(dictionary, dict_list): for index in range(0, len(dict_list)): if is_match(dictionary, dict_list[index]): return index return -1 def process_data(dataset): result = [] for index in range(1, len(dataset)): data_dict = dataset[index] match_index = find_match(data_dict, result) id = str(data_dict["id"]) if match_index == -1: result.append(data_dict) else: (result[match_index])["fte2"] = data_dict["fte"] return result f.close() for row in process_data(dataset): print(row) Any help would be extrem…
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/52322965
type: UnansweredQuestion

http://stackoverflow.com/q/52424112
downvote count: 1
has comment: http://stackoverflow.com/comment/91790950
score: 1
linked to: http://stackoverflow.com/q/28033882
type: Question
has answer: http://stackoverflow.com/a/52424335
has answer: http://stackoverflow.com/a/52424355
has answer: http://stackoverflow.com/a/52424502
has comment: http://stackoverflow.com/comment/91791346
answer count: 3
tagged with: python
linked to: http://stackoverflow.com/q/4998629
tagged with: nlp
has title: how to extract head nouns from a phrase in python?
favorite count: 0
has body: I am doing a keyphrase classification task and for this i am working with the head noun extraction from keyphrases in python. The little help available on internet is not of good use. i am struggling with this.
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/a/53309454
score: 2
has body: In my experience, if you do not have the codec or a different version of the codec installed in your OS, with which one you are trying to save your video can provoke it crashes. Even if this piece of code is in C++, it could help you: // Load input video or camera stream cv::VideoCapture cap(0); if (!cap.isOpened()) { std::cout &lt;&lt; "!!! Input video could not be opened" &lt;&lt; std::endl; return 1; } float fps = cap.get(CV_CAP_PROP_FPS); int cols = cap.get(CV_CAP_PROP_FRAME_WIDTH); int rows = cap.get(CV_CAP_PROP_FRAME_HEIGHT); // Setup output video cv::VideoWriter video("output.avi", cap.get(CV_CAP_PROP_FOURCC), fps, cv::Size(cols,rows),true)
answers question: http://stackoverflow.com/q/52411916
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/comment/91653983
comment on: http://stackoverflow.com/a/52354544
type: AnswerComment
score: 0
type: Comment
has text: Thanks again @neverwalkaloner. This removes the error - it now returns the data from `ReleasesAll` but it still doesnt return the data from `audiolinks`.

http://stackoverflow.com/comment/91536002
comment on: http://stackoverflow.com/q/52293709
score: 0
type: Comment
type: QuestionComment
has text: Also, if this is a GUI-related question, screenshots help as well a lot

http://stackoverflow.com/q/52383948
has comment: http://stackoverflow.com/comment/91712058
has answer: http://stackoverflow.com/a/52384356
accepted answer: http://stackoverflow.com/a/52384356
upvote count: 5
has comment: http://stackoverflow.com/comment/91712099
possible better answer: http://stackoverflow.com/a/62475362
has comment: http://stackoverflow.com/comment/91714439
tagged with: python
type: AnsweredQuestion
score: 3
tagged with: fractions
has comment: http://stackoverflow.com/comment/91712420
has comment: http://stackoverflow.com/comment/91714533
type: Question
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/91712833
has answer: http://stackoverflow.com/a/62475362
has comment: http://stackoverflow.com/comment/91712247
has comment: http://stackoverflow.com/comment/91712087
tagged with: python-3.6
tagged with: recurring
has comment: http://stackoverflow.com/comment/91712358
has body: I want to do a program in python (3.6.5) that tell the length of e.g. 1/7. The output should be for this example something like: "length: 6, repeated numbers: 142857". I got this so far: n = int(input("numerator: ")) d = int(input("denominator: ")) def t(n, d): x = n * 9 z = x k = 1 while z % d: z = z * 10 + x k += 1 print ("length:", k) print ("repeated numbers:", t) return k, z / d t(n, d)
has comment: http://stackoverflow.com/comment/91713236
has title: Calculate period length of recurring decimal fraction
has comment: http://stackoverflow.com/comment/91712551
favorite count: 0

http://stackoverflow.com/a/52386701
has body: The python module binsascii is most likely what you need. Example: &gt;&gt;&gt; import os &gt;&gt;&gt; salt = os.urandom(16) &gt;&gt;&gt; import binascii &gt;&gt;&gt; binascii.b2a_hex(salt) '9df7cc8d135fb9f115e166e140153217' &gt;&gt;&gt; binascii.a2b_hex(binascii.b2a_hex(salt)) '\x9d\xf7\xcc\x8d\x13_\xb9\xf1\x15\xe1f\xe1@\x152\x17' A number of other encodings are also available.
accepted answer of: http://stackoverflow.com/q/52386589
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52386589
score: 1
upvote count: 1

http://stackoverflow.com/a/52329983
type: Answer
score: 2
downvote count: 0
has body: Try this for zfile in zipfiles: print("Opening: {}".format(zfile)) try: with ZipFile(zfile, 'r') as testzip: print(testzip.comment) # comment for entire zip l = testzip.infolist() #list all files in archive for finfo in l: # per file/directory comments print("{}:{}".format(finfo.filename, finfo.comment)) except BadZipFile: print("Bad file:", zfile) you may need to import BadZipFile exception from zipfile You can also use catch-all exception but I would discourage it as it may hide other errors there: except Exception as e: print(e)
upvote count: 2
answers question: http://stackoverflow.com/q/52329793
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91607782
has comment: http://stackoverflow.com/comment/91607667
accepted answer of: http://stackoverflow.com/q/52329793
has comment: http://stackoverflow.com/comment/91606845
has comment: http://stackoverflow.com/comment/91607148

http://stackoverflow.com/q/52319836
answer count: 2
favorite count: 0
possible better answer: http://stackoverflow.com/a/52319982
tagged with: django
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52319847
downvote count: 2
type: Question
has body: Undefined name 'cleaned_data' What am I doing wrong here? code: def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = cleaned_data['first_name'] user.last_name = cleaned_data['last_name'] user.email = cleaned_data['email'] if commit: user.save() return user
has answer: http://stackoverflow.com/a/52319982
has title: Undefined name in function
has answer: http://stackoverflow.com/a/52319847
upvote count: 0
score: -2

http://stackoverflow.com/a/52279566
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52279479
answers question: http://stackoverflow.com/q/52279479
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91507427
has body: You can use a list comprehension with zip and list slicing: res = [[j, i, k] for i, j, k in zip(mylist[::2], mylist[1::2], mylist[2::2])] [['green', 'red', 'blue'], ['yellow', 'blue', 'orange'], ['purple', 'orange', 'black']] Or use list with zip directly for a list of tuples: res = list(zip(mylist[1::2], mylist[::2], mylist[2::2])) If you want a list of lists with similar syntax, you can use map: res = list(map(list, zip(mylist[1::2], mylist[::2], mylist[2::2])))
type: Answer

http://stackoverflow.com/q/52324005
tagged with: python-3.x
has body: I have the following function: def median(list): if list ==[]: return [] elif len(list)==1: return list[0] else: list= sorted(list) length= len(list)+1 median=0 if length%2==0: median= (list[length/2]+list[length/2-1])/2 else: median= list[length-1/2] return median It gives me an error when I call it like this: median([4, 5, 5, 4]) resulted in an error: list index out of range
possible better answer: http://stackoverflow.com/a/52324046
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52324046
has answer: http://stackoverflow.com/a/52324135
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52325432
has comment: http://stackoverflow.com/comment/91595141
type: Question
downvote count: 0
has title: python code to calculate median for a list as input
answer count: 3
has answer: http://stackoverflow.com/a/52325432
has comment: http://stackoverflow.com/comment/91595493
favorite count: 0

http://stackoverflow.com/comment/91681774
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52368700
has text: try using `//b`. Using `.//b` makes no sense. `//b` should bring ou `` elements with everything inside them.

http://stackoverflow.com/a/61462859
score: 2
answers question: http://stackoverflow.com/q/52407736
has body: It's an old question, but what you did is not working because you get the wrong gunicorn logger. The access log is not on error logger but on access logger (cf https://github.com/benoitc/gunicorn/blob/b2dc0364630c26cc315ee417f9c20ce05ad01211/gunicorn/glogging.py#L61) Define your class like you did : class NoReadyFilter(logging.Filter): def filter(self, record): return record.getMessage().find('/api/v1/ready') == -1 Then in the main entrypoint of your app : if __name__ != "__main__": gunicorn_logger = logging.getLogger("gunicorn.access") gunicorn_logger.addFilter(NoReadyFilter()) gunicorn run command : gunicorn --access-logfile=- --log-file=- -b 0.0.0.0:5000 entrypoint:app
downvote count: 0
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/116417035

http://stackoverflow.com/a/52418403
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52418270
has body: Technically you don't need regex for that (you can use set() for instance): &gt;&gt;&gt; # Assume your string is in the variable called "text" &gt;&gt;&gt; result = set(text.split('\n')) &gt;&gt;&gt; result {'bo_7', 'bo_3', 'bo_1', 'bo_6', 'bo_5', 'bo_8', 'bo_9', 'bo_2', 'bo_4', 'bo_10'} Anyway, the issue with your regex is that bo_1 is also matching bo_10, so it will be seen as a duplicate by the regex. You can solve it using word boundaries to ensure that the full 'word' is tested for a match: \b(bo_\d+)\b(?![\s\S]*\b\1\b) regex101 demo

sqlalchemy
tags question: http://stackoverflow.com/q/52323700
tags question: http://stackoverflow.com/q/52429508
tags question: http://stackoverflow.com/q/52347763
tags question: http://stackoverflow.com/q/52333598
tags question: http://stackoverflow.com/q/52414291
tags question: http://stackoverflow.com/q/52395405
tags question: http://stackoverflow.com/q/52393064
tags question: http://stackoverflow.com/q/52417059
tags question: http://stackoverflow.com/q/52341148
tags question: http://stackoverflow.com/q/52422883
tags question: http://stackoverflow.com/q/52408644
tags question: http://stackoverflow.com/q/52399907
tags question: http://stackoverflow.com/q/52327311
tags question: http://stackoverflow.com/q/52391072
tags question: http://stackoverflow.com/q/52336707
tags question: http://stackoverflow.com/q/52328299
tags question: http://stackoverflow.com/q/52364876
tags question: http://stackoverflow.com/q/52419849
tags question: http://stackoverflow.com/q/52411968
tags question: http://stackoverflow.com/q/52336432
tags question: http://stackoverflow.com/q/52419170
tag name: sqlalchemy
tags question: http://stackoverflow.com/q/52392182
tags question: http://stackoverflow.com/q/52330033
tags question: http://stackoverflow.com/q/52414329
tags question: http://stackoverflow.com/q/52393021
tags question: http://stackoverflow.com/q/52312593
tags question: http://stackoverflow.com/q/52274882
tags question: http://stackoverflow.com/q/52302999
tags question: http://stackoverflow.com/q/52330925
tags question: http://stackoverflow.com/q/52272170
tags question: http://stackoverflow.com/q/52405435
tags question: http://stackoverflow.com/q/52366251
tags question: http://stackoverflow.com/q/52298269
tags question: http://stackoverflow.com/q/52375238
type: Tag
tags question: http://stackoverflow.com/q/52306960

http://stackoverflow.com/q/52384406
linked to: http://stackoverflow.com/q/47155569
has body: So I have a data:number matching lists. I change the length of each list to 32~. than I plot: list_of_datetimes = [s for (i, s) in enumerate(list_of_datetimes) if (i % (len(list_of_datetimes) &gt;&gt; 5)) == 0] y_axis = [s for (i, s) in enumerate(y_axis) if (i % (len(y_axis) &gt;&gt; 5)) == 0] dates = mdates.datestr2num(list_of_datetimes) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y')) #plt.gca().xaxis.set_major_locator(mdates.DayLocator()) plt.style.use('seaborn-whitegrid') plt.gcf().autofmt_xdate() plt.plot_date(dates, y_axis, linestyle='solid', marker='None') And I don't understand why chart is breaking: chart_breaks
duplicate of: http://stackoverflow.com/q/47155569
tagged with: matplotlib
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/52384658
score: 0
has title: matplotlib plot_dates break the line when yaxis integer change length
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/126095749
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52407348
type: AnswerComment
has text: There is another scenario, where something like enterprise TLS inspection is causing the hash to change by delivering a slightly different version of the file. This is known to happen with Sophos, specifically, though other vendors are not immune.

http://stackoverflow.com/comment/91648781
comment on: http://stackoverflow.com/a/52351581
score: 0
type: AnswerComment
has text: This is not the right usage `accounts = discover_page.select('a', {'class': 'author track'})['href'] print(len(accounts))` Check the doc - https://www.crummy.com/software/BeautifulSoup/bs4/doc/
type: Comment

http://stackoverflow.com/comment/91505009
score: 0
type: QuestionComment
type: Comment
has text: have you tried `df['Date'].date()`?
comment on: http://stackoverflow.com/q/52278464

http://stackoverflow.com/q/52331614
upvote count: 1
tagged with: celery
type: Question
tagged with: pika
has comment: http://stackoverflow.com/comment/91611517
has comment: http://stackoverflow.com/comment/91610772
has comment: http://stackoverflow.com/comment/91611475
has comment: http://stackoverflow.com/comment/98023829
tagged with: amqp
downvote count: 0
has comment: http://stackoverflow.com/comment/130983417
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/91612103
has title: Python Celery : ValueError: too many values to unpack (expected 3)
type: UnansweredQuestion
tagged with: python
has body: I'm trying to publish a message to Celery via RabbitMQ using the python library Pika The message hits RabbitMQ but blows up when Celery handles it. I have no issues when I implement the same concept using .Net or Php, but I just can't seem to get it to work using python. Connect to RabbitMQ connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() Publishing a message: def sendMsg(): #generate a unique ID rd = random.Random() rd.seed(0) id = uuid.UUID(int=rd.getrandbits(128)) msg = '{"msg":"What if i fall? but son, what if you fly"}' hrds = {'task': 'task.hello', 'id':str(id)} properties = pika.BasicProperties(content_type='application/json',headers= hrds) channel.basic_publish(exchange='celery',routing_key='celery',body=msg,properties=properties) Celery task handler @app.task def hello(msg): print("Your msg is: "+msg) Celery Error: [2018-09-14 06:44:01,091: ERROR/MainProcess] Pool callback raised exception: ValueError('too many values to unpack (expected 3)',) Traceback (most recent call last): File "/home/devops/Documents/celery/workers/lib/python3.6/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'chord' During handling of the above exception, another exception occurred: &gt; Traceback (most recent call last): File &gt; "/home/devops/Documents/celery/workers/lib/python3.6/site-packages/billiard/pool.py", &gt; line 1747, in safe_apply_callback &gt; fun(*args, **kwargs) File "/home/devops/Documents/celery/workers/lib/python3.6/site-packages/celery/worker/request.py", &gt; line 366, in on_failure &gt; self.id, exc, request=self, store_result=self.store_errors, File "/home/devops/Documents/celery/workers/lib/python3.6/site-packages/celery/backends/base.py", &gt; line 157, in mark_as_failure &gt; if request.chord: File "/home/devops/Documents/celery/workers/lib/python3.6/site-packages/kombu/utils/objects.py", &gt; line 44, in __get__ &gt; value = obj.__dict__[self…
answer count: 0
score: 1

http://stackoverflow.com/q/52273067
linked to: http://stackoverflow.com/q/52379317
has answer: http://stackoverflow.com/a/52320963
score: 1
upvote count: 1
type: Question
has title: Word2Vec: How to check the trained model for the value of the vector?
has body: I have recently tried to use word2vec, i trained my model and gotten all the vectors assigned. However, I do not know how to find the value for each of the vector. I try to print the model but it only output all the vectors it have trained. But, I still don't get it, I thought the vectors are based on each word but somehow everything is inside one list. My understanding about word2vec is that each word(assume this W1) has their own vectors and with each vector it represents the similarity between the current word(W1) and word2(W2). Since each word is assigned with sparse vectors then it should consist lots of vectors for only W1. However, when I print my model, I received (maybe) for one word only but I am not sure which word is this. Can anyone please assist me? My codes: import collections import numpy as np import tensorflow as tf import matplotlib.pyplot as plt batch_size = 20 embedding_size = 2 num_sampled = 15 sentences = ["I have something that I want to say to him", "How are you", "We can see many stars tonight", "That's our house", "sung likes cats", "she loves dogs", "Do you know what he has done", "cats are great companions when they want to be", "We need to invest in clean, renewable energy", "women love his man", "queen love his king", "girl love his boy", "The line is too long. Why don't you come back tomorrow", "man and women roam in park", "Does it really matter", "dynasty king remain mortal"] words = " ".join(sentences).split() count = collections.Counter(words).most_common() # Build dictionaries reverse_dictionary = [i[0] for i in count] #reverse dic, idx -&gt; word dic = {w: i for i, w in enumerate(reverse_dictionary)} #dic, word -&gt; id voc_size = len(dic) data = [dic[word] for word in words] cbow_pairs = [] for i in range(1, len(data)-1) : cbow_pairs.append([[data[i-1], data[i+1]], data[i]]) skip_gram_pairs = [] for c in cbow_pairs: skip_gram_pairs.append([c[1], c[0][0]]) skip_gram_pairs.append([c[1], c[0][1]]) def generate_batch (size): assert…
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91519904
tagged with: word2vec
tagged with: python

http://stackoverflow.com/a/70612490
answers question: http://stackoverflow.com/q/52283840
score: 0
type: Answer
has body: For PyCharm use the Terminal: pip install pipwin pipwin install PyAudio &lt;-- Remember the capital letters

google-app-engine-python
type: Tag
tag name: google-app-engine-python
tags question: http://stackoverflow.com/q/52311029

http://stackoverflow.com/comment/91739816
type: AnswerComment
comment on: http://stackoverflow.com/a/52397643
score: 0
type: Comment
has text: @MadPhysicist Thanks very very much, Now i am happy :) (hahaha)

http://stackoverflow.com/a/52321050
answers question: http://stackoverflow.com/q/52320850
score: 0
type: Answer
has body: Your question is very confusing. Do you mean that everyday, your daily salary increases by a factor of 3? Would this code provide the informations you require? numberOfDaysWorked = int(input ("Enter the amount of days worked: \n")) #Asking the user to enter the amount of days they have worked salary = 0.01 # setting the inital amount of pennies total = 0.00 print("Day\tSalary\n---\t----") # printing out the titles for days and salary for currentDay in range(numberOfDaysWorked): salary += 2 * salary total += salary # this is adding the amount of pennies earned that day to the total amount of pennies that will be used toward the total print(currentDay + 1, "\t", salary) # printing out the day (+1 to ensure progression from day1 to day2 to day3 etc. and then printing out the amount of pennies earned on that one day) print("Total Pay: $", total) Output for an input of 10: Day Salary --- ---- 1 0.03 2 0.09 3 0.27 4 0.81 5 2.43 6 7.290000000000001 7 21.870000000000005 8 65.61000000000001 9 196.83000000000004 10 590.4900000000001 Total Pay: $ 885.7200000000003

http://stackoverflow.com/q/52326709
favorite count: 0
has comment: http://stackoverflow.com/comment/91600357
accepted answer: http://stackoverflow.com/a/52326737
tagged with: element
has comment: http://stackoverflow.com/comment/91600412
has body: Assume we have a list of words stored in a list like this: list_of_words = ["this", "is", "a", "text","for", "demonstration"] Furthermore, i have a list of selected words: selected_words = ["hello", "text", "demonstration"] I would like to count the number of words (elements if you like) that occur in list_of_words prior to the words in selected_words that match a word in list_of_words. I.e. the first word in selected_word that match is "text" and there are 3 words prior to that word in list_of_words. The second word that match is "demonstration" which has 5 words prior to it. So the output should be [3, 5]. What would be the most efficient way to calculate this? I can't seem to find anyone else who have asked this question in python.
tagged with: count
tagged with: python
tagged with: text
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/91600433
has title: Count number of elements in list prior to occurrence of specific element
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52326737
score: -1
upvote count: 0
answer count: 1

http://stackoverflow.com/q/52354914
possible better answer: http://stackoverflow.com/a/52354972
type: Question
has answer: http://stackoverflow.com/a/52355017
tagged with: expression
has answer: http://stackoverflow.com/a/52355255
has title: How to add a word to the line below using regular expression in python?
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/91654975
favorite count: 0
accepted answer: http://stackoverflow.com/a/52355255
has body: I need a regular expression in python to add {\an8} in the start of every line below the lines contains 'line:10.00%' , thanks.
tagged with: python
has answer: http://stackoverflow.com/a/52354972
type: AnsweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/q/52273148
has body: Imagine a pandas data frame given by df = pd.DataFrame({ 'id': range(5), 'desc': ('This is text', 'John Doe ABC', 'John Doe', 'Something JKL', 'Something more'), 'mfr': ('ABC', 'DEF', 'DEF', 'GHI', 'JKL') }) which yields id desc mfr 0 0 This is text ABC 1 1 John Doe ABC DEF 2 2 John Doe DEF 3 3 Something JKL GHI 4 4 Something more JKL I wish to determine which id's belong to eachother. Either they are matched by mfrcolumn or if mfrvalue are contained in desccolumn. E.g. id = 1 and 2 are the same group because mfr are equal but id = 0 and 1 are also the same group since ABC from mfr in id = 0 are part of desc in id = 1. The resulting data frame should be id desc mfr group 0 0 This is text ABC 0 1 1 John Doe ABC DEF 0 2 2 John Doe DEF 0 3 3 Something JKL GHI 1 4 4 Something more JKL 1 Are there anyone out there with a good solution for this? I imagine that there are no really simple ones so any is welcome.
has comment: http://stackoverflow.com/comment/91494735
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91494649
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91494559
tagged with: python
linked to: http://stackoverflow.com/q/4842613
score: 2
has comment: http://stackoverflow.com/comment/91494855
tagged with: conditional-statements
downvote count: 0
has answer: http://stackoverflow.com/a/52294638
has comment: http://stackoverflow.com/comment/91494942
type: Question
has title: Conditional grouping in pandas data frame
tagged with: string
upvote count: 2
tagged with: pandas-groupby
tagged with: pandas

http://stackoverflow.com/q/52414577
answer count: 0
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/91773714
type: Question
has comment: http://stackoverflow.com/comment/91773909
has title: Vectorized way to shuffle characters of strings in a list
has comment: http://stackoverflow.com/comment/91773644
has comment: http://stackoverflow.com/comment/91773706
has comment: http://stackoverflow.com/comment/91773177
has comment: http://stackoverflow.com/comment/91773742
downvote count: 0
score: 1
tagged with: string
has body: I am interested in shuffle all characters of the strings in a list, and to do this on a single string, there are two possibilities: ''.join(random.sample(string, k=len(string))) OR string_utils.shuffle(string) However, I need to shuffle around 10^8 strings I have in a list, and doing something like a list comprehension takes forever. Is there a vectorized or more efficient way to do this? Thanks!
favorite count: 0
has comment: http://stackoverflow.com/comment/91773068
has comment: http://stackoverflow.com/comment/91884143
tagged with: python
has comment: http://stackoverflow.com/comment/91773551
tagged with: python-3.x

google-chrome
tags question: http://stackoverflow.com/q/52324331
tags question: http://stackoverflow.com/q/52339411
tags question: http://stackoverflow.com/q/52364667
tags question: http://stackoverflow.com/q/52364135
tags question: http://stackoverflow.com/q/52301201
type: Tag
tags question: http://stackoverflow.com/q/52365003
tag name: google-chrome
tags question: http://stackoverflow.com/q/52356072
tags question: http://stackoverflow.com/q/52394408

http://stackoverflow.com/comment/91566682
comment on: http://stackoverflow.com/a/52309816
type: Comment
score: 2
type: AnswerComment
has text: Don't get caught up in one-linerness, your code is perfectly readable now

http://stackoverflow.com/comment/91581606
type: Comment
has text: Great, I'll work something out. I can anticipate you that you will still need to pull LabelEncoder out of the pipeline, no way around it. Could you add the mock input to the Question, so others can find it?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52310347

http://stackoverflow.com/comment/91568148
comment on: http://stackoverflow.com/q/52310383
has text: There is still the option of building a lookup table for factorials. You do all the processing once (it can be outside of your script) to generate the table then move the needle in your table to get the results.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91732050
type: QuestionComment
comment on: http://stackoverflow.com/q/52378957
has text: I think your expression summarizes to `~(A|B) = ~A&~B`. Why don't just go straight to the result of ~(A|B)?
score: 0
type: Comment

http://stackoverflow.com/q/52428830
upvote count: 1
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52428908
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52428908
has title: UnboundLocalError: local variable 'ticketCost' referenced before assignment
type: Question
has body: So I want a error message to appear saying 'Sorry, invalid input' when I input anything other than child,adult and senior or 3D and 2D. And then I want it to ask the user again to input the ticketType and movieType but it comes up with "File "python", line 33, in &lt;module&gt; File "python", line 27, in buyOneTicket UnboundLocalError: local variable 'ticketCost' referenced before assignment" . print ('Welcome to RareCinema Ticketing System') num = int(input('How many tickets would you like to buy?')) def buyOneTicket() : ticketType = input('Enter the type of ticket (Child/Adult/Senior)?') movieType = input('Enter the movie type (2D/3D)?') if ticketType == ("child"): if movieType == ("2D"): ticketCost = 16 elif movieType == ('3D'): ticketCost = 19 elif ticketType == ('adult'): if movieType == ('2D'): ticketCost = 22 elif movieType == ('3D'): ticketCost = 27 elif ticketType == ('senior'): if movieType == ('2D'): ticketCost = 14 elif movieType == ('3D'): ticketCost = 18 return ticketCost ticketCost=0 count = 1 while (count &lt;= num): ticketCost = ticketCost + buyOneTicket() count = count + 1 if ticket_type != ('child') and ('adult') and ('senior'): if movie_type != ('2D') and ('3D'): print ('Sorry, you have entered an invalid input') ticketType = input('Enter the type of ticket (Child/Adult/Senior)?') movieType = input('Enter the movie type (2D/3D)?') else: print('Your total cost for ' +str(num)+ ' is ', ticketCost )

http://stackoverflow.com/q/52284076
has answer: http://stackoverflow.com/a/52284165
accepted answer: http://stackoverflow.com/a/52284165
tagged with: matplotlib
has title: Plot multiple graph using same graph
score: -1
tagged with: numpy
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python
has body: I have written one code where I want to plot multiple graphs in a same plot. When I run this, I do not get any result or any error. I am trying to take each value of a and plot graph using the program. So i suppose to have 4 graph as a have 4 elements. Most importantly all graphs shall be in a same figure. Though I am not getting any error or any result I am a bit confuse whether the for loop is working or not. When I use a fixed alpha value and, without using for loop, my code works perfectly. Any idea how to perform that? If my question is not clear please let me know. import numpy as np import matplotlib.pyplot as plt r=10**-6 a=np.array([10,30,60,90]) E=[] B=[] gamma_sa=58.6*10**-3 gamma_sw=25*10**-3 gamma_pa=153*10**-3 gamma_pw=110*10**-3 gamma_aw=72.5*10**-3 kt= 1.38*10**-23*290 i=0 for n in a: alpha=n*(np.pi/180) while i&lt;360: beta=(90-i)*(np.pi/180) if i&gt;=alpha*180/np.pi and i&lt;=180-alpha*180/np.pi: Energy= 2*np.pi*r**2*(gamma_pw+gamma_sw*np.cos(alpha)+gamma_sa*(1-np.cos(alpha))-0.5*gamma_aw*np.sin(alpha)**2) elif i&gt;=180+alpha*180/np.pi and i&lt;=360-alpha*180/np.pi: Energy=2*np.pi*r**2*(gamma_sw+gamma_pw*(np.cos(alpha))+gamma_pa*(1-np.cos(alpha))-0.5*gamma_aw*np.sin(alpha)**2) elif i&gt;180-alpha*180/np.pi and i&lt;180+alpha*180/np.pi : x=np.arcsin(((1/np.tan(-beta))*(1/np.tan(alpha)))) w=np.cos(alpha) y=np.arctan((np.cos(-beta))/(np.sqrt((np.sin(beta)**2)-(np.cos(alpha)**2)))) z= (2*r**2)*((x*w)-y) A_pa= (np.pi*r**2)*(1-np.cos(alpha))+z A_sa=(2*np.pi*r**2)*(1-np.cos(alpha))-A_pa A_sw=(2*np.pi*r**2)-A_sa A_pw=(2*np.pi*r**2)-A_pa Energy= (gamma_sa*A_sa)+(gamma_pa*A_pa)+(gamma_sw*A_sw)+(gamma_pw*A_pw)-(np.pi*r**2*gamma_aw*np.sin(alpha)**2) else: x=np.arcsin(((1/np.tan(beta))*(1/np.tan(alpha)))) w=np.cos(alpha) y=np.arctan((np.cos(beta))/(np.sqrt((np.sin(beta)**2)-(np.cos(alpha)**2)))) z= (2*r**2)*((x*w)-y) A_pa= (np.pi*r**2)*(1-np.cos(alpha))+z A_sa=(2*np.pi*r**2)*(1-np.cos(alpha))-A_pa A_sw=(2*np.pi*r**2)-A_sa A_pw=(2*np.pi*r**2)-A_pa Energy= (gamm…
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 0
type: Question

http://stackoverflow.com/q/52333190
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91614620
has comment: http://stackoverflow.com/comment/91614399
accepted answer: http://stackoverflow.com/a/52334352
tagged with: duration
upvote count: 1
has body: The code below is supposed to: parse an input string to some kind of duration validate that the duration is not empty, not negative, not longer than 10 years Example of input strings are: duration_string = "P10W" duration_string = "P1Y" Here is the code duration = isodate.parse_duration(duration_string) if isinstance(duration, datetime.timedelta): if not duration &gt; datetime.timedelta(0): raise Exception('duration invalid') if duration &gt; datetime.timedelta(3660): raise Exception('duration cannot be longer than 10 years') elif isinstance(duration, isodate.Duration): if not duration &gt; 0: raise Exception('duration invalid') if duration &gt; isodate.duration.Duration(0, 0, 0, years=10, months=0): log.debug("duration %s isodate %s" % (duration, isodate.duration.Duration(0, 0, 0, years=10, months=0))) raise Exception('duration cannot be longer than 10 years') Is there an easier way to do this than the monstrocity I have produced? In addition to needing simplification, the line duration &gt; isodate.duration.Duration(0, 0, 0, years=10, months=0) does not work. I am using Python 2.7
has comment: http://stackoverflow.com/comment/91614120
type: Question
has comment: http://stackoverflow.com/comment/91615184
score: 1
has comment: http://stackoverflow.com/comment/91614806
has comment: http://stackoverflow.com/comment/91613898
possible better answer: http://stackoverflow.com/a/52362332
has comment: http://stackoverflow.com/comment/91614589
linked to: http://stackoverflow.com/q/52332509
tagged with: python-2.7
has answer: http://stackoverflow.com/a/52362332
has comment: http://stackoverflow.com/comment/91614884
answer count: 2
has title: Simplify code dealing with time and duration that currently uses datetime and isodate?
downvote count: 0
has comment: http://stackoverflow.com/comment/91615049
favorite count: 0
tagged with: time
has comment: http://stackoverflow.com/comment/91614310
has comment: http://stackoverflow.com/comment/91613521
tagged with: python
has answer: http://stackoverflow.com/a/52334352

http://stackoverflow.com/comment/91621812
type: Comment
type: QuestionComment
has text: Can you add a more complete example of an api return value and the expected data frame you would like to build out of it?
comment on: http://stackoverflow.com/q/52337216
score: 0

http://stackoverflow.com/a/52420369
accepted answer of: http://stackoverflow.com/q/52420357
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91784220
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91784036
downvote count: 0
has comment: http://stackoverflow.com/comment/91783911
has comment: http://stackoverflow.com/comment/91783946
score: 1
answers question: http://stackoverflow.com/q/52420357
has body: Use Series.str.contains: df.C = np.where(df.C.str.contains('ye').values, 'no', df.C.values) If performance is important: df.C = np.where(['ye' in x for x in df.C], 'no', df.C.values) df.loc[['ye' in x for x in df.C], 'C'] = 'no' Performance: df = pd.DataFrame({'C':['aa ss ye','a s d','fff', 'yeye']}) #[40000 rows x 1 columns] df = pd.concat([df] * 10000, ignore_index=True) print (df) In [13]: %timeit df.C = np.where(df.C.str.contains('ye').values, 'no', df.C.values) 21.6 ms ± 294 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) In [14]: %timeit df.C = np.where(['ye' in x for x in df.C], 'no', df.C.values) 3.29 ms ± 49.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [15]: %timeit df.loc[['ye' in x for x in df.C], 'C'] = 'no' 5.26 ms ± 105 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) String operation are slow in pandas, so fastest is use list comprehension with in. Timings in real data should be different, because depends of number of matched values and length of DataFrame.

http://stackoverflow.com/comment/91506188
type: Comment
has text: Doesn't return anything isn't technically correct. `list.sort` returns `None`.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52279024

http://stackoverflow.com/comment/91531875
has text: Thanks you also your command was a guide to installing django.
type: AnswerComment
comment on: http://stackoverflow.com/a/52285684
score: 0
type: Comment

http://stackoverflow.com/a/63117058
answers question: http://stackoverflow.com/q/52291236
downvote count: 3
upvote count: 4
score: 1
has comment: http://stackoverflow.com/comment/121405036
has body: Try running cmd as admin when installing
type: Answer

http://stackoverflow.com/comment/91620840
comment on: http://stackoverflow.com/a/52335340
score: 0
type: AnswerComment
type: Comment
has text: @zinyosrim nope I did not

http://stackoverflow.com/comment/91648402
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52337825
has text: This is really helpful. Thank you very much. Last thing I need is to just export this to a csv file with the two columns: one for word, other for frequency. Any chance you can help with that?

http://stackoverflow.com/a/52281673
accepted answer of: http://stackoverflow.com/q/52280944
has comment: http://stackoverflow.com/comment/91511965
answers question: http://stackoverflow.com/q/52280944
type: Answer
has body: My following solution proposal is based on the RANSAC algorithm. It is method to fit a mathematical model (e.g. a line) to data with heavy of outliers. RANSAC is one specific method from the field of robust regression. My solution below first fits a line with RANSAC. Then you remove the data points close to this line from your data set (which is the same as keeping the outliers), fit RANSAC again, remove data, etc until only very few points are left. Such approaches always have parameters which are data dependent (e.g. noise level or proximity of the lines). In the following solution and MIN_SAMPLES and residual_threshold are parameters which might require some adaption to the structure of your data: import matplotlib.pyplot as plt import numpy as np from sklearn import linear_model MIN_SAMPLES = 3 x = np.linspace(0, 2, 100) xs, ys = [], [] # generate points for thee lines described by a and b, # we also add some noise: for a, b in [(1.0, 2), (0.5, 1), (1.2, -1)]: xs.extend(x) ys.extend(a * x + b + .1 * np.random.randn(len(x))) xs = np.array(xs) ys = np.array(ys) plt.plot(xs, ys, "r.") colors = "rgbky" idx = 0 while len(xs) &gt; MIN_SAMPLES: # build design matrix for linear regressor X = np.ones((len(xs), 2)) X[:, 1] = xs ransac = linear_model.RANSACRegressor( residual_threshold=.3, min_samples=MIN_SAMPLES ) res = ransac.fit(X, ys) # vector of boolean values, describes which points belong # to the fitted line: inlier_mask = ransac.inlier_mask_ # plot point cloud: xinlier = xs[inlier_mask] yinlier = ys[inlier_mask] # circle through colors: color = colors[idx % len(colors)] idx += 1 plt.plot(xinlier, yinlier, color + "*") # only keep the outliers: xs = xs[~inlier_mask] ys = ys[~inlier_mask] plt.show() In the following plot points shown as stars belong to the clusters detected by my code. You also see a few points depicted as circles which are the points remaining after the iterations. The few black stars form a cluster which you could get rid of by increasing MIN_SAMP…
downvote count: 0
score: 6
type: AcceptedAnswer
upvote count: 6

http://stackoverflow.com/a/52326257
has comment: http://stackoverflow.com/comment/91603003
has comment: http://stackoverflow.com/comment/91602660
has comment: http://stackoverflow.com/comment/91603086
score: 0
has comment: http://stackoverflow.com/comment/91602482
type: Answer
has comment: http://stackoverflow.com/comment/91600831
has body: You can write a loop to go through each object final=[] for obj in d: final.append(obj['city']) Or you can try using this final = [obj['city'] for obj in d] Or if you only need the first value then print(d[0]['city']) Output 'Paris' Since your data is a list of dictionaries, you'll have to use the index value to get the data in the dictionary
has comment: http://stackoverflow.com/comment/91603281
answers question: http://stackoverflow.com/q/52326223
has comment: http://stackoverflow.com/comment/91602846

http://stackoverflow.com/comment/91685258
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52368428
has text: @BlackThunder I've tried the first one and it sort of works. Only problem is that you have to wait 10 seconds even if you do input something and I'm trying to make it so you don't have to wait the full 10 seconds. The second one doesn't seem to work for me. When I run it just says process finished without any input or output. I have already translated it to python 3.6 (which I'm using) and didn't help.
type: Comment

http://stackoverflow.com/comment/91741534
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52389667
has text: I was able to get this to work: `pd.concat([grouped.get_group(key).groupby(level=1).filter(lambda x: (x.loc[pd.IndexSlice[:, :, '1'], 'Val2']>5).any()) for key, group in grouped])`
score: 0

http://stackoverflow.com/comment/91649556
type: QuestionComment
has text: The code looks correct. Have you tried adding prints at the beginning and end of `getImageUrls` and `getImage` to check if they are really not running in parallel? Maybe there are other differences (cookies or other headers) that lead to the performance difference between Node and aiohttp.
score: 0
comment on: http://stackoverflow.com/q/52346297
type: Comment

http://stackoverflow.com/comment/91793030
has text: By using tools like `itertools.groupby`. SQL databases are not that good with "hierarchical data".
comment on: http://stackoverflow.com/q/52425163
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/52346399
has title: generate_tfrecords.py error (pandas -> parsers.py)
has body: Im trying to use my own images to train for object identification with tensorflow. I have followed all instructions given by: https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10 As im using the command: "python generate_tfrecord.py --csv_imput=images\train_labels.csv --image_dir=images\train --output_path=train.record" in the command prompt i get the following. Command prompt error message Have anyone recieved the same/similar error and knows how to fix it ? :)
score: 0
answer count: 1
tagged with: training-data
type: UnansweredQuestion
tagged with: python
tagged with: object-detection
tagged with: image-processing
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/52351329

http://stackoverflow.com/a/52275644
has comment: http://stackoverflow.com/comment/91516041
accepted answer of: http://stackoverflow.com/q/52275531
answers question: http://stackoverflow.com/q/52275531
has body: Somethink like w_alarms[w_alarms.site_id &gt; 3].groupby('site_id')['issue'].count()
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91504151
has comment: http://stackoverflow.com/comment/91500290
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/52291458
has comment: http://stackoverflow.com/comment/91531044
has comment: http://stackoverflow.com/comment/91569058
tagged with: python
upvote count: 0
has comment: http://stackoverflow.com/comment/91568911
has comment: http://stackoverflow.com/comment/91531698
has comment: http://stackoverflow.com/comment/91568170
has comment: http://stackoverflow.com/comment/91530811
has body: I am generating PNG images using wordcloud. My file consists of over 220000 entries with frequencies, to generate wordcloud (hence its slow). I have to generate wordclouds in a loop and look for a string in file and change the color of that word to red (rest of the words will be in black). Can anyone guide me to a way to search a specific word in the PNG image and just change the color of that word in the PNG file using python???For instance, in the attached image would like to search for a word like game,and change its color to red I have already tried to generate wordcloud using wordcloud function in python and used the following function to change color. Using this function I can change the color but as I have to generate hundreds of images, it takes alot of time. I was looking for a way to generate the image once and then search for specific words in the image and just change the color of that word using python. import matplotlib.pyplot as plt import numpy as np from PIL import Image from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator #to get rid of warning of open windows plt.rcParams.update({'figure.max_open_warning': 0}) import os.path stopwords = set(STOPWORDS) d={} ################################################################## def color_word(word, *args, **kwargs): if (word == name.upper()): color = '#ff0000' # red else: color = '#000000' # black return color ################################################################## with open('f1.txt') as inf: for line in inf: parts = line.split(',') d[parts[0]]=float(parts[1]) with open('f2.txt') as inf: for line in inf: parts = line.split() name=parts[0] print(name) wordcloud = WordCloud(stopwords=STOPWORDS, background_color='white', max_words=210000, width=1500, height=1000, color_func=color_word).generate_from_frequencies(d) plt.figure(figsize = (15, 15), facecolor = None) plt.imshow(wordcloud) plt.axis("off") plt.tight_layout(pad = 0) # plt.savefig(name+".eps",format='eps', dpi=1000) wordcloud.…
type: Question
has answer: http://stackoverflow.com/a/52310978
has title: python - changing the color of a word in a png file (search for the word and change the color of the word)
has comment: http://stackoverflow.com/comment/91545429
score: -1
has comment: http://stackoverflow.com/comment/91535652
has comment: http://stackoverflow.com/comment/91532299
has comment: http://stackoverflow.com/comment/91567577
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91541741
type: UnansweredQuestion

http://stackoverflow.com/comment/91608916
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52331065
has text: @PM2Ring Yes, I forgot to include it, but outside of the function and the if statement it is declared.

http://stackoverflow.com/a/52423651
has comment: http://stackoverflow.com/comment/91802461
answers question: http://stackoverflow.com/q/52423525
has body: You can use a filter with a lambda like filter(lambda x: x!=2,foo_list)
score: 0
has comment: http://stackoverflow.com/comment/91790163
type: Answer

http://stackoverflow.com/q/52319053
tagged with: server
has body: I am trying to run a simple python server with REST API and Connexion/Flask built in on a remote Linux server (binding to the server public IP address) using Apache. (Server is running Ubuntu 16.04.5 LTS, python code was written in Python 3.7) Here are some files for the server implementation: server.py: import connexion app = connexion.App(__name__, specification_dir='./') app.add_api('swagger.yml') if __name__ == "__main__": app.run(host='127.0.0.1', port=5000, debug=True) swagger.yml: Specifications for the REST API, I have tested it by running on the localhost and it's working properly. (The base path is /api) opertations.py: Functions for the API depending on the response My goal is to run the server on a remote Linux server that anyone who knows the public IP address of the server, they will be able to call the API. For example, if the public IP address is xxx.xx.xx.xxx, then users should be able to call the following URL to retrieve the data: http://xxx.xx.xx.xxx:&lt;port&gt;/api/&lt;operation_name&gt;?&lt;query_parameters&gt; So far, I was able to call the API (that was running on the localhost on the server) from the client side with SSH port forwarding as well as ngrok (they provide tunnels to the server localhost), but these are not what I want. I'm new to creating my own web servers and I've been looking into Apache and how it works with VirtualHosts etc. but I couldn't find how exactly to set it up so that it binds the python server to the public IP address of the Linux server.
tagged with: apache
downvote count: 0
answer count: 1
tagged with: flask
favorite count: 0
tagged with: linux
has answer: http://stackoverflow.com/a/52327297
tagged with: python
accepted answer: http://stackoverflow.com/a/52327297
type: AnsweredQuestion
has title: Creating Apache web server on Ubuntu with Connexion/Flask and public IP address
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/91713361
comment on: http://stackoverflow.com/q/52384648
type: Comment
type: QuestionComment
score: 2
has text: what's your expected output?

http://stackoverflow.com/a/63787456
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52386257
has body: None of the other suggestions worked for me. I simply replaced all \n with \\n before saving to CSV and it'll preserve the newline character. df.Column2 = df.Column2.apply(lambda x : x.replace('\n', '\\n')) df.to_csv("df.csv", index=False)
downvote count: 0

http://stackoverflow.com/q/52388831
has answer: http://stackoverflow.com/a/52547559
tagged with: time-series
has body: I am trying to understand how to correctly feed data into my keras model to classify multivariate time series data into three classes using a LSTM neural network. I looked at different resources already - mainly these three excellent blog posts by Jason Brownlee post1, post2, post3), other SO questions and different papers, but none of the information given there exactly fits my problem case, and I was not able to figure out if my data preprocessing / feeding it into the model is correct, so I guessed I might get some help if I specify my exact conditions here. What I am trying to do is classify multivariate time series data, which in its original form is structured as follows: I have 200 samples One sample is one csv file. A sample can have 1 to 50 features (i.e. the csv file has 1 to 50 columns). Each feature has its value "tracked" over a fixed amount of time steps, let's say 100 (i.e. each csv file has exactly 100 rows). Each csv file has one of three classes ("good", "too small", "too big") So what my current status looks like is the following: I have a numpy array "samples" with the following structure: # array holding all samples [ # sample 1 [ # feature 1 of sample 1 [ 0.1, 0.2, 0.3, 0.2, 0.3, 0.1, 0.2, 0.4, 0.5, 0.1, ... ], # "time series" of feature 1 # feature 2 of sample 1 [ 0.5, 0.6, 0.7, 0.6, 0.4, 0.3, 0.2, 0.1, -0.1, -0.2, ... ], # "time series" of feature 2 ... # up to 50 features ], # sample 2 [ # feature 1 of sample 2 [ 0.1, 0.2, 0.3, 0.2, 0.3, 0.1, 0.2, 0.4, 0.5, 0.1, ... ], # "time series" of feature 1 # feature 2 of sample 2 [ 0.5, 0.6, 0.7, 0.6, 0.4, 0.3, 0.2, 0.1, -0.1, -0.2, ... ], # "time series" of feature 2 ... # up to 50 features ], ... # up to sample no. 200 ] I also have a numpy array "labels" with the same length as the "samples" array (i.e. 200). The labels are encoded in the following way: "good" = 0 "too small" = 1 "too big" = 2 [0, 2, 2, 1, 0, 1, 2, 0, 0, 0, 1, 2, ... ] # up to label no. 200 This "labels" array is then encoded with…
downvote count: 0
possible better answer: http://stackoverflow.com/a/61768723
tagged with: keras
has answer: http://stackoverflow.com/a/61768723
score: 6
tagged with: lstm
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52547559
linked to: http://stackoverflow.com/q/38714959
favorite count: 0
has title: Understanding multivariate time series classification with Keras
answer count: 2
tagged with: machine-learning
tagged with: python
upvote count: 6

http://stackoverflow.com/comment/91736503
comment on: http://stackoverflow.com/a/52395721
type: AnswerComment
has text: You're definitely right about my logic, thank you for pointing that out to me. When I try and run your code, both the arrays print blank. Am i doing something wrong?
score: 0
type: Comment

http://stackoverflow.com/q/52299808
score: 1
has body: I have an R object (.rda) file that I would like to load into a numpy array in python. Unfortunately, the following code produces a MemoryError that I can't seem to get to the bottom of. import numpy as np import rpy2.robjects as robjects robjects.r['load']('myrobject.rda') rils = np.array(robjects.r['myobjectname']) The error is thrown with respect to the very bottom line of code, so the issue is converting the object into a numpy array, not loading the object. The data is primarily one to three digit floats ranging between 0 and 1, but there are some characters in there as well. My machine runs a 64 bit version of Ubuntu 16.04 and is running python 3.5.2 64 bit, so running 32 bit anything is not the problem here as it has been with related posts that I've seen. I've got 16 GB of RAM. When I use htop to look at memory usage during execution of this code, it gradually increases to about 4.5 GB before quitting and throwing the error. The object I'm trying to load is 113.7MB in size, though my understanding is that .rda files are compressed. I've never seen an error like this before, and I'd appreciate any help figuring out what is causing it and what I should do to fix it. EDIT Since I was asked, here is the exact error. Traceback (most recent call last): File "rils_ga.py", line 10, in &lt;module&gt; rils = np.array(robjects.r['Aprobma']) MemoryError Aprobma corresponds to myobjectname that I used in the original post.
tagged with: rpy2
tagged with: memory
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91557868
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/91550687
favorite count: 0
has comment: http://stackoverflow.com/comment/91578703
tagged with: python
has comment: http://stackoverflow.com/comment/91550823
has answer: http://stackoverflow.com/a/52826975
has title: Memory Error when trying to load an R object file into a python numpy array
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/91790785
comment on: http://stackoverflow.com/q/52422680
score: 0
type: Comment
type: QuestionComment
has text: @PetrPetrov I've updated my answer, let me know if that solves it for you.

http://stackoverflow.com/comment/91682027
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52368607
has text: You are currently not using namespaces in your urlpatterns. It should be just `index` - but then it collides with the one in the main patterns.

http://stackoverflow.com/comment/91496359
comment on: http://stackoverflow.com/q/52274356
has text: @jpp there could be value in a standalone question specifically answered based on benchmarks if all else fails?
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/52299268
type: Question
has title: ValueError: Cannot feed value of shape (128,) for Tensor 'Target:0', which has shape '(128, ?)'
has body: I know this question has been asked a lot but I cannot figure out the solution. I have already built a cnn and preproccecing for images and everything worked fine until I set the feed_dict parameter in sess.run. I have 24 classes and the images are sized as (64,64). Both imagepaths and labels are lists of paths. imagepaths = tf.convert_to_tensor(imagepaths, dtype=tf.string) labels = tf.convert_to_tensor(labels, dtype=tf.int32) image, label = tf.train.slice_input_producer([imagepaths, labels], shuffle=True) #(here) i did decoding,resing and normalizing X, Y = tf.train.batch([image, label], batch_size=batch_size, capacity=batch_size * 8, num_threads=4) place_holder_X = tf.placeholder(tf.string,(128, 64, 64, 3), name="Input") place_holder_Y = tf.placeholder(tf.int32,(128,None), name="Target") with tf.Session() as sess: sess.run(init) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) try: for step in range(1, num_steps+1): #print("step = ",step,"display step",display_step,end=' ') if coord.should_stop(): break if step % display_step == 0: images, labels = sess.run([X, Y]) _, loss, acc = sess.run([train_op, loss_op, accuracy], feed_dict={place_holder_X: images, place_holder_Y: labels}) print("Step " + str(step) + ", Minibatch Loss= " + \ "{:.4f}".format(loss) + ", Training Accuracy= " + \ "{:.3f}".format(acc)) else: # Only run the optimization op (backprop) sess.run(train_op) except Exception as e: coord.request_stop(e) finally: coord.request_stop() coord.join(threads) print("Optimization Finished!") print("Time taken: %f" % (time.time() - startTime)) saver = tf.train.Saver() saver.save(sess, "./models1/my_tf_model.ckpt")
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91584265
tagged with: python
has comment: http://stackoverflow.com/comment/91551628
tagged with: tensorflow

http://stackoverflow.com/q/52382517
has title: process_item pipeline not called
type: Question
tagged with: pipeline
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/52385267
accepted answer: http://stackoverflow.com/a/52385267
has comment: http://stackoverflow.com/comment/91710580
tagged with: sqlite
tagged with: python
has comment: http://stackoverflow.com/comment/91710381
tagged with: scrapy
type: AnsweredQuestion
has body: I'm new to python and scrapy After scraping process I tried to save database to mysqlite, Follow by this src : https://github.com/sunshineatnoon/Scrapy-Amazon-Sqlite( from url) My problem is database was created successfully but items can't be inserted to database because process_item not called EDIT I paste the source code from github link above setting.py ITEM_PIPELINES = { 'amazon.pipelines.AmazonPipeline': 300 } pipelines.py # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import sqlite3 import os con = None class AmazonPipeline(object): def __init__(self): self.setupDBCon() self.createTables() def process_item(self, item, spider): print('---------------process item----') self.storeInDb(item) return item def setupDBCon(self): self.con = sqlite3.connect(os.getcwd() + '/test.db') self.cur = self.con.cursor() def createTables(self): self.dropAmazonTable() self.createAmazonTable() def dropAmazonTable(self): #drop amazon table if it exists self.cur.execute("DROP TABLE IF EXISTS Amazon") def closeDB(self): self.con.close() def __del__(self): self.closeDB() def createAmazonTable(self): self.cur.execute("CREATE TABLE IF NOT EXISTS Amazon(id INTEGER PRIMARY KEY NOT NULL, \ name TEXT, \ path TEXT, \ source TEXT \ )") self.cur.execute("INSERT INTO Amazon(name, path, source ) VALUES( 'Name1', 'Path1', 'Source1')") print ('------------------------') self.con.commit() def storeInDb(self,item): # self.cur.execute("INSERT INTO Amazon(\ # name, \ # path, \ # source \ # ) \ # VALUES( ?, ?, ?)", \ # ( \ # item.get('Name',''), # item.get('Path',''), # item.get('Source','') # )) self.cur.execute("INSERT INTO Amazon(name, path, source ) VALUES( 'Name1', 'Path1', 'Source1')") print ('------------------------') print ('Data Stored in Database') print ('------------------------') self.con.commit() spiders/amazonspider.py import scrapy import urlli…
has comment: http://stackoverflow.com/comment/91711098

http://stackoverflow.com/q/52303882
has title: Python Scrapy not outputting to csv file
tagged with: scrapy
type: Question
accepted answer: http://stackoverflow.com/a/52305215
has answer: http://stackoverflow.com/a/52306070
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/52306070
has answer: http://stackoverflow.com/a/52303974
has body: What am I doing wrong with the script so it's not outputting a csv file with the data? I am running the script with scrapy runspider yellowpages.py -o items.csv and still nothing is coming out but a blank csv file. I have followed different things here and also watched youtube trying to figure out where I am making the mistake and still cannot figure out what I am not doing correctly. # -*- coding: utf-8 -*- import scrapy import requests search = "Plumbers" location = "Hammond, LA" url = "https://www.yellowpages.com/search" q = {'search_terms': search, 'geo_location_terms': location} page = requests.get(url, params=q) page = page.url items = () class YellowpagesSpider(scrapy.Spider): name = 'quotes' allowed_domains = ['yellowpages.com'] start_urls = [page] def parse(self, response): self.log("I just visited: " + response.url) items = response.css('a[class=business-name]::attr(href)') for item in items: print(item)
has comment: http://stackoverflow.com/comment/91557905
tagged with: python
has answer: http://stackoverflow.com/a/52305215
type: AnsweredQuestion

http://stackoverflow.com/comment/91517810
type: AnswerComment
comment on: http://stackoverflow.com/a/52284448
type: Comment
has text: @leewz Does the edit make that clear enough? (And is it worth adding examples from the stdlib or popular third-party libraries instead of just builtins?)
score: 0

http://stackoverflow.com/q/52374584
has answer: http://stackoverflow.com/a/52375137
has title: How to iterate over a tuple of tuples without flattening
type: Question
has answer: http://stackoverflow.com/a/52375096
answer count: 2
tagged with: iterator
has body: I'd like to check the values of a tuple of tuples. In addition to checking each value of each tuple, I need to also compare the last element in one tuple to the first element in the next tuple. Can I iterate over a tuple of tuples without flattening it into a list? flattened_tuple = [element for tupl in tupleOfTuples for element in tupl] for i in range(len(flattened_tuple)-1): print(flattened_tuple[i], flattened_tuple[i+1]) This is what I came up with that doesn't flatten into a list, but I can't compare last element of one tuple to first element of next tuple: for row in tuple_of_tuples: for i, element in enumerate(tuple_of_tuples): print(row[i], row[i+1]) For the tuple of tuples: ((0,1,2),(3,4,5),(6,7,8)), I get this error: 0 1 1 2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "npuzzle.py", line 67, in goal_test print(row[i], row[i+1]) IndexError: tuple index out of range
has comment: http://stackoverflow.com/comment/91694029
favorite count: 0
tagged with: tuples
has comment: http://stackoverflow.com/comment/91694137
tagged with: python
score: -2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91694042
type: UnansweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/91694012
upvote count: 1

http://stackoverflow.com/q/52311003
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52313581
downvote count: 0
has answer: http://stackoverflow.com/a/52340542
type: Question
has answer: http://stackoverflow.com/a/63402321
score: 12
tagged with: python-2.7
answer count: 3
possible better answer: http://stackoverflow.com/a/52313581
has title: Is there a simple way to add a border to Kivy Buttons
tagged with: kivy
favorite count: 0
upvote count: 12
has body: I am using python-2.7 and kivy. Can someone tell me that how to add a different colour border to kivy button. test.py from kivy.uix.screenmanager import Screen from kivy.app import App from kivy.core.window import Window Window.clearcolor = (0.5, 0.5, 0.5, 1) Window.size = (300, 100) class User(Screen): pass class Test(App): def build(self): return self.root if __name__ == '__main__': Test().run() test.py User: BoxLayout: Button: background_normal: '' text: 'Ok'
tagged with: python
accepted answer: http://stackoverflow.com/a/52340542

http://stackoverflow.com/comment/91586471
type: QuestionComment
comment on: http://stackoverflow.com/q/52319296
has text: Dictionary comprehension won't gracefully handle duplicate keys.
score: 0
type: Comment

http://stackoverflow.com/a/52402772
answers question: http://stackoverflow.com/q/52401629
accepted answer of: http://stackoverflow.com/q/52401629
score: 0
type: AcceptedAnswer
has body: Nils gave you correct answer to check matplotlib documentation Dummy data import pandas as pd import numpy as np from matplotlib import pyplot as plt series1 = pd.Series(np.random.rand(20)) series2 = pd.Series(np.random.rand(20)+0.3) Plot plt.fill_between(series1.index, series1, series2, where=series2&gt;=series1, facecolor='green', alpha=0.5, interpolate=True) plt.fill_between(series1.index, series2, series1, where=series2&lt;=series1, facecolor='red', alpha=0.5, interpolate=True)
type: Answer

http://stackoverflow.com/comment/91705720
has text: Thanks for your solution. I really hoped there is a built-in method to do this. I cannot imaging that this an uncommon intention, isn't it?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52372737

http://stackoverflow.com/a/63490931
downvote count: 1
score: 9
accepted answer of: http://stackoverflow.com/q/52391784
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52391784
type: Answer
has body: Sorry for the late answer. I am facing a similar issue and found your question. The problem is not really one it's just a warning and wont actually result in any differences in your matches. WARNING:root:Applied processor reduces input query to empty string, all comparisons will have score 0. [Query: '/'] Means that the query string for process.extract() didn't contain any common characters of a natural language: [Query: '/']. After digging into fuzzywuzzy, i found that a string processor reduces input query to empty string, which wont match any pattern in the search text you provide. My approach to get rid of these warnings is to validate the query string with that string processor before doing the fuzzy search. from fuzzywuzzy import utils invalid_query = &quot; ... // &quot; if utils.full_process(invalid_query): # wont execute and not produce a warning process.extract(invalid_query, patterns)
upvote count: 10

http://stackoverflow.com/q/52299344
tagged with: python
has comment: http://stackoverflow.com/comment/91570140
answer count: 0
type: Question
has title: What's the best way to combine rigidbody markers into a transform?
tagged with: linear-algebra
score: 0
has body: I have a motion tracker that gives me the positions of LEDs in space. I know which LED is which. I need to compute the orientation of the rigidbody over time. Right now I build a rotation matrix from three LEDs, by using cross products to make orthogonal basis vectors. But the code doesn't easily transfer to more than 3 markers. What if I have 6 markers to avoid the danger of less than 3 being in view of the tracker at any time point? I can make a rotation matrix of all combinations of three markers. But how can I use all available markers, which should also help a little bit with measurement noise? I'm working in python by the way, so numpy examples are appreciated, but not necessary.
tagged with: 3d
tagged with: rigid-bodies
has comment: http://stackoverflow.com/comment/91598408
type: UnansweredQuestion

http://stackoverflow.com/q/52333905
tagged with: batch-normalization
answer count: 1
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/52335164
has body: Somehow for my implementation, I have to define the weights first and can not use high level functions in tensorflow like tf.layers.batch_normalization or tf.layers.dense. So to do batch normalization I need to use tf.nn.batch_normalization. I know that for calculating mean and variance of each minibatch I can use tf.nn.moments, but what about moving mean and variance? Does anyone have experience with doing that or knows an example of implementation? I see that people talk about using tf.nn.batch_normalization could be tricky so I want to know the complexity of doing that. In other words, what makes it tricky and what points I should be careful about during my implementation? Is there any other point besides moving average and variance that I should be aware of?
tagged with: tensorflow
type: Question
has title: How to take care of moving mean and moving variance using tf.nn.batch_normalization?
downvote count: 0

http://stackoverflow.com/a/52423272
answers question: http://stackoverflow.com/q/52401194
score: 0
type: Answer
has body: Many thanks for everyone's replies (this is my first Stack question :) ). As i suspected there is a really straight forward solution to this but for the 'replace' i'm not actually allowed to use that syntax yet as it's not been covered in the current module. i did managed to get there in the end (and it's quite long winded because of the way we are expected to answer using only syntax we've covered. For anyone curious, please see below; work_tip = "Good code is commented code" new_string = "" for letter in work_tip: if letter.isalpha(): new_string = new_string + letter else: new_string = new_string + "-" print(new_string) quite long winded for what some covered in three lines but i'll get there some day. Thanks again everyone! Ed

qpushbutton
type: Tag
tags question: http://stackoverflow.com/q/52338366
tag name: qpushbutton

http://stackoverflow.com/comment/91677689
has text: See the tip [here](https://github.com/mkleehammer/pyodbc/wiki/Tips-and-Tricks-by-Database-Platform#databases-containing-odbc-linked-tables) regarding databases containing ODBC linked tables.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52364695

http://stackoverflow.com/comment/91719861
score: 0
comment on: http://stackoverflow.com/q/52385299
type: Comment
type: QuestionComment
has text: To norok2: yes, I have looked but the examples (like yours) does not fit with what I was looking for...

http://stackoverflow.com/a/52289094
upvote count: 2
answers question: http://stackoverflow.com/q/52288957
has comment: http://stackoverflow.com/comment/91526445
has body: The problem is that your file is named celery.py. This hides the celery library. Rename your module and this error should go away (assuming you have celery installed).
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/q/52280878
tagged with: python
tagged with: string-matching
downvote count: 0
score: 1
type: Question
answer count: 1
has body: I've written a very naive token string search matcher. It's a little too naive though, as with the following code, it would bring back every artists in the artists list, due to how 'a r i z o n a' is tokenised. import collections import re def __tokenised_match(artist, search_artist): matches = [] if len(re.split(r'[\\\s/-]', search_artist)) &gt; 1: a = [artist.sanitisedOne, search_artist] bag_of_words = [ collections.Counter(re.findall(r'\w+', words)) for words in a] sumbags = sum(bag_of_words, collections.Counter()) print(sumbags) for key, value in sumbags.items(): if len(re.findall(r'\b({k})\b'.format(k=key), search_artist)) &gt; 0 and value &gt; 1: matches.append(artist) if len(matches): return matches artists = [ { 'artist': 'A R I Z O N A', 'sanitisedOne': 'a r i z o n a'}, { 'artist': 'Wutang Clan', 'sanitisedOne': 'wutang clan'} ] search_artist = 'a r i z o n a' for artist in artists: print(__tokenised_match(artist, search_artist)) this'll create a sumbags like this: Counter({'a': 4, 'r': 2, 'i': 2, 'z': 2, 'o': 2, 'n': 2}) Counter({'a': 2, 'wutang': 1, 'clan': 1, 'r': 1, 'i': 1, 'z': 1, 'o': 1, 'n': 1}) this is kind of edge casey, but i wonder how i can tighten up against this kind of edge case. it would be fine for 'wutang clang' to match, but when it's single letters like this... it's a little much and will bring back every artist due to a matching twice.
has answer: http://stackoverflow.com/a/52281419
upvote count: 1
tagged with: string
favorite count: 0
has title: python naive string token matcher
type: UnansweredQuestion

http://stackoverflow.com/q/52282726
score: -1
tagged with: mysql
has comment: http://stackoverflow.com/comment/91513891
has comment: http://stackoverflow.com/comment/91513777
linked to: http://stackoverflow.com/q/4263272
type: Question
has title: Python - Create SQL Table with Capital Letter
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91513869
tagged with: create-table
downvote count: 1
has comment: http://stackoverflow.com/comment/91513810
has comment: http://stackoverflow.com/comment/91513825
upvote count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91513852
has comment: http://stackoverflow.com/comment/91513837
linked to: http://stackoverflow.com/q/6134006
has answer: http://stackoverflow.com/a/52282884
has body: I'm learning the basics of MySQL using Python. When creating tables, they will always be named without any formatting, and ignore formatting I use in the script. How can I adjust my code to add a capital when creating a table? Sorry if this is quite basic, my current knowledge means its hard for me to use the answers of relevant questions such as this. My query: SQL_Create_Table = """ CREATE TABLE Employee """

http://stackoverflow.com/comment/91618505
type: Comment
type: QuestionComment
score: 1
has text: "does the job (but is not pretty)" I clearly have beer goggles :P What do you think is wrong with that? I think the problem overall is interesting, I'm just curious what you think is wrong with that specifically?
comment on: http://stackoverflow.com/q/52335680

http://stackoverflow.com/comment/91770103
type: Comment
comment on: http://stackoverflow.com/q/52393400
has text: thanks i have refere so many book for this
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91760111
type: Comment
has text: It's not a list of strings, it's a string representation of a list
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/52408193

currency
tag name: currency
type: Tag
tags question: http://stackoverflow.com/q/52397832

http://stackoverflow.com/comment/91519519
type: Comment
comment on: http://stackoverflow.com/a/52285545
score: 0
type: AnswerComment
has text: glad to hear it :D

http://stackoverflow.com/q/52317696
linked to: http://stackoverflow.com/q/54030519
has answer: http://stackoverflow.com/a/67107320
favorite count: 0
linked to: http://stackoverflow.com/q/36230492
tagged with: package
tagged with: python
tagged with: module
upvote count: 15
tagged with: python-3.x
downvote count: 0
has answer: http://stackoverflow.com/a/52317799
type: UnansweredQuestion
type: Question
has title: AttributeError: module '' has no attribute '__path__'
score: 15
has body: I'm having a problem which I have no idea how to further debug. I have a project with different purposes, making use of Python 3 among other things. I created a Python package named package. The package's top-directory is located inside myproject/python/. In the filesystem, it has the following structure: - /home/myuser/myproject/python --- package/ ------ __init__.py ------ myutil.py ------ sub_package/ ---------- __init__.py ---------- sub_sub_package/ -------------- __init__.py -------------- myscript.py All __init__.py files are blank, with the exception of the root one (package/__init__.py), which has the following contents: from . import myutil So far so good. The file myscript.py is actually a Python script to run directly. As it resides inside a package, I am executing it as such: cd /home/myuser/myproject/python python -m package.sub_package.sub_sub_package.myscript Now the weird part. The script works as expected. However, after the program finishes, I get the following message: /usr/bin/python3: Error while finding module specification for 'package.sub_package.sub_sub_package.myscript.py' (AttributeError: module 'package.sub_package.sub_sub_package.myscript' has no attribute '__path__') I have been searching online but to no avail. Can't figure out what is causing this message and how to solve it. I am guessing it is some obscure behavior of Python 3's import handling, but have no clue. Any help is greatly appreciated.
has comment: http://stackoverflow.com/comment/100879035
answer count: 2

http://stackoverflow.com/q/52423737
type: Question
has answer: http://stackoverflow.com/a/52423844
score: 0
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52423799
has body: I have two df's df1: index text 1 string1 2 string2 3 string3 4 a 5 string5 6 a df2: index text 4 string4 6 string6 How can I replace the text 'a' in df1 with the values found in df2 based on the index, so that it shows as below. df3: index text 1 string1 2 string2 3 string3 4 string4 5 string5 6 string6
tagged with: python
accepted answer: http://stackoverflow.com/a/52423844
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52423799
has title: Pandas creating a conditional column based on the value of another column

http://stackoverflow.com/a/64608970
has body: Shorter solution: fig.update_layout(margin_pad=10)
answers question: http://stackoverflow.com/q/52391451
score: 8
downvote count: 0
upvote count: 8
type: Answer

http://stackoverflow.com/comment/91626315
comment on: http://stackoverflow.com/q/52339523
type: Comment
type: QuestionComment
has text: Must it support arbitrary size inputs?
score: 1

http://stackoverflow.com/a/58093744
has body: (Python client) This works for me and it returns JSON result = v1.list_namespaced_pod( "default", label_selector="label_key=label_value",watch=False) print(len(result.items))
upvote count: 9
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52387656
score: 9

http://stackoverflow.com/a/52337191
has body: Even easier. Iterate both lists, then iterate the iteration variable :) l1=["michael jackson","nintendo", "michael jackson"] l2 = ["i think michael jackson is cool","i love nintendo","i miss jackson nintendo"] for x in l1: for y in x.split(): if y in x:print('X: '+y)
has comment: http://stackoverflow.com/comment/91622766
has comment: http://stackoverflow.com/comment/91621724
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91622912
has comment: http://stackoverflow.com/comment/91622389
has comment: http://stackoverflow.com/comment/91622503
has comment: http://stackoverflow.com/comment/91622338
has comment: http://stackoverflow.com/comment/91622639
has comment: http://stackoverflow.com/comment/91622535
type: Answer
answers question: http://stackoverflow.com/q/52337094
has comment: http://stackoverflow.com/comment/91622555

http://stackoverflow.com/comment/91717094
comment on: http://stackoverflow.com/q/52386330
type: QuestionComment
type: Comment
score: 8
has text: Since you already mention ``args`` and ``kwargs``, what is stopping you from using them?

http://stackoverflow.com/comment/91728630
score: 0
comment on: http://stackoverflow.com/q/52383984
type: Comment
type: QuestionComment
has text: Creating a ne w thread as the last action of each previous thread is probably not the best approach to a multi-threaded program. You should consider having a thread pool of some sort (of e.g. worker threads) and then re-use them over and over. Your issue also stems from this thread creation, as pointed out in the answer below. You can easily continue past a 100 threads. In debug you may not notice since the timing is completely different.

http://stackoverflow.com/comment/91794300
score: 0
type: AnswerComment
has text: is there some way to get linregres headers at the top? Also, how do I convert this result to csv or xlsx?
type: Comment
comment on: http://stackoverflow.com/a/52422539

http://stackoverflow.com/comment/91538624
has text: @tpaskowski The thing is that I have multiple compression algorithms to test, and I don't want to abort without testing all of them. Seeing which tests pass and which don't gives me more context about the problem; for example if *all* compression algorithms fail then I can assume that the problem is somewhere in my `DataCompressor` base class. That's why I want to skip only these specific tests, not my entire test suite.
score: 0
comment on: http://stackoverflow.com/q/52295214
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91587295
comment on: http://stackoverflow.com/a/52319816
score: 0
type: AnswerComment
type: Comment
has text: @user3203275: umm, there's only 1 such column, and it's the one this generates. If you want to avoid any materialized `x`, just use piRS's `.5 ** (pd.Series(range(len(x))`, but put in 4 for len(x), e.g. `.5 ** pd.Series(range(4))`.

http://stackoverflow.com/comment/91614389
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52328232
type: Comment
has text: You can get the string containing the value using the same regex, and add whatever you want, to get the new number as a string. Something like `old = re.findall(r"(?<=/)\d{3}(?=/)", url)[0] ; new = add_to_string(old, 5)`

http://stackoverflow.com/comment/91544408
type: Comment
type: QuestionComment
has text: The image has been removed @darthbith
score: 1
comment on: http://stackoverflow.com/q/52284234

http://stackoverflow.com/comment/91519340
has text: Check [this](https://stackoverflow.com/questions/4915361/whats-the-difference-between-raw-input-and-input-in-python3-x) to get a clear understanding on the differences.
comment on: http://stackoverflow.com/a/52285452
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52297740
has comment: http://stackoverflow.com/comment/91543459
duplicate of: http://stackoverflow.com/q/28311655
tagged with: pandas
downvote count: 1
linked to: http://stackoverflow.com/q/28311655
accepted answer: http://stackoverflow.com/a/52297788
favorite count: 0
has comment: http://stackoverflow.com/comment/91543337
has body: df = df[~df["column"].str.contains("Total")] TypeError: bad operand type for unary ~: 'float' Why does .str.contains() return a float? What should I be doing here?
tagged with: python
has answer: http://stackoverflow.com/a/52297788
has title: TypeError: bad operand type for unary ~: float
type: AnsweredQuestion
score: 83
upvote count: 84
linked to: http://stackoverflow.com/q/54585333
possible better answer: http://stackoverflow.com/a/69097391
type: Question
has comment: http://stackoverflow.com/comment/91544425
answer count: 2
has answer: http://stackoverflow.com/a/69097391

http://stackoverflow.com/comment/91658566
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52356978
score: 0
has text: Your idea is great, I am so so sorry that I forgot to note that I need to determine the ratio of ones in every mask.

http://stackoverflow.com/a/52360261
has comment: http://stackoverflow.com/comment/91664933
has comment: http://stackoverflow.com/comment/93992372
type: Answer
has comment: http://stackoverflow.com/comment/91665022
has comment: http://stackoverflow.com/comment/92080260
has body: It includes the suspended periods but as far as i think it is the only option to find the process running time.Moreover using this you can even find the running time of even individual lines of code. from time import time t0=time() #your code here print(time()-t0)
downvote count: 1
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/92078339
answers question: http://stackoverflow.com/q/52359903

http://stackoverflow.com/comment/91514790
comment on: http://stackoverflow.com/a/52278752
score: 0
has text: Thanks, I agree. Updated my comment.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91686449
comment on: http://stackoverflow.com/q/52370869
type: QuestionComment
type: Comment
score: 1
has text: One way: keep extracting random value from array, and add it to a variable that holds the partial sum, until the sentinel value is reached. Anyway, please show us what you've tried.

http://stackoverflow.com/q/52320807
score: 0
has comment: http://stackoverflow.com/comment/91590324
answer count: 1
has comment: http://stackoverflow.com/comment/91590218
accepted answer: http://stackoverflow.com/a/52321361
tagged with: typeerror
tagged with: eval
has title: having a string as dict and formatting it through eval (not subscriptable)
tagged with: python
tagged with: dictionary
has body: I never used this kind of command so this error makes me raise an eybrow. I'm trying to refactor my code so instead of an output like 'temp': 22,56, 'temp_max': 25.6, 'temp_min': 19.0, 'temp_kf': None it shows simply 22,56. I found a code that said to us a dict: s = "'temp': 18.72, 'temp_max': 20.0, 'temp_min': 17.0, 'temp_kf': None" data = eval('{{{}}}'.format(s)) temperature1 = str(data['temp']) print(temperature1) where the output comes out like 18,72 So i tried to put my variable t as a string (which if printed gives the same exact output as the dict inside of s, only with current temperature numbers) inside of s.: s = str(t)) data = eval('{{{}}}'.format(s)) temperature1 = str(data['temp']) print(temperature1) And this tells me s is unhashable, so i modified it in s = hash(str(t)) And now I get the error TypeError: 'set' object is not subscriptable Why is this so difficutlt?
tagged with: set
has comment: http://stackoverflow.com/comment/91590429
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52321361
has comment: http://stackoverflow.com/comment/91590072

http://stackoverflow.com/comment/91610053
has text: @MartijnPieters I didm't know that method. I've added to the answer.
comment on: http://stackoverflow.com/a/52329641
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52404501
tagged with: python
has comment: http://stackoverflow.com/comment/91752922
has answer: http://stackoverflow.com/a/52405062
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91752825
has title: How to do pattern searching in a text file using class in python
has body: I am trying to search a pattern using Class. I have a sample text file given. I have to find search a string ('Debug_logs') in each line of text file. Then I have to print date of searched line by using pattern, (\d\d\d\d-\d\d-\d\d) Without using the Class, I am able to do and getting perfect results. But how to make it work with class and objects. import re class text_processing: def __init__(self,file_name): print ("File opened") self.file_name = file_name self.search_pat = 'DEBUG Facebook' def search(self): print ("in sreach function") for line in self.file_name: print (line) if self.search_pat in line: print (self.line) for i in self.search_pat: print re.findall(r"\d\d\d\d-\d\d-\d\d", self.search_pat) break def main(): filename = 'sample1.txt' file_open = open(filename, "r") x = text_processing(file_open) x.search()
accepted answer: http://stackoverflow.com/a/52405062
has comment: http://stackoverflow.com/comment/91752981
has comment: http://stackoverflow.com/comment/91753420
has comment: http://stackoverflow.com/comment/91752815
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91752940
has comment: http://stackoverflow.com/comment/91753472

http://stackoverflow.com/comment/91784521
has text: Thanks @Daniel. But this code throws me an attribute error. AttributeError: 'list' object has no attribute 'keys'
comment on: http://stackoverflow.com/a/52420230
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91568735
type: QuestionComment
has text: Your code will obviously raise a `TypeError; 'NoneType object is not callable` if you replace `return func` by `return func()`, o whatever you "ran" after this modification is not what you think.
score: 1
comment on: http://stackoverflow.com/q/52308643
type: Comment

http://stackoverflow.com/comment/91662383
comment on: http://stackoverflow.com/a/52358950
type: AnswerComment
score: 0
type: Comment
has text: @FedericoCorazza: that's because the process of creating instances isn't handled by `__init__`, that's just a hook called *after* the instance is already created.

http://stackoverflow.com/q/52295418
has comment: http://stackoverflow.com/comment/91541176
has comment: http://stackoverflow.com/comment/91540756
has comment: http://stackoverflow.com/comment/91538904
has title: How to solve the error when i draw graphic in python with using datas in csv file?
score: 0
has comment: http://stackoverflow.com/comment/91541045
tagged with: python-3.x
has body: I think the problem is the following steps, but just in case，I will also write the whole body of my code down blow. The most strange thing is, this code can read over 6000 csv files and a graphic can also successfully show, but when I want more files to be read, then occours an error. The screenshot shows the graphic and the content of the csv files. as you can see, the path = r'C:\Users\AK6PRAKT\Desktop\6daten' includes all datas and path = r'C:\Users\AK6PRAKT\Desktop\daten' includes only parts of them.enter image description here import os from matplotlib import pyplot as pyplot from collections import defaultdict import csv import numpy as np path = r'C:\Users\AK6PRAKT\Desktop\6daten' dirs = os.listdir(path) s = [] x = [] y = [] names = [] ...(ignore some steps for reading the datas from csv files) print(list_temp1,list_temp2) #list_temp1 is the datas of xaxise, and list_temp2 of yaxise. y.append(float(list_temp2)) names.append(list_temp1) x = range(len(names)) pyplot.ylim((0, 40)) my_y_ticks = np.arange(0, 40, 10) pyplot.plot(x,y, linewidth=2) pyplot.xticks(x,names,rotation = 90) fig = pyplot.figure(figsize=(10,10)) pyplot.show() and then...the whole body, and i must say something to declare: I had no background about computer science before, it's really a little bit hard for me to deal with such many datas at the very beginning. Actually i am now doing Internship in a german company and i started to learn python one week ago. I got an assignment from my mentor, I tried to devide the whole assignment into several steps, and I searched the commands of each of the steps and then combine them together with some revising. So, it may seem that I did a lot of useless work. Please be kind in commends(If you have suggestions about that, always glad to hear that of course) import os from matplotlib import pyplot as pyplot from collections import defaultdict import csv import numpy as np path = r'C:\Users\AK6PRAKT\Desktop\6daten' dirs = os.listdir(path) s = [] x = [] y = …
type: UnansweredQuestion
tagged with: python
answer count: 0
type: Question
tagged with: graph

http://stackoverflow.com/comment/112481681
type: AnswerComment
comment on: http://stackoverflow.com/a/52339003
type: Comment
has text: @DrM So I tried your code, and it works, no errors at all. I'm getting the original error when running Jupyter Notebook, so I think I should not run the notebook. I also found I can use the notebook as long as I leave out waitKey()
score: 0

http://stackoverflow.com/comment/91707428
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52381428
has text: I was using postman to test the functionality, I was looking at the wrong tab, thanks for pointing out about the traceback.
score: 0

opencv
type: Tag
tags question: http://stackoverflow.com/q/52276295
tags question: http://stackoverflow.com/q/52384426
tags question: http://stackoverflow.com/q/52351672
tags question: http://stackoverflow.com/q/52352027
tags question: http://stackoverflow.com/q/52297189
tags question: http://stackoverflow.com/q/52337910
tags question: http://stackoverflow.com/q/52370466
tags question: http://stackoverflow.com/q/52316556
tags question: http://stackoverflow.com/q/52420038
tags question: http://stackoverflow.com/q/52349669
tags question: http://stackoverflow.com/q/52279916
tags question: http://stackoverflow.com/q/52378708
tags question: http://stackoverflow.com/q/52419830
tags question: http://stackoverflow.com/q/52397592
tags question: http://stackoverflow.com/q/52273313
tags question: http://stackoverflow.com/q/52316354
tags question: http://stackoverflow.com/q/52373922
tags question: http://stackoverflow.com/q/52424043
tags question: http://stackoverflow.com/q/52422060
tags question: http://stackoverflow.com/q/52279810
tags question: http://stackoverflow.com/q/52278362
tags question: http://stackoverflow.com/q/52427909
tags question: http://stackoverflow.com/q/52297627
tags question: http://stackoverflow.com/q/52318259
tags question: http://stackoverflow.com/q/52309291
tags question: http://stackoverflow.com/q/52362389
tags question: http://stackoverflow.com/q/52408991
tags question: http://stackoverflow.com/q/52322714
tags question: http://stackoverflow.com/q/52417233
tags question: http://stackoverflow.com/q/52287204
tags question: http://stackoverflow.com/q/52389205
tags question: http://stackoverflow.com/q/52366207
tags question: http://stackoverflow.com/q/52330887
tags question: http://stackoverflow.com/q/52411321
tag name: opencv
tags question: http://stackoverflow.com/q/52350987
tags question: http://stackoverflow.com/q/52374197
tags question: http://stackoverflow.com/q/52408909
tags question: http://stackoverflow.com/q/52407041
tags question: http://stackoverflow.com/q/52337870
tags question: http://stackoverflow.com/q/52295414
tags question: http://stackoverflow.com/q/52385215
tags question: http://stackoverflow.com/q/52283791
tags question: http://stackoverflow.com/q/52299833
tags question: http://stackoverflow.com/q/52411916
tags question: http://stackoverflow.com/q/52410303
tags question: http://stackoverflow.com/q/52274378
tags question: http://stackoverflow.com/q/52329002
tags question: http://stackoverflow.com/q/52353883
tags question: http://stackoverflow.com/q/52359728
tags question: http://stackoverflow.com/q/52330472
tags question: http://stackoverflow.com/q/52286017
tags question: http://stackoverflow.com/q/52401920
tags question: http://stackoverflow.com/q/52361299
tags question: http://stackoverflow.com/q/52335553
tags question: http://stackoverflow.com/q/52300087
tags question: http://stackoverflow.com/q/52424812
tags question: http://stackoverflow.com/q/52318311
tags question: http://stackoverflow.com/q/52373571
tags question: http://stackoverflow.com/q/52406045
tags question: http://stackoverflow.com/q/52414542
tags question: http://stackoverflow.com/q/52425952
tags question: http://stackoverflow.com/q/52355071
tags question: http://stackoverflow.com/q/52324937
tags question: http://stackoverflow.com/q/52321305
tags question: http://stackoverflow.com/q/52399546
tags question: http://stackoverflow.com/q/52387590
tags question: http://stackoverflow.com/q/52424348
tags question: http://stackoverflow.com/q/52288066
tags question: http://stackoverflow.com/q/52282250
tags question: http://stackoverflow.com/q/52352876
tags question: http://stackoverflow.com/q/52343936
tags question: http://stackoverflow.com/q/52419070
tags question: http://stackoverflow.com/q/52287359
tags question: http://stackoverflow.com/q/52312304
tags question: http://stackoverflow.com/q/52273971
tags question: http://stackoverflow.com/q/52365190
tags question: http://stackoverflow.com/q/52400542
tags question: http://stackoverflow.com/q/52363732

http://stackoverflow.com/q/52362419
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91769042
tagged with: python
has body: The question is To find the square root of number ‘N’.using this procedure, we must implement the following process: Guess a value for the square root of N Divide N by that guess Average the result with your original guess to get your new guess Go to step 2 and repeat I have set the code to return the Guess once it is within 0.5 of the previous Guess, and if its not to repeat the function. I'm not sure how to make it repeat or how to close the loop. def SqrRt(Number,Guess): while Guess2 == ((Estimate+Guess)/2): if (Estimate - Guess2) &lt;= 0.5: return Guess2 elif (Estimate - Guess2) &gt;= -0.5: return Guess2 else: Estimate = (Number/Guess) Guess2 = Estimate + 1 answer = SqrRt(34567823321421,500000) print(answer)
has comment: http://stackoverflow.com/comment/91669458
has comment: http://stackoverflow.com/comment/91669373
has comment: http://stackoverflow.com/comment/91669088
has answer: http://stackoverflow.com/a/52362742
score: 1
tagged with: loops
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52362828
has comment: http://stackoverflow.com/comment/91670446
tagged with: square-root
has comment: http://stackoverflow.com/comment/91669446
answer count: 2
has title: Loop Function to find a Square root of a number
favorite count: 0

http://stackoverflow.com/a/52318913
answers question: http://stackoverflow.com/q/52318572
score: 0
has body: Changing the dask.get( to dask.threaded.get( fixed my problem but I also really liked mdurant's answer.
type: Answer

http://stackoverflow.com/q/52278966
has comment: http://stackoverflow.com/comment/91505867
favorite count: 0
has answer: http://stackoverflow.com/a/52279087
has answer: http://stackoverflow.com/a/52279043
has comment: http://stackoverflow.com/comment/91505898
tagged with: datetime
tagged with: python
type: AnsweredQuestion
has body: I am trying to get date from pickle file and add one day to the date. The print statement returns 2018-09-10 . Then getting error 'strftime' requires a 'datetime.date' object but received a 'str' on datetime.datetime.strftime(dataHist['last_updated'], '%Y-%m-%d') line Import pickle dataHistFile = open('dat.pkl', 'rb') dataHist = pickle.load(dataHistFile, encoding='bytes') print(dataHist['last_updated']) dt_obj = datetime.datetime.strftime(dataHist['last_updated'], '%Y-%m-%d') date = dt_obj + datetime.timedelta(days=1) 2018-09-10 File "C:/Users/Arvinth Kumar/Downloads/strtsmrt-master/gendata.py", line 81, in init fetchData() File "C:/Users/Arvinth Kumar/Downloads/strtsmrt-master/gendata.py", line 15, in fetchData news.init() File "C:\Users\Arvinth Kumar\Downloads\strtsmrt-master\news.py", line 58, in init getNews() File "C:\Users\Arvinth Kumar\Downloads\strtsmrt-master\news.py", line 38, in getNews dt_obj = datetime.datetime.strftime(dataHist['last_updated'], '%Y-%m-%d') TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str' Please help!
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/52279087
type: Question
answer count: 2
has title: TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'
downvote count: 0
possible better answer: http://stackoverflow.com/a/52279043

http://stackoverflow.com/comment/91552728
type: Comment
comment on: http://stackoverflow.com/q/52302106
score: 0
type: QuestionComment
has text: Thanks for the clarification. Yeh it seems like for the most part I can harmlessly remove all the .keys() and then run 2to3 to fix the prints and raw_inputs. However in this particular instance if an 'echo' exhausts it's repetitions, it will be deleted. Does it matter that it would be the current key being deleted or should that still be avoided?

http://stackoverflow.com/comment/91652437
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52352743
score: 0
has text: in your xPath, you should be using a more robust path like id's or CSS selectors

http://stackoverflow.com/comment/91639002
type: Comment
comment on: http://stackoverflow.com/q/52346617
score: 0
has text: I can't graph it like that. party infants democrat y 156 n 102 ? 9 republican n 134 y 31 ? 3
type: QuestionComment

http://stackoverflow.com/comment/91790970
has text: merge and loc added more columns than i needed, thanks, but update() did the trick for me
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52423799
type: AnswerComment

http://stackoverflow.com/comment/91516785
comment on: http://stackoverflow.com/q/52284282
score: 0
type: Comment
type: QuestionComment
has text: Can you please run `CompProfile.head(10).to_dict()` and paste the output in your question?

http://stackoverflow.com/comment/91660383
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52357831
score: 0
has text: Well as a newbie in Python, all I can say I made this example of my more complex problem. I have a data which is plotted, and I use this procedure when I want to find certain digits with that procedure, like here it suppose to find numbers above 60, and it works. When I use zip function because I have plots so to yaxis I need data from xaxis, everything crack and I stuck at this point. Still not sure if you can understand me correctly.

http://stackoverflow.com/q/52311549
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52411170
type: Question
tagged with: graph
downvote count: 0
tagged with: osmnx
has title: Python: How can I import waterways from OpenStreetMaps as a graph so I can do graph analysis with networkx
has body: Thanks at first for actually taking the time to help me :-) I want to create a undirected graph from waterways for example from the canals of Venice or Amsterdam. OpenStreetMaps has such a graph of a waterway network of these cities, but the OSMnx package does not have such a filter to filter the waterways (or maybe I don't know it yet ;-) ). import osmnx as ox G = ox.graph_from_bbox(52.36309012572587,4.890326718121118,52.36590601699889,4.898316757037793, network_type='all') G_projected = ox.project_graph(G) ox.plot_graph(G_projected) I thought I was possible to just download the whole map, and then filter on just the waterway network. But I don't know how to go further about this. OSMnx would be the best as I then immediately have a graph which I can use for functions of networksx such as Dijkstra's shortest path. Another way I was thinking of was overpass package: import overpass import networkx as nx import matplotlib.pyplot as plt api= overpass.API() data = api.get('way(52.36309012572587,4.890326718121118,52.36590601699889,4.898316757037793);(._;&gt;;)', verbosity='geom') [f for f in data.features if f.geometry['type'] == "LineString"] But this still doesn't work, because I haven't figured out how to filter the data and transform it to a graph for so that networkx can use it. Hope you guys (and girls :-) ) can help me, because I have no clue how to go further. Kind regards, Jeroen
tagged with: overpass-api
accepted answer: http://stackoverflow.com/a/52411170
answer count: 1
tagged with: python
favorite count: 0
upvote count: 1
tagged with: networkx

http://stackoverflow.com/q/52308937
answer count: 1
accepted answer: http://stackoverflow.com/a/52309182
tagged with: python
score: 0
tagged with: qthread
has body: I want to insert text items from a Worker Qthread to a QTableWidget UI in Main thread ?. I want to know the Syntax to create the signal in Main thread , so I can insert the text as well as the row and column from Worker thread by sending via signal class Example(QWidget): def __init__(self): super().__init__() self.myclass2 = myclass2() self.myclass2.start() self.initUI() def initUI(self): self.setGeometry(300, 300, 300, 220) self.setWindowTitle('Icon') self.setWindowIcon(QIcon('web.png')) self.show() class myclass2(QThread): def __init__(self, parent=None): super(myclass2, self).__init__(parent) def run(self): while True: time.sleep(.1) print(" in thread \n") if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
has title: Python Qt - How to insert items in Table widget from another Thread?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52309182
type: Question
tagged with: pyqt

http://stackoverflow.com/q/52422610
tagged with: dataframe
has body: I have it set to "append" but when it's pulling the info from the table, it's throwing the header in for every record. i've read multiple threads on here but haven't found anything that worked. here are 4 of the urls i'm using and the code that i have. http://www.wvlabor.com/new_searches/contractor_RESULTS.cfm?wvnumber=WV057804&amp;contractor_name=&amp;dba=&amp;city_name=&amp;County=&amp;Submit3=Search+Contractors http://www.wvlabor.com/new_searches/contractor_RESULTS.cfm?wvnumber=WV057805&amp;contractor_name=&amp;dba=&amp;city_name=&amp;County=&amp;Submit3=Search+Contractors http://www.wvlabor.com/new_searches/contractor_RESULTS.cfm?wvnumber=WV057806&amp;contractor_name=&amp;dba=&amp;city_name=&amp;County=&amp;Submit3=Search+Contractors http://www.wvlabor.com/new_searches/contractor_RESULTS.cfm?wvnumber=WV057807&amp;contractor_name=&amp;dba=&amp;city_name=&amp;County=&amp;Submit3=Search+Contractors import csv from urllib.request import urlopen import pandas as pd contents = [] with open('WV_urls.csv','r') as csvf: # Open file in read mode urls = csv.reader(csvf) for url in urls: contents.append(url) # Add each url to list contents for url in contents: # Parse through each url in the list. page = urlopen(url[0]).read() df, header = pd.read_html(page) df.to_csv('WV_Licenses_Daily.csv', index=False, header=None, mode='a') However, if i use just 2 urls by themselves, it prints the header and appends the second file. calls_df, header = pd.read_html('http://www.wvlabor.com/new_searches/contractor_RESULTS.cfm?wvnumber=WV057728&amp;contractor_name=&amp;dba=&amp;city_name=&amp;County=&amp;Submit3=Search+Contractors', header=0) calls_df1, header = pd.read_html('http://www.wvlabor.com/new_searches/contractor_RESULTS.cfm?wvnumber=WV057729&amp;contractor_name=&amp;dba=&amp;city_name=&amp;County=&amp;Submit3=Search+Contractors', header=0) calls_df.to_csv('WV_Licenses_Daily.csv', index=False, header=None, mode='w') calls_df1.to_csv('WV_Licenses_Daily.csv', index=False, header=Non…
accepted answer: http://stackoverflow.com/a/52425059
answer count: 1
has comment: http://stackoverflow.com/comment/91790353
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/91789006
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91792318
has answer: http://stackoverflow.com/a/52425059
tagged with: python
has title: Appending rows to CSV with pandas - duplicating headers
score: 0

http://stackoverflow.com/a/52300598
score: 0
has body: If you want to bind to the number 1, just use &lt;Key-1&gt;. the_widget.bind('&lt;Key-1&gt;', some_function)
type: Answer
accepted answer of: http://stackoverflow.com/q/52300457
answers question: http://stackoverflow.com/q/52300457
type: AcceptedAnswer

http://stackoverflow.com/a/52301438
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91550836
answers question: http://stackoverflow.com/q/52300994
has comment: http://stackoverflow.com/comment/91550876
accepted answer of: http://stackoverflow.com/q/52300994
type: Answer
score: 2
downvote count: 0
has body: From the comments it looks like this is what you want: class Example: def __init__(self, func, param1, param2): self.function = lambda: func(self) self.param1 = param1 self.param2 = param2 def doSomething(self): print("hi there") def func(self): self.doSomething() return(self.param1) example = Example(func, 1, 2) example.function() I feel like this is the wrong way to solve whatever problem you want to solve, though.
upvote count: 2

http://stackoverflow.com/comment/91663290
type: QuestionComment
comment on: http://stackoverflow.com/q/52359342
score: 0
has text: Would a manual list not suffice? E.g. `return [report_x, report_y, ...]`? It sounds like you have some sort of manual selection process anyway.
type: Comment

http://stackoverflow.com/a/52327420
type: Answer
has body: Error is not with syntax of window partitioning. Since spark does lazy evaluation, you are getting an error at show(). Meaning error can be any transformation that has been done till then. But I suppose error is mostly caused by java.lang.OutOfMemoryError: Java heap space since partitioning is heavy memory operation. I suggest to read the full error traceback. If my prediction is right you should increase your memory to avoid this issue.
has comment: http://stackoverflow.com/comment/91601728
has comment: http://stackoverflow.com/comment/91606861
score: 0
answers question: http://stackoverflow.com/q/52322216
has comment: http://stackoverflow.com/comment/91604094
has comment: http://stackoverflow.com/comment/91606469

http://stackoverflow.com/a/52287018
has body: You have to give an external input to your code. One easy way for this is using a named pipe (assuming you are on a Linux OS). Create a named file using mkfifo mypipe Now in python, you can open the named pipe import os pipe = os.fdopen(os.open('mypipe', os.O_RDONLY | os.O_NONBLOCK)) You can ignore the O_NONBLOCK flag if your code doesn't have anything else to do while you are waiting for the input. Then it will wait for something to be written in the pipe. So now for waiting you can use a while loop to check if your pipe received the command you want. while pipe.read().rstrip() != "terminalcommand": #something to do while waiting. time.sleep() maybe? Or just pass If you do not know how named pipes behave, you can write something to it just like a normal file. Since now the code waits for terminalcommand, you can do echo terminalcommand &gt; mypipe in the terminal to exit the while loop. If you want to have a single command, create an alias in the terminal. alias stopmyprogram="echo terminalcommand &gt; [directory to mypipe]/mypipe" You can make the alias globally available by adding that line to the file ~/.bash_aliases
answers question: http://stackoverflow.com/q/52272839
score: 0
type: Answer

http://stackoverflow.com/q/52300300
duplicate of: http://stackoverflow.com/q/885546
favorite count: 0
tagged with: python-3.x
has body: What is the simplest way to count the total number of repeating sequential letters in a string? For example, if I have a string 'TCAAAAAAAACAT', I know I can count the total number of 'A's using the count function count(A). However, since I only want the number of 'As' that are sequential in the string (the ones in the middle), what would I do to have the script ignore any letters that are not repeating and sequential?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52300402
linked to: http://stackoverflow.com/q/25537028
linked to: http://stackoverflow.com/q/885546
has title: Counting number of identical sequential letters in a string in python
type: Question
has answer: http://stackoverflow.com/a/52300471
has comment: http://stackoverflow.com/comment/91548438
has comment: http://stackoverflow.com/comment/91548562
score: 0
answer count: 2
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/91690164
comment on: http://stackoverflow.com/q/52372690
type: QuestionComment
has text: OK. What have tried so far in Python? :-)
score: 0
type: Comment

http://stackoverflow.com/q/52305974
has comment: http://stackoverflow.com/comment/91561899
type: UnansweredQuestion
tagged with: python
has title: How can I get data from python generator
tagged with: generator
has comment: http://stackoverflow.com/comment/91559475
has comment: http://stackoverflow.com/comment/91561939
has comment: http://stackoverflow.com/comment/91559343
type: Question
has body: This is a function that use the keyword yield。 I wanna get real data from the function。 How Can I do that? """ # function to reshape features into (samples, time steps, features) Only sequences that meet the window-length are considered, no padding is used. This means for testing we need to drop those which are below the window-length. An alternative would be to pad sequences so that we can use shorter ones """ def gen_sequence(samples, seq_length, seq_cols): # for one id I put all the rows in a single matrix data_matrix = samples[seq_cols].values num_elements = data_matrix.shape[0] # Iterate over two lists in parallel. # For example id1 have 192 rows and sequence_length is equal to 50 # so zip iterate over two following list of numbers (0,112),(50,192) # 0 50 -&gt; from row 0 to row 50 # 1 51 -&gt; from row 1 to row 51 # 2 52 -&gt; from row 2 to row 52 # ... # 111 191 -&gt; from row 111 to 191 for start, stop in zip(range(0, num_elements-seq_length), range(seq_length, num_elements)): yield data_matrix[start:stop, :] this is what i do,but I only get a list of [] # samples, seq_length, seq_cols # generator for the sequences seq_gen = [] for serial_number in hdd['serial_number'].unique(): temp = gen_sequence(hdd[hdd['serial_number']==serial_number], sequence_length, sequence_cols) print(type(temp)) seq_gen.append(list(temp)) # print(seq_gen) the example of dataframe hdd date serial_number ... smart_197_raw smart_198_raw 15 2018-01-01 S30075JX ... 0 0 509 2018-01-02 S30075JX ... 0 0 1000 2018-01-03 S30075JX ... 0 0 1488 2018-01-04 S30075JX ... 0 0 1975 2018-01-05 S30075JX ... 0 0 [5 rows x 16 columns] hdd.columns: 'date','capacity_bytes','serial_number','model','failure','smart_5_raw','smart_197_raw','smart_187_raw', 'smart_7_raw','smart_1_raw','smart_3_raw','smart_9_raw','smart_194_raw','smart_189_raw', 'smart_188_raw','smart_198_raw' temp_samples = hdd[hdd['serial_number']==serial_number]. the result of print(temp_samples.shape) is like this: (90, 16) (90, 16) (2, 16…
tagged with: dataframe
score: 0
has answer: http://stackoverflow.com/a/52306024
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/93260487
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52350395
type: AnswerComment
has text: I'm going to mark this as the answer as I have ended up doing it this way; I still would like to see a way of doing it though.

http://stackoverflow.com/comment/91565156
has text: @lenik Alright then :). I agree with your above comment about the **images** and the intention.
comment on: http://stackoverflow.com/a/52308882
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91637905
has text: Why use the bash script since the selenium command : browser.quit() does the job?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52345425

http://stackoverflow.com/comment/91556525
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52304172
has text: help me please??
score: 0

http://stackoverflow.com/comment/91717107
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52385977
has text: You could make this very modular Leopold - something like https://gist.github.com/puppystack/d9f4148ecfd0863a2972410e0835bbda ?

http://stackoverflow.com/comment/93650960
score: 0
type: AnswerComment
has text: Interesting observation. Didn't think of that. It becomes especially clear when looking at the disassembled function. Good catch. Have a +1.
type: Comment
comment on: http://stackoverflow.com/a/52312650

http://stackoverflow.com/comment/91557237
score: 0
type: AnswerComment
type: Comment
has text: Hi @sacul, That works for this demo example and I think it is putting me on the right direction. Is there a more pythonic way to call the columns than individually typing each reverse compliment? (i.e. if I have two lists of column name and reverse compliment) Thank you very much though. I have tinkering to do!
comment on: http://stackoverflow.com/a/52304831

http://stackoverflow.com/comment/91687833
score: 0
type: AnswerComment
has text: @BowenLiu Sure. I just copied a small part of the `append` function. The full function is highlighted [here](https://github.com/pandas-dev/pandas/blob/v0.23.4/pandas/core/frame.py#L6075-L6211), with the last few lines above being the return statement for `pd.append`. If you look at the full source code you can see that if you call `df.append(df1)`, then `df` is treated as `self` and `other` will reference `df1`, the `DataFrame` or `Series` to append. So `to_concat` is basically just a list of the `DataFrames`, `[df, df1]`, which is passed to `pd.concat`
type: Comment
comment on: http://stackoverflow.com/a/52339382

matplotlib-venn
tag name: matplotlib-venn
tags question: http://stackoverflow.com/q/52317507
type: Tag

http://stackoverflow.com/comment/91676747
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52364612
has text: Sorry use False - not True...
type: Comment

http://stackoverflow.com/q/52414135
score: 0
has body: This are my code button1= tk.Button(text ="1", height=7, width=20) button1.bind("&lt;Button-1&gt;",handle_pin_button) button1.grid(row=3,column=0) button2 = tk.Button(text="2", height=7, width=20) button2.bind("&lt;Button-1&gt;", handle_pin_button) button2.grid(row=3,column=1) button3 = tk.Button(text="3", height=7, width=20) button3.bind("&lt;Button-1&gt;", handle_pin_button) button3.grid(row=3,column=2) And my handle_pin_button is below def handle_pin_button(event): '''Function to add the number of the button clicked to the PIN number entry via its associated variable.''' print("hello") values_for_pin = repr(event.char) print(values_for_pin) print(event.keysym) pin_number_var.set(values_for_pin) value = str(pin_number_var.get()) print(value) # Limit to 4 chars in length if(len(value)&gt;4): pin_number_var.set(value[:4]) its coming like '??' in event.char
answer count: 1
tagged with: python
tagged with: tkinter
type: UnansweredQuestion
tagged with: oop
type: Question
has comment: http://stackoverflow.com/comment/91772015
has title: Not able to get button click value into event in Tkinter
has answer: http://stackoverflow.com/a/52420380

http://stackoverflow.com/comment/91756993
type: QuestionComment
has text: Please provide us with a [complete and verifiable](https://www.stackoverflow.com/help/mcve) example of what you tried
score: 2
comment on: http://stackoverflow.com/q/52406587
type: Comment

http://stackoverflow.com/comment/91639678
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52347018
score: 1
has text: Please make sure to include sample code and sample desired output , in its current format this does not make for a good question, and will likely delay the ability for others to assist.

http://stackoverflow.com/q/52421063
has comment: http://stackoverflow.com/comment/91785886
score: 4
has comment: http://stackoverflow.com/comment/91785725
has comment: http://stackoverflow.com/comment/91785438
favorite count: 0
has body: Aside from learning the Python language itself, I have to learn on the go during daily business how to solve real-life problems with Python and share solutions with other colleagues. Therefore I want while starting my projects from scratch, bootstrap them already with an advanced level for good readability1 and unit testing and have a more or less convenient efficient environment (besides what is the matter of taste, error-prone and well-readable code is here in focus). Here is what I have found so far - what else would you add? Install not Python itself but the Anaconda distro Organize project in a comprehensive well-explained structure: Python project HowTo - Anatomy of a Python project and test methods Document your code - docstring conventions (PEP 257) If you are coming from an object-oriented language, consider Python object and classes Control code quality: Use pylint to check the quality of code, Anaconda has it already on-board Read about Python anti-patterns Consider to add a Dockerfile will required dependencies to demo how your tests run through in a given operating system environment There is also a useful info on what modules' __init__.py file could contain. Answers welcome also pointing out what are Python specific but tool-neutral aspects to consider while integrating with a DevOps toolchain i.e. source control, continuous integration and binary package management. 1 I've noticed that the tag clean code and related are leading to opinionated discussions; so I have decided to follow where possible recommendations available from Google, PEP, and pylint.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91785471
linked to: http://stackoverflow.com/q/2573135
tagged with: coding-style
answer count: 0
has title: Quick start learning Python following industrial standards
downvote count: 1
has comment: http://stackoverflow.com/comment/91785667
tagged with: unit-testing
type: Question
upvote count: 5
has comment: http://stackoverflow.com/comment/91786051

http://stackoverflow.com/q/52282780
tagged with: qt-designer
has body: In the application I am building I have a few "windows" I am working with. I am trying to figure out, according to python/industry standards, how to properly manage them. I have a warning screen, disclaimer screen, main gui, and essentially a message box for communicating errors. What my customer would like to transpire is the program displaying the warning screen (QDialog), and then the disclaimer screen (QDialog) on button click, then the main gui (QMainWindow) after the user has agreed to the disclaimer. The message box is only used when the user needs to be alerted to some event. Note: I am using qt desinger I'm trying to approach this project in a very object orient manner, but I'm struggling to implement this in such a way that it isn't a complete mess. What I intended to do was have a main class that initializes all the pieces of the application at startup, with two controllers (one for the gui and one for the backend processes). So far my gui controller is failing miserably. Initially, I created a class for each of the windows, and then tried creating objects for each in the gui controller. I was forced to move all the classes into a single file, remove the gui controller class code, and utilize this file as the "main" for the application to even get the first window to launch. I am still unable to switch between windows, at best I can close the one that is currently open. What is the proper way to structure an application like this in Python3/PyQt5? Some code: #There used to be another class for gui_controller that instantiated all the below (pyqt5 doesn't work this way as I've come to learn) #Used to be in its own file. class WarningScreen(QDialog, Ui_SomeWarningScreen): def __init__(self, parent=None): super(WarningScreen, self).__init__(parent) self.setupUi(self) self.accept_button_2.clicked.connect(self.acknowledge_warning) def acknowledge_warning(self): window = Disclaimer() window.show() self.close() #Used to be in its own file. class DisclaimerScreen…
answer count: 1
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/52283325
tagged with: pyqt5
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/52283325
type: Question
upvote count: 2
tagged with: pyqt
downvote count: 0
tagged with: python-3.6
has title: What is the proper way to manage windows in pyqt5?

http://stackoverflow.com/a/52332418
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: The correlation metric to use in this case is Pearson's rho. Defined for two binary variables, it is also known as Pearson's correlation coeffecient. rho = (n11*n00 - n10*n01)/sqrt(n11.n10.n01.n00) where n11 (n00) = number of rows with x=1(0) and y=1(0) etc. https://en.wikipedia.org/wiki/Phi_coefficient
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52326174
answers question: http://stackoverflow.com/q/52326174

http://stackoverflow.com/comment/91539833
type: QuestionComment
has text: @norok2 3-channel images of 8-bits per code value are commonly referred to as 24-bit color. It's less common to refer to a 3-channel image of 16-bits per code value as a 48-bit image. I think the OP wants 10-12 bits per code value packed into a 16 bit container, but it's unclear.
comment on: http://stackoverflow.com/q/52295414
score: 0
type: Comment

http://stackoverflow.com/comment/91663593
score: 0
comment on: http://stackoverflow.com/q/52359559
type: Comment
type: QuestionComment
has text: my version is python3.6 @iBug

http://stackoverflow.com/a/52308153
has body: You can use a descriptor class: class get_subclasses: def __get__(self, obj, objtype): return objtype.__subclasses__() class Eukaryota(Kingdom): subtypes = get_subclasses() so that Eukaryota.subtypes would return: [&lt;class '__main__.Plantae'&gt;, &lt;class '__main__.Fungi'&gt;]
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52307665
type: Answer
answers question: http://stackoverflow.com/q/52307665
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91563805

http://stackoverflow.com/comment/91681519
has text: Ok, let me update.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52368556
type: Comment

http://stackoverflow.com/q/52340645
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/52346686
accepted answer: http://stackoverflow.com/a/52346686
downvote count: 0
tagged with: tensorflow
type: Question
score: 2
type: AnsweredQuestion
has title: Eager execution: gradient computation
has body: I m wondering why is this very simple gradient computation not working correctly. It is actually generating a [None, None] vector. Obviously, this is not the desired output. import tensorflow as tf tf.enable_eager_execution() a = tf.constant(0.) with tf.GradientTape() as tape: b = 2 * a da, db = tape.gradient(a + b, [a, b]) print(da) print(db) Expected Output: da = 3 and db = 1
upvote count: 2
answer count: 1

http://stackoverflow.com/q/52283839
score: 0
has comment: http://stackoverflow.com/comment/91519132
has comment: http://stackoverflow.com/comment/91542222
has title: Using the Enter button to navigate, to next frame
type: UnansweredQuestion
tagged with: python
tagged with: tkinter
has body: I need help, im trying to script together a function that when I press the Enter key that it will navigate to the next frame. I am reallllllllly new to python coding and have only dabbled at it for about 3-4 hours. So far I have the following. from tkinter import * class App(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Fullscreen Application") self.pack(fill="both", expand=True, side="top") self.parent.wm_state("zoomed") self.parent.bind("&lt;F11&gt;", self.fullscreen_toggle) self.fullscreen_toggle() self.label = tk.Label(self, text="Program Screen", font=("default",60), fg="black") self.label.pack(side="top", fill="both", expand=True) def fullscreen_toggle(self, event="none"): self.parent.focus_set() self.parent.overrideredirect(True) self.parent.overrideredirect(False) #added for a toggle effect, not fully sure why it's like this. self.parent.attributes("-fullscreen", True) self.parent.wm_attributes("-topmost", 1) def fullscreen_next(self, event="none"): self.parent.overrideredirect(False) self.parent.attributes("-fullscreen", False) self.parent.wm_attributes("-topmost", 0) self.button = Button(self, text="Next", command=self.func) self.button.pack(side='left') master.bind('Return', self.func) def func(self, _event=None): self.parent.bind("&lt;Return&gt;", self.fullscreen_next) self.centerWindow()
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/91519261
has comment: http://stackoverflow.com/comment/91521001
has comment: http://stackoverflow.com/comment/91516019

web-services
type: Tag
tags question: http://stackoverflow.com/q/52329155
tags question: http://stackoverflow.com/q/52335081
tags question: http://stackoverflow.com/q/52357513
tag name: web-services
tags question: http://stackoverflow.com/q/52283411

http://stackoverflow.com/comment/91800909
type: QuestionComment
has text: I guess you could say this is my first official attempt. I have worked with MNIST and that was super easy to use. The reason why I am starting with the geese is...this is kind of my warm up for moving to chess. If I can figure out how to move the geese properly....i'd imagine making the jump to actual chess won't be impossible after this. If i get stuck I will take a step back and do the fox agent for sure!
type: Comment
comment on: http://stackoverflow.com/q/52417056
score: 0

http://stackoverflow.com/q/52272676
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/91492779
has comment: http://stackoverflow.com/comment/91494893
has answer: http://stackoverflow.com/a/52274246
has comment: http://stackoverflow.com/comment/91492918
tagged with: python
has comment: http://stackoverflow.com/comment/91495414
score: 4
has comment: http://stackoverflow.com/comment/91492665
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91493859
linked to: http://stackoverflow.com/q/45086731
has comment: http://stackoverflow.com/comment/91494763
type: Question
upvote count: 4
answer count: 1
downvote count: 0
has title: Combined group by using pandas
has body: Imagine a pandasdata frame given by df = pd.DataFrame({ 'id': range(1, 10), 'mfr': ('a', 'b', 'a', 'c', 'd', 'e', 'd', 'd', 'f'), 'vmn': ('A', 'A', 'B', 'C', 'D', 'E', 'F', 'F', 'D') }) which gives the following table id mfr vmn 0 1 a A 1 2 b A 2 3 a B 3 4 c C 4 5 d D 5 6 e E 6 7 d F 7 8 d F 8 9 f D I wish to determine which id's belong to eachother by grouping either by mfrand/or vmn. I can easily assign a group id by using one of the other by df['groupby_mfr'] = df.groupby('mfr').grouper.group_info[0] df['groupby_vmn'] = df.groupby('vmn').grouper.group_info[0] which gives the following id mfr vmn groupby_mfr groupby_vmn 0 1 a A 0 0 1 2 b A 1 0 2 3 a B 0 1 3 4 c C 2 2 4 5 d D 3 3 5 6 e E 4 4 6 7 d F 3 5 7 8 d F 3 5 8 9 f D 5 3 Now I want to combine this to a new group id so the resulting data frame becomes like this id mfr vmn groupby_mfr groupby_vmn combined_group 0 1 a A 0 0 0 1 2 b A 1 0 0 2 3 a B 0 1 0 3 4 c C 2 2 1 4 5 d D 3 3 2 5 6 e E 4 4 3 6 7 d F 3 5 2 7 8 d F 3 5 2 8 9 f D 5 3 2 The first two rows are the same since vmn are equal. The third are also the same group since row 3 and 1 are the same for vmn. And so on... Note also that this will be run on multiple columns with many rows so performance is much appreciated as well.
favorite count: 0
has comment: http://stackoverflow.com/comment/91492790

http://stackoverflow.com/comment/91717272
score: 1
type: QuestionComment
type: Comment
has text: General algo. 1. Read the text files 2. Read it line by line using loop 3. Split each line by "" 4. Compare to get if you got "ABCD"
comment on: http://stackoverflow.com/q/52385946

http://stackoverflow.com/q/52377617
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/91699892
downvote count: 1
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52377634
possible better answer: http://stackoverflow.com/a/52410685
linked to: http://stackoverflow.com/q/11522933
tagged with: floating-point
has answer: http://stackoverflow.com/a/52410685
type: Question
answer count: 2
has title: How to solve representation errors with floating-point numbers in Python?
tagged with: truncation
favorite count: 0
has body: I need to truncate a decimal at the hundredths place without rounding. I'm using the the method: y = 78.459 x = int(y * 100) / 100 which comes back as 78.45. As it should. However, if I do y = 5.10 x = int(y * 100) / 100 it come back as 5.09, when it should be 5.10 I know that this is a representation error, due to the floating-point inaccuracies in Python, but I don't know how to fix it. If anyone can either help me figure out how to fix representation errors or maybe find a better way to truncate at the hundredths place, I would really appreciate it. Thanks
has answer: http://stackoverflow.com/a/52377634

http://stackoverflow.com/q/52385146
answer count: 4
favorite count: 0
type: UnansweredQuestion
score: -3
has title: How to index a middle character in a list in python
upvote count: 1
has answer: http://stackoverflow.com/a/52385405
has answer: http://stackoverflow.com/a/52385258
has body: Complete the get_mid_letter() function which is passed a list of strings as a parameter. The function returns a string made up of the concatenation of the middle letter of each word from the parameter list. The string returned by the function should be in lowercase characters. If the parameter list is an empty list, the function should return an empty string. def get_mid_letter(a_list): middle_list = [] for item in a_list: middle_index = int(len(item) / 2) middle_letter = a_list.index(middle_index) middle_list = middle_list + [middle_letter] return middle_list.lower() def test_get_mid_letter(): print("1.", get_mid_letter(["Jess", "Cain", "Amity", "Raeann"])) In my case, it shows an error message like "2 is not in the list". What can I do to run my code successfully? Thanks!
has answer: http://stackoverflow.com/a/52385363
has comment: http://stackoverflow.com/comment/91720438
type: Question
downvote count: 4
has answer: http://stackoverflow.com/a/52389589
tagged with: python

http://stackoverflow.com/comment/91756022
has text: can you please share error you are getting @Rushabh
type: Comment
comment on: http://stackoverflow.com/q/52397640
score: 0
type: QuestionComment

http://stackoverflow.com/a/52303642
score: 1
has body: It could be even leaner with: while glossary: user_input = ...
answers question: http://stackoverflow.com/q/52303314
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/91598543
comment on: http://stackoverflow.com/a/52325755
type: AnswerComment
has text: I dont know why this was down voted. This worked for me :) . Is it possible to send the bytes in JSON object ? For me the image is going to be my JSON. Is there any way to send bytes to JSON?
type: Comment
score: 1

http://stackoverflow.com/a/52399665
downvote count: 0
has body: As per https://www.novell.com/support/kb/doc.php?id=7012805 "This message isn't really an error per se, it's more just informational. There is an environmental variable, TCMALLOC_LARGE_ALLOC_REPORT_THRESHOLD, which by default is set to 1073741824 bytes. ~1GB So if there is an allocation that is == or exceeds 1GB of memory, this message will be displayed in the ndsd.log. If there is a great deal of memory in the server, such as greater than 8G - 32GB and/or a fairly large eDirectory database you may see this message more readily. You can just modify the threshold to be greater than the typical alloc that your seeing in the ndsd.log." I'm not sure this is specifically correct given I'm unaware of the environment you're using, I'd say the explanation can be generalized as a warning that 1GB of memory has been allocated by the running application. Further info: https://github.com/gperftools/gperftools/issues/360 Edit: As per the OPS comments, it appears that the same error was produced when allocating 1gb and 21gb so it would be safe to assume that there is a programmatic error that is using all available memory, I would go back and review the code.
has comment: http://stackoverflow.com/comment/91746056
type: Answer
has comment: http://stackoverflow.com/comment/92825662
has comment: http://stackoverflow.com/comment/96710766
has comment: http://stackoverflow.com/comment/92808993
accepted answer of: http://stackoverflow.com/q/52351611
upvote count: 17
has comment: http://stackoverflow.com/comment/92788796
answers question: http://stackoverflow.com/q/52351611
has comment: http://stackoverflow.com/comment/96198298
has comment: http://stackoverflow.com/comment/91746234
has comment: http://stackoverflow.com/comment/91744059
score: 17
has comment: http://stackoverflow.com/comment/92789646
has comment: http://stackoverflow.com/comment/91744994
type: AcceptedAnswer

http://stackoverflow.com/q/52360546
type: UnansweredQuestion
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/91681885
has answer: http://stackoverflow.com/a/68448135
type: Question
tagged with: concatenation
has body: In python, I am trying to build a neural network model using Sequential in keras to perform binary classification. Note that X is a numpy array of time series data 59x1000x3 (samples x timesteps x features) and D is a numpy array of 59x100 (samples x auxillary features). I want to pass the time series through an lstm layer, and then augment at a later layer with the accompanying features (i.e. concatenate two layers). My code to fit the model is below: def fit_model(X, y, D, neurons, batch_size, nb_epoch): model = Sequential() model.add(LSTM(units = neurons, input_shape = (X.shape[1], X.shape[2])) model.add(Dropout(0.1)) model.add(Dense(10)) input1 = Sequential() d = K.variable(D) d_input = Input(tensor=d) input1.add(InputLayer(input_tensor=d_input)) input1.add(Dropout(0.1)) input1.add(Dense(10)) final_model = Sequential() merged = Concatenate([model, input1]) final_model.add(merged) final_model.add(Dense(1, activation='sigmoid')) final_model.compile(loss = 'binary_crossentropy', optimizer = 'adam') final_model.fit(X, y, batch_size = batch_size, epochs = nb_epoch) return final_model I get the following error: ValueError: A Concatenate layer should be called on a list of at least 2 inputs I tried using various permutations of merge/concatenate/the functional api/not the functional api, but I keep landing with some sort of error. I've seen answers using Merge from keras.engine.topology. However, it seems to now be deprecated. Any suggestions to fix the error when using Sequential or how to convert the code to the functional API would be appreciated. Thanks.
downvote count: 0
tagged with: neural-network
has comment: http://stackoverflow.com/comment/91671382
tagged with: keras
has comment: http://stackoverflow.com/comment/91699741
tagged with: lstm
answer count: 1
has comment: http://stackoverflow.com/comment/91666635
tagged with: python
linked to: http://stackoverflow.com/q/52328130
favorite count: 0
has title: Python Keras Multiple Input Layers - How to Concatenate/Merge?

http://stackoverflow.com/a/52302923
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52302352
type: AcceptedAnswer
downvote count: 0
score: 1
has body: A simple answer would be: Estimator hides some TensorFlow concepts, such as Graph and Session, from the user. This is best for newbies since it makes new learners be able to get started much easier (this is nothing to do with the type of dataset, just use tf.dataset API to write an input_fn is sufficient to provide input data for an estimator). Once you have played with tensorflow for a while, understanding how Estimator works and maybe start to use low-level APIs is definitely needed to make you an expert.
type: Answer
answers question: http://stackoverflow.com/q/52302352

http://stackoverflow.com/comment/91634255
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52343765
has text: But that just for one domain .. how i want grab it from raw / another website ? like in my pastebin link.
type: AnswerComment

http://stackoverflow.com/a/52441319
has comment: http://stackoverflow.com/comment/128625362
downvote count: 0
score: 10
answers question: http://stackoverflow.com/q/52291236
upvote count: 10
has body: You can try setting the install target with the --target option like so: pip install --target=C:\Users\Autouser\Appdata\Roaming\Python\site-packages package_name If that doesn't work, another option is to try using --install-option like this: pip install --install-option="--prefix=$PREFIX_PATH" package_name Finally, if all else fails, here's one more way to do it: PYTHONUSERBASE=/path/to/install/to pip install --user You can specify which python version to install the package for by using python2.x -m pip install ... Hopefully one of these helps you! :)
type: Answer

http://stackoverflow.com/a/52357768
upvote count: 3
has comment: http://stackoverflow.com/comment/91662560
accepted answer of: http://stackoverflow.com/q/52357733
has body: dicta = dict() with open("yourfile.txt", "r") as file: for i in file: line, *lines = i.split() dicta[line] = lines .split() will only split it at the spaces the dict look like this {'ABC,_XYZ': ['45.1976844', '-69.458819'], 'AWA,_WES': ['44.946356', '-90.315969'], 'AXA,_WWA': ['36.3055851', '-104.2588701']} here line takes the first value and *lines just takes the rest UPDATE dicta = dict() with open("yourfile.txt", "r") as file: for i in file: line, *lines = i.split() if line in dicta: dicta[line] += lines else: dicta[line] = lines dicta = dict() with open("yourfile.txt", "r") as file: for w,i in enumerate(file): line, *lines = i.split() if line in dicta: dicta[w] = lines else: dicta[line] = lines dicta = list() with open("yourfile.txt", "r") as file: for w,i in enumerate(file): line, *lines = i.split() dicta.append((line,lines))
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91662185
downvote count: 0
has comment: http://stackoverflow.com/comment/91662706
type: Answer
has comment: http://stackoverflow.com/comment/91663306
score: 3
has comment: http://stackoverflow.com/comment/91661420
has comment: http://stackoverflow.com/comment/91662097
has comment: http://stackoverflow.com/comment/91663226
has comment: http://stackoverflow.com/comment/91660922
answers question: http://stackoverflow.com/q/52357733
has comment: http://stackoverflow.com/comment/91660966

http://stackoverflow.com/q/52307443
tagged with: python
tagged with: tweepy
upvote count: 3
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/29928638
has title: How to get the replies for a given tweet with tweepy and python?
type: Question
has answer: http://stackoverflow.com/a/55804977
has body: After some searching I found a way to download the recent tweets from a given user. Now I want to get the replies for each tweet. I know that Twitter API does not provide an endpoint to get replies of a tweet unless we have a premium account. But I could find some workarounds in the internet. I found a way to get few tweets and their replies using Getting tweet replies to a particular tweet from a particular user. This code is also given below. How can I modify my code (getData.py) to save the replies of each tweet along with the tweet in the csv? My code to download a user's tweets as csv (getData.py) import tweepy import csv # Twitter API credentials consumer_key = "###########" consumer_secret = "################" access_key = "#################" access_secret = "#####################" def get_all_tweets(screen_name): # Twitter only allows access to a users most recent 3240 tweets with this method # authorize twitter, initialize tweepy auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api = tweepy.API(auth) # initialize a list to hold all the tweepy Tweets alltweets = [] # make initial request for most recent tweets (200 is the maximum allowed count) new_tweets = api.user_timeline(screen_name=screen_name, count=200) # save most recent tweets alltweets.extend(new_tweets) # save the id of the oldest tweet less one oldest = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(new_tweets) &gt; 0: print "getting tweets before %s" % (oldest) # all subsiquent requests use the max_id param to prevent duplicates new_tweets = api.user_timeline(screen_name=screen_name, count=200, max_id=oldest) # save most recent tweets alltweets.extend(new_tweets) # update the id of the oldest tweet less one oldest = alltweets[-1].id - 1 print "...%s tweets downloaded so far" % (len(alltweets)) # transform the tweepy tweets into a 2D array that will populate the csv outtweets = [[tweet.id_str, …
score: 3
answer count: 1
downvote count: 0
favorite count: 0

header
type: Tag
tag name: header
tags question: http://stackoverflow.com/q/52425932

http://stackoverflow.com/comment/114855842
score: 0
type: AnswerComment
has text: for the --no-<flag> pattern argparse introduced the BooleanOptionalAction https://docs.python.org/3/library/argparse.html#action
type: Comment
comment on: http://stackoverflow.com/a/52403318

http://stackoverflow.com/q/52378745
answer count: 1
accepted answer: http://stackoverflow.com/a/52380041
favorite count: 0
tagged with: jupyter-notebook
has title: Getting error while using watson_developer_cloud in Jupyter Notebook
has answer: http://stackoverflow.com/a/52380041
tagged with: python
tagged with: ibm-watson
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has body: I am trying to use Watson Developer in my Jupyter Notebook, but for some reason I am getting error like this. This is the import part: import json from watson_developer_cloud import AlchemyLanguageV1 After this I am getting error like this: No module named 'watson_developer_cloud' I installed Watson Developer cloud using command shell and ANACONDA prompt. This is the command which I used and it installed successfully. pip install -I watson-developer-cloud==1.0.0 Do I need to configure any thing to avoid this error in my Jupyter Notebook while importing Watson Developer.
upvote count: 1

http://stackoverflow.com/a/52383293
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52383122
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52383122
has body: you can try of shifting the dataframe values to next and previous to check conditions considered dataframe 0 1 0 2018-08-31 1.15839 1 2018-08-30 1.16411 2 2018-08-29 1.16511 3 2018-08-28 1.16618 4 2018-08-27 1.15938 5 2018-08-24 1.15340 [(df[1].ge(df[1].shift())) &amp; df[1].le(df[1].shift(-1))] Out: [0 False 1 True 2 True 3 False 4 False 5 False Name: 1, dtype: bool] if your intention is to just check low value of whole column, you can use df[1].min() Out: 1.1534
type: Answer

http://stackoverflow.com/comment/91734503
type: Comment
has text: like mooing said, it does the same thing as my function, it keeps showing 5 is my score. Would someone mind helping? I can't seem to understand this even though I read through my textbook multiple times
comment on: http://stackoverflow.com/a/52394599
type: AnswerComment
score: 0

http://stackoverflow.com/q/52335033
tagged with: python
has comment: http://stackoverflow.com/comment/91617391
has comment: http://stackoverflow.com/comment/91617410
type: Question
has answer: http://stackoverflow.com/a/52335186
has title: Pandas series index datetime sort
score: 0
tagged with: pandas
answer count: 1
has body: I'm trying to sort a Pandas Series which has dtype=&lt;M8[ns Yet, the sorting goes well for the first few entries, and then becomes quite random. I'm using this code d_series = pd.Series(dates_count) d_series.index = pd.to_datetime(d_series.index) d_series.sort_index(inplace=True) d_series The specific issue is here: 2018-11-04 3 2018-11-06 338 2018-11-07 319 Since we didn't have those months yet. To confirm that the date-notation is not different from what I expect, this is how the series starts: 2018-03-15 2 2018-03-21 1 2018-03-22 1 As you can tell, the formatting is 'yyyy/mm/dd' but somehow going wrong.
tagged with: jupyter-notebook
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91617335
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91617240

http://stackoverflow.com/q/52346313
has answer: http://stackoverflow.com/a/52363091
score: 3
upvote count: 3
has body: I try to understand purpose and usage of bazel. For this project , running command is bazel run -c opt :train_ptn -- --init_model={}. What is the difference between this command and only python train_ptn.py? Also, this github project only contains python scripts and why do we need bazel for running this project?
has title: Difference between running with/without Bazel
type: Question
tagged with: bazel
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91797193
type: QuestionComment
has text: @MosheSlavin , I am not getting any error. it's just all pawns should be placed but only last pawn is placed/visible.
comment on: http://stackoverflow.com/q/52426355
score: 0
type: Comment

http://stackoverflow.com/q/52351710
linked to: http://stackoverflow.com/q/437419
tagged with: python
has title: How to use python code in .NET as a module or package
has comment: http://stackoverflow.com/comment/91648896
score: 0
has answer: http://stackoverflow.com/a/52353034
tagged with: ironpython
type: Question
tagged with: c#
has body: I have a python code that take an image as input and output an image, I want to use this code from .NET. I search online and most of them suggest IronPython. But my code contains tensorflow, opencv and numpy array. So I couldnot import tensorflow, opencv and numpy array in Ironpython. IronPython use python version 2.7. And I want to use my python code in .NET as a module or package. How can I do that?? Can anyone help please?? Thanks.
tagged with: .net
answer count: 1
has comment: http://stackoverflow.com/comment/91649315
type: UnansweredQuestion

http://stackoverflow.com/comment/91494402
score: 0
has text: That wont work. If you want to use that variable, you will have to store it in some storage means like a DB or cache and then retrieve it again from your other task.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52271999

http://stackoverflow.com/q/52313653
accepted answer: http://stackoverflow.com/a/52314232
favorite count: 0
type: Question
tagged with: pandas
has body: I am looking to generate a graph using Python (Pandas and Networkx) for a file folder. So far I have managed to import the data into a DataFrame, where every row corresponds to a folder link, and every column corresponds to a folder: Example: If folder link was: C:\User\some_folder\foo\foo2\last_folder 0 1 2 3 4 5 0 C User some_folder foo foo2 last_folder It would look like the above. What is the graph algorithm that lets me connect the last element to the element before that, and that element to the element before?
tagged with: python
has comment: http://stackoverflow.com/comment/91574671
upvote count: 3
downvote count: 1
answer count: 1
tagged with: networkx
has answer: http://stackoverflow.com/a/52314232
has title: How to form a graph for file folders using Python
has comment: http://stackoverflow.com/comment/91575653
tagged with: dataframe
tagged with: graph
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/52415779
has answer: http://stackoverflow.com/a/52415796
has title: Python: run bash commands sequentially
score: 0
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52415796
type: Question
tagged with: popen
answer count: 1
has body: I am running an executable on a bunch of *.in files in a directory. My script dumps all commands at once. I want to run Popen sequentially after the earlier process has terminated. Here is my script: import glob, os, subprocess import sys, re, math exec_path='/Users/me/path/to/exec' for name in glob.glob("*.in"): print name output = name+'.out' args = [exec_path, '-o', output, name] subprocess.Popen(args) Thanks for your time.

http://stackoverflow.com/a/52375471
answers question: http://stackoverflow.com/q/52374807
has comment: http://stackoverflow.com/comment/91697172
has comment: http://stackoverflow.com/comment/91697281
has comment: http://stackoverflow.com/comment/91697259
has body: You can use a simple for loop and a dictionary no need to overcomplicate it fruits = [ ('Vendor A', 'Apples'), ('Vendor B', 'Apples'), ('Vendor C', 'Bananas'), ('Vendor A', 'Grapes'), ('Vendor A', 'Bananas'), ('Vendor B', 'Oranges') ] dicta = {} for vendor, item in fruits: if vendor not in dicta: dicta[vendor] = [item] else: dicta[vendor].append(item) print(dicta) (xenial)vash@localhost:~/python/stack_overflow$ python3.7 fruits.py {'Vendor A': ['Apples', 'Grapes', 'Bananas'], 'Vendor B': ['Apples', 'Oranges'], 'Vendor C': ['Bananas']}
has comment: http://stackoverflow.com/comment/91696739
upvote count: 1
has comment: http://stackoverflow.com/comment/91696987
has comment: http://stackoverflow.com/comment/91697039
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/a/52390013
has body: The mainloop call stops when your GUI stops. If you want to run some code after the GUI exits just put it after mainloop(). root.mainloop() # starts the GUI and waits for the GUI to close shelve.close() # do something after the GUI closes
answers question: http://stackoverflow.com/q/52387376
score: 0
type: Answer

http://stackoverflow.com/comment/91858998
has text: You could attach a new writer to just the loggers you want.
comment on: http://stackoverflow.com/a/52424323
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52290365
answer count: 2
tagged with: isodate
has answer: http://stackoverflow.com/a/52290857
score: 0
tagged with: python
has title: Check if a variable that can be either duration or timedelta is larger than 0?
has answer: http://stackoverflow.com/a/52290685
type: UnansweredQuestion
has body: I am using isodate to parse durations in isoformat to dates: &gt;&gt;&gt; isodate.parse_duration("P1M") isodate.duration.Duration(0, 0, 0, years=0, months=1) &gt;&gt;&gt; isodate.parse_duration("P1D") datetime.timedelta(1) Months are parsed into duration objects and days are parsed into timedelta objects, as described in the docs: https://pypi.org/project/isodate/ I want to test if the value of a variable that can be of either duration type or timedelta type is larger than 0. The method that works for the duration type does not work for the timedelta type and vice versa. &gt;&gt;&gt; isodate.parse_duration("P1M") &gt; 0 True &gt;&gt;&gt; isodate.parse_duration("P1D") &gt; 0 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: can't compare datetime.timedelta to int &gt;&gt;&gt; isodate.parse_duration("P1M") &gt; timedelta.min Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: can't compare datetime.timedelta to Duration &gt;&gt;&gt; isodate.parse_duration("P1D") &gt; timedelta.min True What is a good solution to this?
type: Question

http://stackoverflow.com/comment/91508294
has text: This explains a bit how overriding of `__str__` works in Python: https://stackoverflow.com/questions/8144026/how-to-define-a-str-method-for-a-class
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52280087

http://stackoverflow.com/q/52390359
upvote count: 6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52390431
type: Question
tagged with: arrays
answer count: 1
downvote count: 0
score: 6
accepted answer: http://stackoverflow.com/a/52390431
has title: How to create a logarithmic spaced array in Python?
has body: I want to create a array that starts from 10^(-2) and goes to 10^5 with logarithmic spaced, like this: levels = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08. 0.09, 0.1, 0.2,..., 10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,200.,300.,400.,500.,600.,700.,800.,900.,1000.,2000.,3000.,4000.,5000.,6000.,7000.,8000.,9000.,10000.,20000.,30000., ..., 100000.] Is there a way to create it without write down every single number? I noticed there is a function in NumPy called logspace, but it doesn't work for me because when I write: levels = np.logspace(-2., 5., num=63) It returns me an array equally spaced, not with a logarithmic increasing.
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/91580658
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52306661
has text: @Joel hi Joel I already update

http://stackoverflow.com/comment/91607532
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52330049
has text: @user58925 I made a bit of a mess, now it should work.

http://stackoverflow.com/comment/91680816
type: Comment
type: QuestionComment
score: 0
has text: You'll want to use groupby and rolling for this. No sample data means no way to show you exactly how.
comment on: http://stackoverflow.com/q/52366219

http://stackoverflow.com/a/52367239
downvote count: 0
has comment: http://stackoverflow.com/comment/91679153
upvote count: 2
type: Answer
score: 2
has body: Okay so: Firstly since you are dealing with floats, you can create a custom step function to use which takes a lower bound, upper bound and step. Then you want to iterate for each SPREAD value, you want to complete a cycle of the STOP range. This can be achieved with a nested loop. In below, I'm just printing out the values, you can look up how to input these values into whatever data structure you wish. def trd(SPREAD,STOP): money = SPREAD * STOP - 10 * STOP return(money) def irange(start, stop, step): x = start while x &lt; stop: yield x x += step def jrange(start, stop, step): x = start while x &lt; stop: yield x x += step for i in irange(2.50,3.50,0.01): for j in jrange(1.00,1.50,0.01): print(i) #current value of SPREAD print(j) #current value of STOP z = trd(i,j) #current value of trd(SPREAD,STOP) print(z)
answers question: http://stackoverflow.com/q/52366926
has comment: http://stackoverflow.com/comment/91679085

http://stackoverflow.com/q/52425681
answer count: 1
tagged with: imapclient
favorite count: 0
accepted answer: http://stackoverflow.com/a/52721819
tagged with: python
has answer: http://stackoverflow.com/a/52721819
score: 2
downvote count: 0
has title: Get content of a mail IMAPCLIENT
type: Question
type: AnsweredQuestion
upvote count: 2
has body: I am using the IMAPclient to get the content of emails, so i made this piece of code : messages = server.search(['FROM', user['email']], charset='UTF-8') if len(messages) &gt; 0: for mail_id, data in server.fetch(messages, ['ENVELOPE']).items(): envelope = data[b'ENVELOPE'] How can I have the content of the emails?

http://stackoverflow.com/q/52360977
has answer: http://stackoverflow.com/a/52361152
answer count: 1
downvote count: 0
favorite count: 0
tagged with: pandas
tagged with: seaborn
tagged with: python
has title: How to arrange 4 Seaborn plots in a grid (Python)?
accepted answer: http://stackoverflow.com/a/52361152
tagged with: grid
type: AnsweredQuestion
upvote count: 5
tagged with: matplotlib
linked to: http://stackoverflow.com/q/63895392
has body: I would like to arrange four Seaborn plots in a 2 x 2 grid. I tried the following code but I got an exception. I would also like to know how to set titles and xlabel, ylabel in the subplots and a title for the overall grid plot. Some toy data: df '{"age":{"76":33,"190":30,"255":36,"296":27,"222":19,"147":39,"127":23,"98":24,"168":29,"177":39,"197":27,"131":36,"36":30,"219":28,"108":38,"198":34,"40":32,"246":24,"109":26,"117":47,"20":26,"113":24,"279":35,"120":35,"7":26,"119":28,"272":24,"66":28,"87":28,"133":28},"Less_than_College":{"76":1,"190":1,"255":0,"296":1,"222":1,"147":1,"127":0,"98":0,"168":1,"177":1,"197":0,"131":1,"36":0,"219":0,"108":0,"198":0,"40":0,"246":0,"109":1,"117":1,"20":0,"113":0,"279":0,"120":0,"7":0,"119":1,"272":0,"66":1,"87":0,"133":0},"college":{"76":0,"190":0,"255":0,"296":0,"222":0,"147":0,"127":1,"98":1,"168":0,"177":0,"197":1,"131":0,"36":1,"219":1,"108":0,"198":1,"40":1,"246":0,"109":0,"117":0,"20":1,"113":1,"279":0,"120":1,"7":1,"119":0,"272":0,"66":0,"87":1,"133":1},"Bachelor":{"76":0,"190":0,"255":1,"296":0,"222":0,"147":0,"127":0,"98":0,"168":0,"177":0,"197":0,"131":0,"36":0,"219":0,"108":1,"198":0,"40":0,"246":1,"109":0,"117":0,"20":0,"113":0,"279":1,"120":0,"7":0,"119":0,"272":1,"66":0,"87":0,"133":0},"terms":{"76":30,"190":15,"255":30,"296":30,"222":30,"147":15,"127":15,"98":15,"168":30,"177":30,"197":15,"131":30,"36":15,"219":15,"108":30,"198":7,"40":30,"246":15,"109":15,"117":15,"20":15,"113":15,"279":15,"120":15,"7":15,"119":30,"272":15,"66":30,"87":30,"133":15},"Principal":{"76":1000,"190":1000,"255":1000,"296":1000,"222":1000,"147":800,"127":800,"98":800,"168":1000,"177":1000,"197":1000,"131":1000,"36":1000,"219":800,"108":1000,"198":1000,"40":1000,"246":1000,"109":1000,"117":1000,"20":1000,"113":800,"279":800,"120":800,"7":800,"119":1000,"272":1000,"66":1000,"87":1000,"133":1000}}' fig = plt.figure() fig.subplots_adjust(hspace=0.4, wspace=0.4) ax = fig.add_subplot(2, 2, 1) ax.sns.distplot(df.Principal) ax = fig.add_subplot…
type: Question
score: 5

http://stackoverflow.com/a/52325580
type: Answer
downvote count: 2
upvote count: 1
answers question: http://stackoverflow.com/q/52325538
score: -1
has comment: http://stackoverflow.com/comment/94176683
has body: Use pdfkit, and then make sure it's included in the Lambda deployment package when you first create your Lambda function.

http://stackoverflow.com/a/52323024
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52322906
has body: Here is a real simple way to do it. str(player.see_inventory()).replace("'", "") Or in the function something like: print(str(element).replace("'", ""))
has comment: http://stackoverflow.com/comment/91593636

snappy
type: Tag
tag name: snappy
tags question: http://stackoverflow.com/q/52293759

http://stackoverflow.com/comment/91525926
comment on: http://stackoverflow.com/a/52288631
has text: You are being very nit picky and I'm happy to improve my answer, but why do you say no memory is allocated?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/52408818
has comment: http://stackoverflow.com/comment/91761999
tagged with: python
has comment: http://stackoverflow.com/comment/91761365
upvote count: 6
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52409524
has body: I have a list of points in 3d coordinates system (X, Y, Z). Moreover, each of them have assigned a float value v, so a single point might be described as (x, y, z, v). This list is represented as a numpy array of shape=(N,4). For each 2d position x, y I need to get the maximum value of v. A straightforward but computationally expensive way would be: for index in range(points.shape[0]): x = points[index, 0] y = points[index, 1] v = points[index, 3] maxes[x, y] = np.max(maxes[x, y], v) Is there a more "numpy" approach, which would be able to bring some gain in terms of performance?
has comment: http://stackoverflow.com/comment/91761768
score: 6
has answer: http://stackoverflow.com/a/52409559
type: Question
has title: Numpy: proper way of getting maximum from a list of points
has comment: http://stackoverflow.com/comment/91761851
has comment: http://stackoverflow.com/comment/91761332
has answer: http://stackoverflow.com/a/52409319
tagged with: numpy
accepted answer: http://stackoverflow.com/a/52409319
tagged with: max
downvote count: 0
has comment: http://stackoverflow.com/comment/91761395
possible better answer: http://stackoverflow.com/a/52409559
has answer: http://stackoverflow.com/a/52409178
favorite count: 0
has comment: http://stackoverflow.com/comment/91761774

loops
tags question: http://stackoverflow.com/q/52323887
tags question: http://stackoverflow.com/q/52279965
tags question: http://stackoverflow.com/q/52334338
tags question: http://stackoverflow.com/q/52387273
tags question: http://stackoverflow.com/q/52393787
tags question: http://stackoverflow.com/q/52355566
tags question: http://stackoverflow.com/q/52305296
tags question: http://stackoverflow.com/q/52378807
tags question: http://stackoverflow.com/q/52294071
tags question: http://stackoverflow.com/q/52383122
tags question: http://stackoverflow.com/q/52363433
tags question: http://stackoverflow.com/q/52319356
tags question: http://stackoverflow.com/q/52401194
tags question: http://stackoverflow.com/q/52414962
tags question: http://stackoverflow.com/q/52278546
tags question: http://stackoverflow.com/q/52360506
tags question: http://stackoverflow.com/q/52378813
type: Tag
tags question: http://stackoverflow.com/q/52396390
tags question: http://stackoverflow.com/q/52425055
tags question: http://stackoverflow.com/q/52408705
tags question: http://stackoverflow.com/q/52412964
tags question: http://stackoverflow.com/q/52286085
tags question: http://stackoverflow.com/q/52306224
tags question: http://stackoverflow.com/q/52405670
tags question: http://stackoverflow.com/q/52379924
tags question: http://stackoverflow.com/q/52306041
tags question: http://stackoverflow.com/q/52362419
tags question: http://stackoverflow.com/q/52347671
tags question: http://stackoverflow.com/q/52422937
tag name: loops
tags question: http://stackoverflow.com/q/52296600
tags question: http://stackoverflow.com/q/52286821
tags question: http://stackoverflow.com/q/52378615
tags question: http://stackoverflow.com/q/52370748
tags question: http://stackoverflow.com/q/52365811
tags question: http://stackoverflow.com/q/52390757
tags question: http://stackoverflow.com/q/52286114
tags question: http://stackoverflow.com/q/52389622
tags question: http://stackoverflow.com/q/52410410
tags question: http://stackoverflow.com/q/52395173
tags question: http://stackoverflow.com/q/52285950
tags question: http://stackoverflow.com/q/52333625
tags question: http://stackoverflow.com/q/52353499
tags question: http://stackoverflow.com/q/52303314

http://stackoverflow.com/comment/91570746
has text: As people are saying, it depends what the bottleneck is. If you are spending most of the time at very low CPU usage, like waiting for a page to download, then look at running multiple threads on a single core. If the script speed is bound by the speed of the CPU and you are doing millions of calculations per second, then go for multiprocessing.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52311339
type: QuestionComment

http://stackoverflow.com/q/52311738
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91573111
tagged with: python
upvote count: 6
has body: I've searched for it on the internet but so far I couldn't find an answer. I have one library which is imported in every other file. let's say the library is imported as import my_lib in the files which uses it. in mylib I'd like to do something like __imported_from__ so the code knows where the import is comming from. I need this for logging purposes (different call different logfile/logname) This would be the log at the moment: 2018-09-13 01:36:00,921 - my_lib - INFO - Start Processing 2018-09-13 01:36:30,921 - my_lib - INFO - Done Processing 2018-09-13 01:37:00,921 - my_lib - INFO - Start Processing 2018-09-13 01:37:30,921 - my_lib - INFO - Done Processing I want my_lib to contain the name from the imported file so it's possible to view where the call is comming from in my logging. Like the example below 2018-09-13 01:36:00,921 - import_from_file_1 - INFO - Start Processing 2018-09-13 01:36:30,921 - import_from_file_1 - INFO - Done Processing 2018-09-13 01:37:00,921 - import_from_file_2 - INFO - Start Processing 2018-09-13 01:37:30,921 - import_from_file_2 - INFO - Done Processing Based on the answer I've wrote 2 lines which provide me with the data I want: import inspect from os.path import basename, splitext imported_from_file = (inspect.stack()[1][1]) if __name__ != '__main__' else False used_from = splitext(basename(imported_from_file))[0] if imported_from_file else __name__
possible better answer: http://stackoverflow.com/a/78670460
has title: Get name from python file which called the import
has answer: http://stackoverflow.com/a/78670460
has answer: http://stackoverflow.com/a/52313172
has comment: http://stackoverflow.com/comment/91571704
downvote count: 1
type: Question
type: AnsweredQuestion
tagged with: python-import
answer count: 2
score: 5
accepted answer: http://stackoverflow.com/a/52313172
favorite count: 0
has comment: http://stackoverflow.com/comment/91571019
has comment: http://stackoverflow.com/comment/91570508

http://stackoverflow.com/q/52428553
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/103441300
tagged with: python
upvote count: 4
has title: Training accuracy graph with model_to_estimator
has comment: http://stackoverflow.com/comment/92229864
answer count: 0
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/92189796
has comment: http://stackoverflow.com/comment/92266593
score: 4
has comment: http://stackoverflow.com/comment/103438094
has body: I have a Keras sequential model and I'm using: model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"]) I can see the training accuracy printed when I use Keras fit() function to train the model. I need to use Estimator API to train the model and I'm using model_to_estimator to convert the model to estimator. Then I use train_and_evaluate() to train the model. However I don't see the accuracy graph in Tensorboard. There's only one accuracy value (from evaluation), so the graph is just a dot. What I need is the accuracy graph from training like the one shown here: https://www.tensorflow.org/guide/custom_estimators#tensorboard I checked the examples and all I could find were ones where they use Estimator API to build the model and use following code to define a summary scalar. # Compute evaluation metrics. accuracy = tf.metrics.accuracy(labels=labels, predictions=predicted_classes, name='acc_op') metrics = {'accuracy': accuracy} tf.summary.scalar('accuracy', accuracy[1]) Does anyone know how to use this with models converted from Keras? I'm using Tensorflow version r1.10.
tagged with: tensorflow-estimator
has comment: http://stackoverflow.com/comment/92164048
downvote count: 0
tagged with: keras
has comment: http://stackoverflow.com/comment/92189737
has comment: http://stackoverflow.com/comment/92324283
favorite count: 0

http://stackoverflow.com/comment/91520517
type: Comment
type: AnswerComment
has text: Thank you. what if I want to have `dict` instead of `list` ?
comment on: http://stackoverflow.com/a/52286134
score: 0

http://stackoverflow.com/comment/91497286
type: AnswerComment
type: Comment
has text: If you use the `matplotlib` object-oriented approach you can avoid using `gcf()` and `gca()`: `fig = plt.figure(figsize=(20, 10); ax = fig.add_subplot(111); ax.bar(...)` See my edit above about this.
comment on: http://stackoverflow.com/a/52274849
score: 0

http://stackoverflow.com/q/52333651
has body: I'm currently trying to set up a communication with a power supply (RND 320-KA3005P) through RS232 with pyserial. The Problem is that after sending "*DIN?", which should return manufacturer, model name and software version, the connection seems to receive nothing. Also no other command was successful. Using the included software, after connecting, a LabView program opens and the device is remote controllable, so I think the problem is in my code. Code Example: Connection parameters as described in the manual. As end-of-line characters I tried "\r\n","\r","\n" which seems to solve many other problems, but here with no success. import io import serial import time import sys ser = serial.Serial('COM4', baudrate = 9600, bytesize=8, timeout=1, stopbits = serial.STOPBITS_ONE, parity = serial.PARITY_NONE, xonxoff = False) eol_char = '\r\n' sio = io.TextIOWrapper(io.BufferedReader(ser),newline=eol_char) while True: sending = input("type:\n") ser.write((sending + eol_char).encode('utf-8')) time.sleep(0.2) ans = sio.read() sys.stdout.write('received: ' + str(ans)) print('\ntry again\n') Which after entering the command gives: type: *DIN? received: try again type: Also when I run the script on the loopback ser = serial.serial_for_url('loop://',timeout=1) ... output: type: *DIN? received: *DIN? try again type: it seems to work fine. I'm using Windows 10 and a USB to RS232 converter. Does anyone have an idea about what I'm missing here? Thanks in advance.
has answer: http://stackoverflow.com/a/52381538
favorite count: 0
tagged with: serial-port
tagged with: python
has title: pyserial: how to receive rs232 answers from power supply correctly
type: AnsweredQuestion
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/59077276
accepted answer: http://stackoverflow.com/a/52381538
type: Question
possible better answer: http://stackoverflow.com/a/59077276
answer count: 2
tagged with: pyserial
downvote count: 0

http://stackoverflow.com/comment/91806955
has text: In what folder is the binary?
score: 0
comment on: http://stackoverflow.com/q/52426245
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52401280
tagged with: path
has answer: http://stackoverflow.com/a/52401442
type: Question
answer count: 2
has title: File paths in python, possible writing styles
has answer: http://stackoverflow.com/a/52401753
tagged with: backslash
has body: I know that the following string definitions represent (python internal) the same (basic knowledge): s1 = "D:\\users\\xy\\Desktop\\PC_daten.txt" s2 = r"D:\users\xy\Desktop\PC_daten.txt" Therefore if you make it e.g. interactive in PythonWin: &gt;&gt;&gt; s1 = "D:\\users\\xy\\Desktop\\PC_daten.txt" &gt;&gt;&gt; s1 'D:\\users\\xy\\Desktop\\PC_daten.txt' &gt;&gt;&gt; print s1 D:\users\xy\Desktop\PC_daten.txt &gt;&gt;&gt; s2 = r"D:\users\xy\Desktop\PC_daten.txt" &gt;&gt;&gt; s2 'D:\\users\\xy\\Desktop\\PC_daten.txt' &gt;&gt;&gt; print s2 D:\users\xy\Desktop\PC_daten.txt Clear for me (understand) But what me confuse is that at the python built in function open all this (partly crazy) path-codings work (interactive tested in PythonWin): &gt;&gt;&gt; a = open("D:\users\xy\Desktop\PC_daten.txt") &gt;&gt;&gt; a &lt;open file 'D:\\users\\xy\\Desktop\\PC_daten.txt', mode 'r' at 0x00000000046989C0&gt; &gt;&gt;&gt; b = open("D:\\users\\xy\\Desktop\\PC_daten.txt") &gt;&gt;&gt; b &lt;open file 'D:\\users\\xy\\Desktop\\PC_daten.txt', mode 'r' at 0x00000000048B2300&gt; &gt;&gt;&gt; c = open(r"D:\users\xy\Desktop\PC_daten.txt") &gt;&gt;&gt; c &lt;open file 'D:\\users\\xy\\Desktop\\PC_daten.txt', mode 'r' at 0x00000000048B20C0&gt; &gt;&gt;&gt; d = open(r"D:\\users\\xy\\Desktop\\PC_daten.txt") &gt;&gt;&gt; d &lt;open file 'D:\\\\users\\\\xy\\\\Desktop\\\\PC_daten.txt', mode 'r' at 0x00000000048B2390&gt; My questions: Where is this behaviour documented? Have anybody background-informations? Tests was made at Windows 7 OS and with PythonWin 2.7.13
tagged with: string
tagged with: python
type: UnansweredQuestion
score: 0

http://stackoverflow.com/comment/118302060
type: Comment
has text: A tedious solution at best
comment on: http://stackoverflow.com/a/52324509
score: 0
type: AnswerComment

seq2seq
tag name: seq2seq
type: Tag
tags question: http://stackoverflow.com/q/52324322

http://stackoverflow.com/q/52306826
favorite count: 0
linked to: http://stackoverflow.com/q/43838785
accepted answer: http://stackoverflow.com/a/58966051
tagged with: python
type: AnsweredQuestion
score: 3
has title: Python Eve - REST API additional_lookup not working
downvote count: 0
has body: I am facing the exact same issue that is described here. I have user_creds endpoint for my API. When I visit localhost:5000/user_creds/, I can see all the documents in that collection. But when I do something like localhost:5000/user_creds/someemail@gmail.com, I always get a 404 Not Found response. user_creds domain in settings.py looks like this: 'user_creds': { 'schema': { 'email': { 'type': 'string', 'regex': r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", 'required': True, 'unique': True, }, 'password': { 'type': 'string', 'required': True }, } 'resource_methods': ['GET', 'POST'], 'item_methods': ['GET', 'PATCH', 'PUT'], 'additional_lookup': { 'url': 'regex("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$")', 'field': 'email' } } I am following the example given here but cant figure out where I am going wrong. Also, if I visit this URL: http://127.0.0.1:5000/user_creds?email==%22abcd12@gmail.com%22, I get all the documents in the collection instead of getting just a single document which matches the email regex. If I visit this http://127.0.0.1:5000/user_creds?where=email==%22abcd12@gmail.com%22, I am getting the desired response.
has answer: http://stackoverflow.com/a/58966051
type: Question
answer count: 1
tagged with: flask
has comment: http://stackoverflow.com/comment/91909104
upvote count: 3
tagged with: rest
tagged with: eve

http://stackoverflow.com/comment/91655877
has text: yeah just a typo. hmm, well we might be out of luck then
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52355588
type: AnswerComment

http://stackoverflow.com/comment/93965113
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52412796
score: 2
has text: To use `safe_load()` I had to modify the above like so... `yaml.add_implicit_resolver('!path', path_matcher, None, SafeLoader)` `yaml.add_constructor('!path', path_constructor, SafeLoader)`

http://stackoverflow.com/a/71294167
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52410927
has body: Just in case someone is interested in deleting all the lines, and only find this question after searching, the easy way would be using ''' for all the codes between the two lines, and then use the triangle on the left to suppress, so you could delete in one go.

http://stackoverflow.com/q/52338795
score: 0
answer count: 3
tagged with: string
has body: sentence = input ('Please enter a sentce: ') change = input ('What word do you want to change: ') replace = input ('What do you want to replace it with: ') n_s = replace(change,replace) print (n_s) I've got this but when I run it it says n_s = replace(change,replace) TypeError:'str' object is not callable
has comment: http://stackoverflow.com/comment/91624817
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52338854
has answer: http://stackoverflow.com/a/52338852
type: Question
has answer: http://stackoverflow.com/a/52338884
has title: How do I replace a user entered sentence with a user entered word. str object not callable

http://stackoverflow.com/q/52403589
tagged with: signal-processing
has comment: http://stackoverflow.com/comment/91893322
score: 11
tagged with: numpy
downvote count: 0
type: UnansweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/91889560
has body: How to apply a lowpass filter, with cutoff frequency varying linearly (or with a more general curve than linear) from e.g. 10000hz to 200hz along time, with numpy/scipy and possibly no other library? Example: at 00:00,000, lowpass cutoff = 10000hz at 00:05,000, lowpass cutoff = 5000hz at 00:09,000, lowpass cutoff = 1000hz then cutoff stays at 1000hz during 10 seconds, then cutoff decreases down to 200hz Here is how to do a simple 100hz lowpass: from scipy.io import wavfile import numpy as np from scipy.signal import butter, lfilter sr, x = wavfile.read('test.wav') b, a = butter(2, 100.0 / sr, btype='low') # Butterworth y = lfilter(b, a, x) wavfile.write('out.wav', sr, np.asarray(y, dtype=np.int16)) but how to make the cutoff vary? Note: I've already read Applying time-variant filter in Python but the answer is quite complex (and it applies to many kinds of filter in general).
has comment: http://stackoverflow.com/comment/91896832
type: Question
tagged with: python
upvote count: 11
has answer: http://stackoverflow.com/a/52459786
linked to: http://stackoverflow.com/q/52468563
answer count: 2
linked to: http://stackoverflow.com/q/18128057
has comment: http://stackoverflow.com/comment/91852094
has title: Lowpass filter with a time-varying cutoff frequency, with Python
tagged with: scipy
has comment: http://stackoverflow.com/comment/91847649
has answer: http://stackoverflow.com/a/52451378

http://stackoverflow.com/comment/91630436
type: Comment
type: AnswerComment
has text: This produces an identical result to jezrael's possible solution. I'm looking for a method or set of methods to combine all purchases of a gender while still accounting for certain members of the players listed having purchased multiple items.
score: 0
comment on: http://stackoverflow.com/a/52333196

http://stackoverflow.com/comment/91614499
has text: "I have used several codes that I have seen on the internet and none of them serve me" Well that's indeed the problem with "copy/paste programming" xD
score: 1
comment on: http://stackoverflow.com/q/52331628
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91585435
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52318744
score: 0
has text: @user2357112: also a possibility, I guess. Still, I'd consider that a bug in PyCharm then, if the UI can't monitor variables properly.

http://stackoverflow.com/comment/91789848
type: QuestionComment
has text: Just checking that you're aware of the [`datetime`](https://docs.python.org/3/library/datetime.html) module?
type: Comment
comment on: http://stackoverflow.com/q/52423516
score: 0

http://stackoverflow.com/comment/91737580
type: AnswerComment
score: 0
has text: Sorry about my low reputation, currently below 15. Stackoverflow didn't post my upvote. I really appreciate your help!
type: Comment
comment on: http://stackoverflow.com/a/52396304

http://stackoverflow.com/q/52372152
score: 0
has body: Suppose you have a dictionary that has a list of dates (pulled from excel as floats) as a value within a sub-dictionary of counties. master_dictionary = {'MO': { 'Lincoln County': [43378.0, 43378.0, 43378.0], 'Franklin County': [43357.0, 43357.0], 'Camden County': [43208.0, 43208.0, 43208.0], 'Miller County': [43208.0], 'Morgan County': [43208.0, 43208.0]}, 'WI': {'Marathon County': [43371.0, 43371.0, 43371.0, 43371.0, 43371.0]}, 'NJ': {'Atlantic County': [43340.0, 43340.0]}} My goal is to 1) get the max value of these 'date' and, 2) convert the max 'date' to a '%M/%D/%Y' value using datetime.strftime. I am able to get the max value and convert it, but I am trying to get it to update the date values in the master dictionary. How can I do this? for key, value in master_dictionary.items(): counties = value for k, v in counties.items(): d = max(v) year, month, day, hour, minute, second = xldate_as_tuple(d, book_datemode) n_date = rawDate = (str(month) + "/" + str(day) + "/" + str(year)) print(n_date)
answer count: 3
favorite count: 0
has comment: http://stackoverflow.com/comment/91689398
accepted answer: http://stackoverflow.com/a/52372467
has comment: http://stackoverflow.com/comment/91689157
upvote count: 1
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52373689
type: AnsweredQuestion
tagged with: list
has title: Updating values in a dictionary list
tagged with: updates
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/52372761
has answer: http://stackoverflow.com/a/52372761
has answer: http://stackoverflow.com/a/52372467
tagged with: python-3.6

http://stackoverflow.com/comment/91520337
has text: Your logic does work, just `print(output)` at the end.
type: Comment
comment on: http://stackoverflow.com/q/52286057
score: 4
type: QuestionComment

http://stackoverflow.com/a/52396690
type: Answer
has body: Using the numjs package that strives to transplant NumPy onto JS (specifically, ndarray.pick from the underlying scijs/ndarray package): var m = nj.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]]]); console.log(m.pick(0,null,null)); Prints: "[[0,1,2],[3,4,5],[6,7,8]]"
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52390892
upvote count: 1
answers question: http://stackoverflow.com/q/52390892
type: AcceptedAnswer

http://stackoverflow.com/comment/91678002
type: AnswerComment
score: 0
type: Comment
has text: @multigoodverse numpy is not written in Python is mostly written in C. *.so is the shared object library created in C and that is imported into Python.
comment on: http://stackoverflow.com/a/52365859

http://stackoverflow.com/a/52389778
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91731125
has body: Turns out that accessing class attributes from within a class is impossible, as the class has yet to be executed when the decorator is called. So the original goal - using a decorator within a class to access class attributes - does not seem to be possible. However, thanks to jdehesa for pointing me to a workaround that allows access to the class attributes using a class decorator, here: Can a Python decorator of an instance method access the class?. I was able to use the class decorator to alter the specific method's docstring using class attributes like so: def class_decorator(cls): for name, method in cls.__dict__.items(): if name == 'example': # do something with the method method.__doc__ = "{} is new for function {} in class {}".format(method.__doc__, name, cls.__name__) # Note that other class attributes such as cls.__base__ # can also be accessed in this way return cls @class_decorator class Test(): def example(self, examplearg=1): """Docstring""" print(Test().example.__doc__) # Returns "Docstring is new for function example in class Test"
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91725161
answers question: http://stackoverflow.com/q/52388654
accepted answer of: http://stackoverflow.com/q/52388654

http://stackoverflow.com/comment/91656889
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52355513
score: 0
has text: Alright. Also, I think it's not reasonable to expect near zero loss without any hidden layers, right?

http://stackoverflow.com/q/52388791
score: -4
tagged with: python
tagged with: integration
tagged with: node.js
type: Question
downvote count: 4
upvote count: 0
has body: Is where a way to use python api in node js? I want use this api - https://github.com/billy-yoyo/RainbowSixSiege-Python-API for my node js app.
tagged with: javascript
has title: How can I use python api in node.js?
answer count: 1
has answer: http://stackoverflow.com/a/52388924
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52322714
type: Question
tagged with: opencv
has body: Im working on face tracking robot with raspberry pi 3 project. I have done with face detection part with opencv on raspberry pi . i need help with the motor control
downvote count: 4
upvote count: 0
answer count: 1
tagged with: raspberry-pi3
has answer: http://stackoverflow.com/a/52457605
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Face Recognition and tracking with raspberry pi3
score: -4
has comment: http://stackoverflow.com/comment/91592995

http://stackoverflow.com/a/52397662
upvote count: 1
downvote count: 0
type: Answer
score: 1
has body: Why not just def not_last(x): return x // 10
answers question: http://stackoverflow.com/q/52397573

http://stackoverflow.com/comment/91519767
has text: I'm running 3.6.5 @RoryDaulton
comment on: http://stackoverflow.com/a/52285452
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52395206
answer count: 1
has comment: http://stackoverflow.com/comment/91735838
tagged with: python-3.x
has title: How to categorize timestamp hours into day and night?
tagged with: python
type: AnsweredQuestion
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/91735722
has body: I was wondering how can we categorize timestamp column in a Data frame into Day and Night column on the basis of time? I am trying to do so but unable to make a new column complete with the same number of entries. d_call["time"] = d_call["timestamp"].apply(lambda x: x.time()) d_call["time"].head(1) 0 17:10:52 Name: time, dtype: object def day_night(name): for i in name: if i.hour &gt; 17: return "night" else: return "day" day_night(d_call["time"]) 'day' d_call["Day / Night"]= d_call["time"].apply(lambda x: day_night(x)) I want to get the entire series of the column but getting the first index only.
score: 0
tagged with: data-analysis
has answer: http://stackoverflow.com/a/52400512
accepted answer: http://stackoverflow.com/a/52400512

http://stackoverflow.com/comment/91755807
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52405435
has text: why is action parameter blank here ?

http://stackoverflow.com/q/52338113
has comment: http://stackoverflow.com/comment/91623563
answer count: 1
has comment: http://stackoverflow.com/comment/91623553
accepted answer: http://stackoverflow.com/a/52338175
tagged with: python
type: AnsweredQuestion
has body: So here is my situation, I am trying to make a pretty basic text-based adventure RPG game as something to just get used to If &amp; Else statements etc. What I am wondering is why I can use the "for letter in 'word'" to pretty much prepare my program for any general input made by the user. For example, If I ask the player if they are ready to begin(Y/N): Instead of the user being forced to put a capital Y or a or a capital N for the program to work without an error, how would I generalize it where they can put anything like "YesYESyeaYEAYEAHyeahSUREsure" etc so if the program sees any sequence of those letters it will still work as if the inputted "Y" I'm not the best at explaining things so if there are any questions feel free to ask. The code I am currently working with is below! :) try: import time import sys except ImportError: pass loadSeq = False startSeq = "" while startSeq != 'Y' or startSeq != 'y': startSeq = str(input("Start Message: Are you ready to begin? ")) for letter in 'YESyes': if startSeq == 'Y': Code here elif startSeq == str('N') or startSeq == str('n'): Code here else: break
has title: How would allow for a string input that doesn't need to be exact for my program to run in a If & Else statement?
score: 0
type: Question
has answer: http://stackoverflow.com/a/52338175
has comment: http://stackoverflow.com/comment/91623537
has comment: http://stackoverflow.com/comment/91623488

http://stackoverflow.com/comment/91742699
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52399156
type: AnswerComment
has text: But I already know that `SIGINT` is causing the script to shut down though, I just don't know why is `SIGINT` send to the script

pyopengl
tags question: http://stackoverflow.com/q/52370988
tag name: pyopengl
tags question: http://stackoverflow.com/q/52291221
type: Tag

http://stackoverflow.com/a/52376362
score: 0
type: Answer
has body: I was actually able to figure it out. I think the problem is that I was trying to read in a directory and not an actual file. the path I was using ended at the folder and not the file. loc = ("C:/Users/mleef/Desktop/python text/practice_data.xlsx") wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) sheet.cell_value(0,0) print(sheet.nrows) output: 1429 (number if rows in the data set)
answers question: http://stackoverflow.com/q/52375993
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52375993

http://stackoverflow.com/q/52276566
linked to: http://stackoverflow.com/q/9001509
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91502633
has comment: http://stackoverflow.com/comment/91502587
duplicate of: http://stackoverflow.com/q/9001509
type: Question
has comment: http://stackoverflow.com/comment/91501256
linked to: http://stackoverflow.com/q/47148473
has comment: http://stackoverflow.com/comment/91501161
has comment: http://stackoverflow.com/comment/91500871
has comment: http://stackoverflow.com/comment/91501526
has comment: http://stackoverflow.com/comment/91500896
has comment: http://stackoverflow.com/comment/91501420
has comment: http://stackoverflow.com/comment/91501557
score: 0
tagged with: dictionary-comprehension
has title: Workaround dictionary sorting
has comment: http://stackoverflow.com/comment/91501613
tagged with: python
has comment: http://stackoverflow.com/comment/91500994
tagged with: dictionary
has body: Through quick research I found out that there is no way to truly sort a dictionary. However there are workarounds and I used the one suggested here by user Malik. I ran this test and got: &gt;&gt;&gt; test={"im2":1,"im4":2,"im3":-1,"im1":5} &gt;&gt;&gt; {x:test[x] for x in sorted(test)} {'im1': 5, 'im2': 1, 'im3': -1, 'im4': 2} which is exactly the behaviour I'm looking for. Any help or suggestion is greatly appreciated. However, when I try to incorporate it into my code, nothing changes. Here's the code: def loop_solution(filenames): mydic={'im'+str(index): import_file_astro(filename) for index, filename in enumerate(filenames, start=1) if filename is not None} print mydic mydic_upd={'im'+str(i):mydic.values()[0] for i in range(1,5) if 'im'+str(i) not in mydic} mydic=dict(mydic, **mydic_upd) print mydic mydic={y:mydic[y] for y in sorted(mydic)} print mydic return loop_solution([None,'CO21_m100_100_final',None,'CO43_m100_100_final']) and the output: {'im2': &lt;astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b6dc690&gt;, 'im4': &lt;astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b7461d0&gt;} {'im1': &lt;astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b6dc690&gt;, 'im3': &lt;astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b6dc690&gt;, 'im2': &lt;astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b6dc690&gt;, 'im4': &lt;astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b7461d0&gt;} {'im1': &lt;astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b6dc690&gt;, 'im3': &lt;astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b6dc690&gt;, 'im2': &lt;astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b6dc690&gt;, 'im4': &lt;astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b7461d0&gt;} I'm at a loss of what could be the problem.

http://stackoverflow.com/q/52301486
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52301776
has comment: http://stackoverflow.com/comment/91550832
score: 0
tagged with: python
type: AnsweredQuestion
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91550849
has answer: http://stackoverflow.com/a/52301776
has body: parser.add_argument('-i', required=True) # One directory path parser.add_argument('-d', required=True) # Output database path parser.add_argument('-t', required=True) # DDL-script path parser.add_argument('-c -i', required=True) # Another directory path I run .py script like this: python.exe s.py -c -i D:\Temp\dir1 -d D:\Temp\out.db -t D:\Temp\ddl.sql -i D:\Temp\dir2 and get error: usage: s.py [-h] -i I -d D -t T -c -i C _I s.py: error: argument -c -i: expected one argument How can i use it without rename argument names??
has title: Python, argparse. What about -opt1 -part-of-opt1 <parameter>?
possible better answer: http://stackoverflow.com/a/52301773
tagged with: argparse
has answer: http://stackoverflow.com/a/52301773

http://stackoverflow.com/comment/91525627
comment on: http://stackoverflow.com/q/52288873
score: 0
has text: If your goal is to produce groups of identical files, why do you use this inefficient intermediate step of generating these much larger lists of `jsonfilexx = jsonfileyy`?
type: Comment
type: QuestionComment

tkinter
tags question: http://stackoverflow.com/q/52421142
tags question: http://stackoverflow.com/q/52351441
tags question: http://stackoverflow.com/q/52343936
tags question: http://stackoverflow.com/q/52330319
tags question: http://stackoverflow.com/q/52375035
tags question: http://stackoverflow.com/q/52379072
tags question: http://stackoverflow.com/q/52289543
tags question: http://stackoverflow.com/q/52427132
tags question: http://stackoverflow.com/q/52355347
tags question: http://stackoverflow.com/q/52311774
tags question: http://stackoverflow.com/q/52285092
tag name: tkinter
tags question: http://stackoverflow.com/q/52372931
tags question: http://stackoverflow.com/q/52287168
tags question: http://stackoverflow.com/q/52350507
tags question: http://stackoverflow.com/q/52283839
tags question: http://stackoverflow.com/q/52281528
tags question: http://stackoverflow.com/q/52289877
tags question: http://stackoverflow.com/q/52370465
tags question: http://stackoverflow.com/q/52302871
tags question: http://stackoverflow.com/q/52280437
tags question: http://stackoverflow.com/q/52338187
tags question: http://stackoverflow.com/q/52381046
tags question: http://stackoverflow.com/q/52322461
tags question: http://stackoverflow.com/q/52348437
tags question: http://stackoverflow.com/q/52331554
tags question: http://stackoverflow.com/q/52309027
tags question: http://stackoverflow.com/q/52378519
tags question: http://stackoverflow.com/q/52412907
tags question: http://stackoverflow.com/q/52335799
tags question: http://stackoverflow.com/q/52391813
tags question: http://stackoverflow.com/q/52319559
tags question: http://stackoverflow.com/q/52303146
tags question: http://stackoverflow.com/q/52365108
tags question: http://stackoverflow.com/q/52285402
tags question: http://stackoverflow.com/q/52336274
tags question: http://stackoverflow.com/q/52375466
tags question: http://stackoverflow.com/q/52401176
tags question: http://stackoverflow.com/q/52349684
tags question: http://stackoverflow.com/q/52370396
tags question: http://stackoverflow.com/q/52296812
tags question: http://stackoverflow.com/q/52414546
tags question: http://stackoverflow.com/q/52305454
tags question: http://stackoverflow.com/q/52395321
tags question: http://stackoverflow.com/q/52300878
tags question: http://stackoverflow.com/q/52314309
tags question: http://stackoverflow.com/q/52356171
tags question: http://stackoverflow.com/q/52426355
tags question: http://stackoverflow.com/q/52396923
tags question: http://stackoverflow.com/q/52387915
tags question: http://stackoverflow.com/q/52314762
tags question: http://stackoverflow.com/q/52272942
tags question: http://stackoverflow.com/q/52392637
tags question: http://stackoverflow.com/q/52286904
tags question: http://stackoverflow.com/q/52300457
tags question: http://stackoverflow.com/q/52358154
tags question: http://stackoverflow.com/q/52282334
tags question: http://stackoverflow.com/q/52325936
tags question: http://stackoverflow.com/q/52405089
tags question: http://stackoverflow.com/q/52345792
tags question: http://stackoverflow.com/q/52303983
tags question: http://stackoverflow.com/q/52317890
tags question: http://stackoverflow.com/q/52414135
tags question: http://stackoverflow.com/q/52344680
tags question: http://stackoverflow.com/q/52369623
tags question: http://stackoverflow.com/q/52296794
tags question: http://stackoverflow.com/q/52349030
tags question: http://stackoverflow.com/q/52301848
tags question: http://stackoverflow.com/q/52345195
type: Tag
tags question: http://stackoverflow.com/q/52383017
tags question: http://stackoverflow.com/q/52323647
tags question: http://stackoverflow.com/q/52387376
tags question: http://stackoverflow.com/q/52350494
tags question: http://stackoverflow.com/q/52421166
tags question: http://stackoverflow.com/q/52402365
tags question: http://stackoverflow.com/q/52304036

http://stackoverflow.com/q/52273801
has comment: http://stackoverflow.com/comment/91494993
upvote count: 1
duplicate of: http://stackoverflow.com/q/42179665
has title: Rotating Rows and columns pandas
has comment: http://stackoverflow.com/comment/91494899
type: UnansweredQuestion
tagged with: pandas
downvote count: 0
score: 1
favorite count: 0
has body: Hi i have been trying to figure out how to rotate my rows and columns.I tried using the transpose but it didnt work. My dataframe looks like this Country | Rates 2015 | Rates2016 | Rates2017 | GDP 2015| GDP 2016 | GDP2017 World | 6 | 7 | 8 | 2355 | 1235 | 324325 Isit possible to change to | Rates | GDP 2015 | 6 | 2355 2016 | 7 | 1235 2017 | 8 | 34132 Yeah this is what im trying to do basically
type: Question
tagged with: python
answer count: 1
linked to: http://stackoverflow.com/q/42179665
has answer: http://stackoverflow.com/a/52273938

http://stackoverflow.com/comment/91606799
has text: I want a selector in the admin with the values from the property `test_field`
comment on: http://stackoverflow.com/q/52329542
type: Comment
type: QuestionComment
score: 0

append
tags question: http://stackoverflow.com/q/52293475
tags question: http://stackoverflow.com/q/52286114
tag name: append
tags question: http://stackoverflow.com/q/52370360
tags question: http://stackoverflow.com/q/52413045
tags question: http://stackoverflow.com/q/52276027
type: Tag

http://stackoverflow.com/comment/91692906
type: QuestionComment
has text: In that case, you should probably be making some attempts on your side and asking for clarification when it doesn't work. The point of curiosity is to discover things about the language for yourself.
type: Comment
comment on: http://stackoverflow.com/q/52373938
score: 2

http://stackoverflow.com/comment/91740361
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52398079
type: QuestionComment
has text: That will depend on what `_` is defined as.

http://stackoverflow.com/q/52399825
tagged with: scrapy
has title: How to crawl multiple websites in different timing in scrapy
type: Question
has body: I have multiple websites stored in database with different crawl time like every 5/10 minutes for every websites. I have created spider to crawl and running with cron. It will take all the websites from database and run crawling parallely for all websites. How can I implement to crawl each websites with different timing which is stored in the database? Is there any way to handle this in scrapy?
upvote count: 3
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52401105
type: UnansweredQuestion
tagged with: python
score: 3
downvote count: 0

http://stackoverflow.com/comment/91730286
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52392227
has text: We can't help if we don't have sufficient context to recreate and/or see the error being thrown. A Stack Trace is helpful when debugging built-in tools, since this is not a code issue, but more a python environment and os issue
score: 2

http://stackoverflow.com/a/52359007
type: Answer
has comment: http://stackoverflow.com/comment/91662471
has body: Why go through all that trouble of appending and popping so much, thats not necessary def BooHoo(n): for index, item in enumerate(list(range(1, (n+1))): if not item % 5 and not item % 3: lista[index] = "BooHoo" elif not item % 3: lista[index] = "Boo" elif not item % 5: lista[index] = "Hoo" else: pass return lista print(BooHoo(25)) Output (xenial)vash@localhost:~/python/stack_overflow$ python3.7 boohoo.py [1, 2, 'Boo', 4, 'Hoo', 'Boo', 7, 8, 'Boo', 'Hoo', 11, 'Boo', 13, 14, 'BooHoo', 16, 17, 'Boo', 19, 'Hoo', 'Boo', 22, 23, 'Boo', 'Hoo']
has comment: http://stackoverflow.com/comment/91662583
has comment: http://stackoverflow.com/comment/91662627
has comment: http://stackoverflow.com/comment/91662574
has comment: http://stackoverflow.com/comment/91662643
has comment: http://stackoverflow.com/comment/91662572
answers question: http://stackoverflow.com/q/52358844
score: 0
has comment: http://stackoverflow.com/comment/91662599
has comment: http://stackoverflow.com/comment/91662616

http://stackoverflow.com/q/52359261
upvote count: 0
favorite count: 0
duplicate of: http://stackoverflow.com/q/45621722
has answer: http://stackoverflow.com/a/52359500
has comment: http://stackoverflow.com/comment/91662955
has answer: http://stackoverflow.com/a/52359469
has comment: http://stackoverflow.com/comment/91663007
has body: I am trying to run 2 python programs with mapreduce and keep getting an error whenever I run them. Below is the code for the 2 files. It keeps telling me that there expected an indented block error appears at the main(sys.argv) command in both programs. Any guidance would be apprecaited. Mapper.py #!/usr/bin/env python #Be sure the indentation is identical and also be sure the line above this is on the first line import sys import re def main(argv): line = sys.stdin.readline() pattern = re.compile("[a-zA-Z0-9]+") while line: for word in pattern.findall(line): print(word+"\t"+"1") line = sys.stdin.readline() #Note there are two underscores around name and main if __name__ == "__main__": main(sys.argv) reducer.py #!/usr/bin/env python #Be sure the indentation is correct and also be sure the line above this is on the first line import sys def main(argv): current_word = None current_count = 0 word = None for line in sys.stdin: line = line.strip() word, count = line.split('\t', 1) count = int(count) if current_word == word: current_count += count else: if current_word: print('%s\t%s' % (current_word, current_count)) current_count = count current_word = word if current_word == word: print('%s\t%s' % (current_word, current_count)) #Note there are two underscores around name and main if __name__ == "__main__": main(sys.argv) Error Message: [maria_dev@sandbox-hdp ~]$ python reducer.py File "reducer.py", line 25 main(sys.argv) ^ IndentationError: expected an indented block Example of Mapper file
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91663049
tagged with: python
downvote count: 1
has title: Python:Expected an indented block
has comment: http://stackoverflow.com/comment/91662991
score: -1
has comment: http://stackoverflow.com/comment/91663162
tagged with: mapreduce
has comment: http://stackoverflow.com/comment/91662950
has comment: http://stackoverflow.com/comment/91662930
type: Question
tagged with: hadoop
has comment: http://stackoverflow.com/comment/91663040
answer count: 2
has comment: http://stackoverflow.com/comment/91662973
linked to: http://stackoverflow.com/q/45621722

http://stackoverflow.com/comment/91553321
has text: @user3483203 you should make that an answer, though I think it will currently break if there's multiple years represented in the dates
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52302605

http://stackoverflow.com/a/52378314
has body: So, instead of the HTML, you want to get the text inside of the tags. BeautifulSoup has a text attribute. So, in this case to get what you want you can just add the line: print(region.text.split('\n')[:3])
score: 0
answers question: http://stackoverflow.com/q/52378122
type: Answer

http://stackoverflow.com/a/52419712
downvote count: 1
has comment: http://stackoverflow.com/comment/91783399
has comment: http://stackoverflow.com/comment/91782888
score: 0
has comment: http://stackoverflow.com/comment/91783952
answers question: http://stackoverflow.com/q/52419395
type: Answer
has comment: http://stackoverflow.com/comment/91783250
upvote count: 1
has comment: http://stackoverflow.com/comment/91785173
has body: I use this generic template code for re-tries at work to handle all cases and avoid code failures. N_try = 10 for n_try in range(0,N_try): success = None try: #code execution output = None output = CodeExecution(input) except ex_name_1 as (errno, strerror): success = False print("EXCEPTION CAUGHT: Try {} of {}:".format(n_try, N_try)) print("exc_n={}, exc_str={}".format(errno, strerror)) except ex_name_2 as (errno, strerror): success = False print("EXCEPTION CAUGHT: Try {} of {}:".format(n_try, N_try)) print("exc_n={}, exc_str={}".format(errno, strerror)) except: print("UNKNOWN EXCEPTION CAUGHT: Try {} of {}".format(n_try, N_try)) success = False if success is True: if CheckOutpup(output) is True: success = True break else: success = False print("CHECK OUTPUT: Try {n_try} of {N_try} FAILED".format{n_try, N_try}) else: print("EXECUTION: Try {n_try} of {N_try} FAILED".format{n_try, N_try}) success = False if success is False: print("Failed execution after {N_try} tries".format{N_try})

http://stackoverflow.com/comment/91680567
type: Comment
comment on: http://stackoverflow.com/a/52318898
has text: @django-unchained not sure if I understand the question. Maybe make it a new post so you can explain it clearly and other people can also suggest answers?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91515185
has text: `python -m pip install module_name`?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52283464
type: Comment

http://stackoverflow.com/comment/91657930
type: AnswerComment
type: Comment
score: 1
has text: @Monduiz: the column name was never "answer", that was just the data label given to a column level because I was too lazy to add "answer" to the pivot. :-) Unfortunately I think you'd have to resort the question order manually, this has been an annoyance for a while.
comment on: http://stackoverflow.com/a/52356596

http://stackoverflow.com/a/52295202
has body: It's simple, you are printing the entire list, wich output is the [] and the commas. You just have to print each element separately Like: for elem in remove(duplicate): print(elem, end=" ")
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52295134

http://stackoverflow.com/comment/91633722
has text: There are no duplicate keys in JSON objects and Python dicts by definition. Strictly seen your input is no JSON.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52343860

http://stackoverflow.com/a/52308850
upvote count: 21
score: 19
has body: See the documentation: sns.lineplot(x="Year", y="signal", hue="label", data=data_preproc) You probably need to re-organize your dataframe in a suitable way so that there is one column for the x data, one for the y data, and one which holds the label for the data point. You can also just use matplotlib.pyplot. If you import seaborn, much of the improved design is also used for "regular" matplotlib plots. Seaborn is really "just" a collection of methods which conveniently feed data and plot parameters to matplotlib.
answers question: http://stackoverflow.com/q/52308749
type: Answer
downvote count: 2

http://stackoverflow.com/q/52407131
tagged with: python
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/52407269
accepted answer: http://stackoverflow.com/a/52407269
possible better answer: http://stackoverflow.com/a/52407473
type: AnsweredQuestion
has body: I am trying to implement for the first time the authentication for Django. I am creating the login part following the official guide of Django 2. However I am having this problem: Exception Type: MultiValueDictKeyError Exception Value: 'username' I created an app called "accounts". Inside of it, I have the following: In accounts/views.py: from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout def login(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: return redirect('home') else: return render(request, "accounts/login.html") In templates/accounts.html: {% extends 'mysite/base.html' %} {% block content %} Login {% csrf_token %} Username: Password: {% endblock %} In urls.py (of my app "accounts" not of the project): from django.urls import path, include from . import views urlpatterns = [ path("signup/", views.signup, name="signup"), path("login/", views.login, name="login"), path("logout/", views.logout, name="logout"), ]
score: 1
tagged with: django-authentication
type: Question
has answer: http://stackoverflow.com/a/52407473
answer count: 2
upvote count: 1
favorite count: 0
has title: Django 2 - Login Authentication PROBLEM: MultiValueDictKeyError for username

http://stackoverflow.com/comment/91623148
has text: Don't be sorry, I'm fighting your corner :) Doesn't mean that I'm right, only that people might be making a snap voting decision because you're asking something that, on the surface, is subjective. I'm not sure it is, though, overall.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52337899
score: 1

http://stackoverflow.com/comment/91498688
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52275535
type: Comment
has text: Sorry, I forgot to tell, I tried return('',204) method also but it returns blank page. Nothing is shown in the webpage.(Haven't tried IFrame method yet). Will look into DropzoneJS, thanks for the suggestion.

http://stackoverflow.com/comment/91602999
has text: You can't mock out `date`, but you can certainly mock `datetime.now()` to return a predictable value. But otherwise yes, abstracting out into a method is the best way.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52328011
type: QuestionComment

http://stackoverflow.com/q/52394843
upvote count: 2
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/63315347
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52394871
score: 2
has body: I'm developing a simple blog with Python and Django. On my home page, I display the 3 latest posts and then all the posts. At this point my blog is working. But I added a link "Show more" or "Show article" to display the post alone in a new page but I get the following error when I load the page: NoReverseMatch at / Reverse for 'post_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)/$'] PS: I'm following this tutorial in french (this one is in English but it is a bit different in english here. And please note that I'm juste starting Python and Django :) So here is my code: post_list.html (template) {% extends 'blog/base.html' %} {% block latestsnews %} {% for latest in latests %} {{ latest.title }} {{ latest.category }} {{ latest.published_date }} Show more {% endfor %} {% endblock %} {% block posts %} {% for post in posts %} {{ post.title }} {{ post.category }}, {{ post.published_date }} Author: {{ post.author }} Show article {% endfor %} {% endblock %} Views from django.shortcuts import render from django.utils import timezone from .models import Category, Post from django.shortcuts import render, get_object_or_404 def category_list(request): categories = Category.objects.all() return render (request, 'blog/post_list.html', {'categories': categories}) def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') latests = Post.objects.filter(published_date__lte=timezone.now()).reverse()[:3] return render(request, 'blog/post_list.html', {'posts': posts, 'latests': latests}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) Urls from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'), ] Code that I ad…
tagged with: post
type: Question
answer count: 2
downvote count: 0
tagged with: python-3.4
has answer: http://stackoverflow.com/a/52394871
favorite count: 0
has answer: http://stackoverflow.com/a/63315347
tagged with: python-3.x
has title: NoReverseMatch at / Reverse for 'post_detail' not found

http://stackoverflow.com/comment/91739082
type: Comment
has text: Just have another quick question if that's alright. What is the r" used for at the beginning of the regex pattern? Cheers
type: AnswerComment
comment on: http://stackoverflow.com/a/52397128
score: 0

http://stackoverflow.com/q/52296825
has comment: http://stackoverflow.com/comment/91543299
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91542652
upvote count: 1
type: Question
has title: Bad format csv read in python
has comment: http://stackoverflow.com/comment/91542470
has comment: http://stackoverflow.com/comment/91542600
has answer: http://stackoverflow.com/a/52298744
answer count: 1
downvote count: 0
score: 1
has body: I have a csv file received in a bad format (do not have control on the app that generates this CSV) the headers of CSV and the first line are like the following: "Start Time" "End Time" "Service" "255/06:06:54","255/06:54:42","S2 AVAIL" This is the code i use to read the csv: import csv import os import sys rootPath = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..')) inputFile = open(rootPath + '\\input\\' + sys.argv[1], 'rt') sys.path.append(rootPath + '\\common') for row in csv.reader(inputFile, dialect='excel'): if row: print(row) This is the output I receive: ['ï»¿"Start Time"'] ['End Time'] ['Service'] ['255/06:06:54', '255/06:54:42', 'S2 AVAIL'] The first problem is that strange character (may an encoding option missing?) also the header is wrong and cannot use DictReader on that format, which for the edit I have to do with the CSV are useful. I could re-write a new CSV with the header correctly formatted, that is not a problem, but I do not know how to skip the first 3 lines of the CSV!? Or can I read it with the format CSV is coming? This is the output I wish to obtain with csv.reader: ['Start Time', 'End Time', 'Service'] ['255/06:06:54', '255/06:54:42', 'S2 AVAIL'] or with csv.DictReader: OrderedDict([('Start Time', '255/06:06:54'), ('End Time', '255/06:54:42'), ('Service', 'S2 AVAIL')])
favorite count: 0
tagged with: parsing
accepted answer: http://stackoverflow.com/a/52298744
tagged with: python-3.x
linked to: http://stackoverflow.com/q/40310042
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/17912307
has comment: http://stackoverflow.com/comment/91541898
tagged with: python
has comment: http://stackoverflow.com/comment/91541936

http://stackoverflow.com/comment/91784909
comment on: http://stackoverflow.com/q/52420831
type: QuestionComment
type: Comment
has text: While the original error is TypeError: when() missing 1 required positional argument: 'value'
score: 0

http://stackoverflow.com/q/52281531
answer count: 0
downvote count: 0
score: 1
type: Question
has body: Im programming a Jump&amp;Run in TigerJython (Python). I implemented the formulas so the actor jumps up(when pressing up-button) and then the actor should go down automatically thanks to the gravitation. The actor should only move on the y-axis (because the platforms are moving) so the value for the x-axis is 1. I really tried many things but this Jumpman doesn't want to move. http://www.tigerjython.ch/index.php?inhalt_links=navigation.inc.php&amp;inhalt_mitte=gamegrid/spriteanimation.inc.php # Jump &amp; Run from gturtle import * from gamegrid import * import math from random import randint from time import sleep # ----------classJumpman----------- class Jumpman(Actor): def __init__(self): Actor.__init__(self, "jumpman.gif") self.speed = speed self.dt = 0.005 * getSimulationPeriod() def reset(self): self.px = self.getX() self.py = self.getY() self.vx = 1 self.vy = self.speed * math.sin(math.radians(self.getDirection())) def act(self): self.vy = self.vy + g * self.dt self.px = 1 self.py = self.py + self.vy * self.dt self.setLocation(Location(int(self.px), int(self.py))) self.setDirection(math.degrees(math.atan2(self.vy, self.vx))) def collide(self, actor1, actor2): self.setY(465) return 0 # ----------classPlaforms---------- class Platform(Actor): def __init__(self, path): Actor.__init__(self, path) def act(self): self.move() def generatePlatforms(): #var = randint(1,4) #var_c = var platform = Platform("platforms/" + str(randint(1,4)) + ".jpg") jumpman.addCollisionActor(platform) addActor(platform, Location(1600, 500), 180) # ---------------------------------- def onKeyRepeated(keyCode): if keyCode == 38: jumpman.setDirection(jumpman.getDirection()+5) g = 9.81 # GameGrid makeGameGrid(1280, 720, 1, None, "retro.jpg", False)#, keyRepeated = onKeyRepeated) jumpman = Jumpman() addActor(jumpman, Location(400, 480), 90) setSimulationPeriod(30) show() doRun() while True: generatePlatforms() sleep(2)
tagged with: jython
tagged with: jython-2.7
upvote count: 1
has title: how to bring the actor moving on the y-axis?
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: jython-2.5

http://stackoverflow.com/comment/91490325
comment on: http://stackoverflow.com/a/52271411
type: Comment
score: 0
type: AnswerComment
has text: @Shiv_90 Thank you, happy that it's good, , and easy (using `transform`)

http://stackoverflow.com/comment/91799665
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52428025
has text: I edited the title, I cannot use pd.concat since it takes too much memory
type: Comment

http://stackoverflow.com/q/52390450
possible better answer: http://stackoverflow.com/a/52390649
has answer: http://stackoverflow.com/a/52390649
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91726334
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52390689
has answer: http://stackoverflow.com/a/52390642
type: Question
tagged with: python
has body: I have the following C# public classes: public class ClassA { public byte var1; public TypeX var2; } public class TypeX { public UInt16 num1; public UInt32 num2; } (Names are simplified for this example and are not real) What would this look like in Python? Specifically, how would var2 be created as an instance of TypeX? So far I have the come up with the following Python classes: class ClassA(): def __init__(self, var1, var2 = TypeX): self.var1 = var1 self.var2 = var2 class TypeX(): def __init__(self, num1, num2): self.num1 = num1 self.num2 = num2 However, I am nearly 100% sure this is not correct. Should ClassA inherit TypeX? Any guidance or explanations would be appreciated!
score: 0
accepted answer: http://stackoverflow.com/a/52390689
answer count: 3
has title: Mimic C# classes in Python
tagged with: c#

python-unittest
tags question: http://stackoverflow.com/q/52300270
tags question: http://stackoverflow.com/q/52324568
tags question: http://stackoverflow.com/q/52285345
type: Tag
tags question: http://stackoverflow.com/q/52389503
tags question: http://stackoverflow.com/q/52342533
tags question: http://stackoverflow.com/q/52317352
tags question: http://stackoverflow.com/q/52328011
tags question: http://stackoverflow.com/q/52331873
tag name: python-unittest

http://stackoverflow.com/comment/91519942
comment on: http://stackoverflow.com/q/52285724
type: QuestionComment
type: Comment
has text: `matmul` (the @ operator) does the `dot` on the last 2 dimensions. So if your `Rp` was (701,4,4) shape, you could probably do something like `Q @ Rp @ QH`. I'll have test for details.
score: 0

http://stackoverflow.com/comment/91505113
has text: Is this python2 or python3?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52277705

http://stackoverflow.com/q/52428898
type: Question
tagged with: python
answer count: 1
has body: This is my first question, please bear with me. I am working with an API that authenticates using an access token that expires in 15 minutes, there is no refresh token to use in-lieu of a re-login. So far I have been able to get the access token and insert it into the requests.get call but I cannot seem to get it to renew and am at a loss as to how. All of the work done with this API, and in general, is with Python so I am hoping to keep it in Python throughout and in the same file. I get a 401 message code once the 15 minutes are up, and code 200 if successful. So far my only ideas are to put it on a timer for renewal but I cannot make heads or tails of stackoverflow posts or the documentation on doing that, have the login running in a separate script and then this script calls the other one for the current header variable (but that still would require a timer), or have it call to redo the login function once it hits a response.status_code != 200. Example script for getting the access token import requests, os, json, time, csv def login (url, payload): #this will log into API and get an access token auth = requests.post(url, data=payload).json() sessionToken = auth["token"] sessionTimer = auth["validFor"] headers = {'Access-Token': sessionToken} return headers #calling the function to generate the token if __name__ == '__main__': url = "url inserted here" u = input("Enter your username: ") p = input("Enter your password: ") t = input("Enter your tenancy name: ") payload = {'username': u, 'password': p, 'tenant': t} print("Logging in") headers = login(url, payload) #the actual work as pulled from a csv file valuables = input("CSV file with filepath: ") file = open(valuables, 'r', encoding='utf-8') csvin = csv.reader(file) for row in csvin: try: uuidUrl = row[0] output_file = row[1] response = requests.get(uuidUrl, headers=headers) print(response.status_code) with open(output_file, 'wb') as fd: for chunk in response.iter_content(chunk_size=128): fd.write(chunk) fd.cl…
accepted answer: http://stackoverflow.com/a/52503971
has title: renewing an access token in python
upvote count: 1
tagged with: python-requests
has comment: http://stackoverflow.com/comment/91801510
downvote count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91835019
score: 1
has answer: http://stackoverflow.com/a/52503971
favorite count: 0
tagged with: python-3.x
tagged with: access-token

http://stackoverflow.com/a/52288476
has comment: http://stackoverflow.com/comment/91525350
has comment: http://stackoverflow.com/comment/91525536
upvote count: 1
answers question: http://stackoverflow.com/q/52288325
type: Answer
downvote count: 0
score: 1
has body: Python runs modules when it imports them, that is how python is supposed to work. If you have modules that are supposed to be imported, they should not have instructions outside of functions. (Unless of course you have code that is supposed to be executed upon import for which there are legitimate use cases) The Pythonic way of writing a module that is supposed to be imported, but also to do stuff if it is executed on its own, is the if main approach: You put the code that is supposed to be excuted when the module is executed in a function called main: def main(): #stuff to de when executed directly And at the end you put: if __name__ == "__main__": main() This will execute the main function only if the module/script is executed directly (for example via calling python script.py or double clicking it) , not if it is imported. After Question Edit Your edit is an example for what I was explaining, your pic.py: def get_imagepath(image): ... ... return imagepath rgb_image = load_image(image_path, grayscale=True) #this gets executed upon import The rgp_image =... part gets executed upon import and from the code you posted image_path is not defined at this point in any way, which is why it is failing.

http://stackoverflow.com/comment/115809658
has text: [I can't install pyaudio on Windows? How to solve “error: Microsoft Visual C++ 14.0 is required.”?](https://stackoverflow.com/a/57731053/5033247)
comment on: http://stackoverflow.com/a/55687782
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52302062
has answer: http://stackoverflow.com/a/52302286
type: Question
type: AnsweredQuestion
has title: Why do I get invalid syntax for else
tagged with: if-statement
has body: name=input ("please enter your name") .upper() names=["MARTIN","JAMES","LOUIS","BABYSHARK"] if name==list:names print ("You are allowed to play my game") else prin ("ACCES DENIED!"))
has answer: http://stackoverflow.com/a/52302350
has comment: http://stackoverflow.com/comment/91552270
answer count: 3
has comment: http://stackoverflow.com/comment/91552475
upvote count: 0
accepted answer: http://stackoverflow.com/a/52302286
favorite count: 0
has comment: http://stackoverflow.com/comment/91552428
has answer: http://stackoverflow.com/a/52302316
score: -3
tagged with: python
possible better answer: http://stackoverflow.com/a/52302316
has comment: http://stackoverflow.com/comment/91552677
downvote count: 3
has comment: http://stackoverflow.com/comment/91552184
has comment: http://stackoverflow.com/comment/91552127

http://stackoverflow.com/comment/91669773
type: Comment
comment on: http://stackoverflow.com/a/52362782
has text: I will try but can you modify code in my below answer as I do not want to use 2 modules of sql in my code. I am using (mysql connector )
type: AnswerComment
score: 0

http://stackoverflow.com/q/52302465
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52302657
accepted answer: http://stackoverflow.com/a/52302657
possible better answer: http://stackoverflow.com/a/52303970
answer count: 2
tagged with: pandas-groupby
has title: Grouping multiple rows in a new data frame
tagged with: pandas
upvote count: 1
favorite count: 0
tagged with: python
has body: I am a python newbie working on version 2.7. Below is a sample of the data frame that I am working with. There are additional columns that are not relevant to the problem so they are not included in the below. df = pd.DataFrame( { "Name" : ["BROD", "BROD", "BROD", "BROD", "SSBD" , "SSBD","SSBD","SSBD"] , "Digit" : ["F", "F", "T", "T", "F", "F", "T", "T"], "ID": ["A","A","A","A","B","B","B","B"], "Date": ["2/3/2010","2/3/2010","2/3/2010","2/3/2010","3/4/2007","3/4/2007","3/4/2007","3/4/2007"], "Base" : ["CAD","CAD","CAD","CAD","CAD","CAD","CAD","CAD"], "Term" : ["USD","USD","JPY","JPY","EUR","EUR","JPY","JPY"], "Amt": [100.00,100.00,9082.00,9082.00,60.00,60.00,7387.80,7387.80]}) There are multiple duplicate values. Each row represents a component of a trade and the ID column groups them into one trade. I would like to create a new data frame that only includes one row for each trade. The data frame would look like this: ID Date Name Buy Sell Buy Amt Sell Amt A 2/3/2010 BROD USD JPY 100.00 9082.00 B 3/4/2007 SSBD EUR JPY 60.00 7387.80 Where for each ID, if the Digit = F then the value in the Term column is placed in the Buy column and the value in the Amt column is placed in the Buy Amt column. If the Digit = T then the value in the Term column is placed in the Sell column and the value in the Amt column is placed in the Sell Amount column. Please point me in the right direction for the most efficient way to solve this problem. Thanks.
has answer: http://stackoverflow.com/a/52303970

http://stackoverflow.com/q/52285515
tagged with: web
linked to: http://stackoverflow.com/q/20437701
type: Question
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52285684
has comment: http://stackoverflow.com/comment/91524972
score: 0
has comment: http://stackoverflow.com/comment/91531749
tagged with: pip
answer count: 1
linked to: http://stackoverflow.com/q/51319189
has comment: http://stackoverflow.com/comment/91521654
accepted answer: http://stackoverflow.com/a/52285684
has body: I am trying to install virtualenv and django and i keep getting errors.I tried using the whql file of virtualenv but still, no solution.My windows firewall is also turned off.This is the error message for virtualenv,The same thing happens when i try installing flask also. C:\Windows\system32&gt;easy_install virtualenv Searching for virtualenv Reading https://pypi.python.org/simple/virtualenv/ Download error on https://pypi.python.org/simple/virtualenv/: [WinError 10061] N o connection could be made because the target machine actively refused it -- Som e packages may not be found! Couldn't find index page for 'virtualenv' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading https://pypi.python.org/simple/ Download error on https://pypi.python.org/simple/: [WinError 10061] No connectio n could be made because the target machine actively refused it -- Some packages may not be found! No local packages or working download links found for virtualenv error: Could not find suitable distribution for Requirement.parse('virtualenv') C:\Windows\system32&gt;pip install virtualenv Collecting virtualenv Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connec tion broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('&lt;pip. _vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0 x0298DD70&gt;: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))': /simple/virt ualenv/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connec tion broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('&lt;pip. _vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0 x0298DED0&gt;: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))': /simple/virt ualenv/ Retrying (Retry(total=2, connect…
linked to: http://stackoverflow.com/q/47459747
has title: Pip install and Easy install Django and VirtualEnv not working
type: AnsweredQuestion

amazon-elastic-beanstalk
tag name: amazon-elastic-beanstalk
type: Tag
tags question: http://stackoverflow.com/q/52398563
tags question: http://stackoverflow.com/q/52360482
tags question: http://stackoverflow.com/q/52427511
tags question: http://stackoverflow.com/q/52355620

http://stackoverflow.com/comment/91638776
has text: Ok - I edit My question and Write it Another way
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52346584
score: 0

http://stackoverflow.com/a/52360745
has comment: http://stackoverflow.com/comment/129998649
downvote count: 0
score: 102
has body: An r-string is a raw string. It ignores escape characters. For example, "\n" is a string containing a newline character, and r"\n" is a string containing a backslash and the letter n. If you wanted to compare it to an f-string, you could think of f-strings as being "batteries-included." They have tons of flexibility in the ability to escape characters and execute nearly arbitrary expressions. The r-string on the other hand is stripped down and minimalist, containing precisely the characters between its quotation marks. As far as actually using the things, typically you would use an r-string if you're passing the string into something else that uses a bunch of weird characters or does its own escaping so that you don't have to think too hard about how many backslashes you really need to get everything to work correctly. In your example, they at least needed r-strings to get the \a bit working correctly without double escapes. Note that '$\\alpha > \\beta$' is identical to r'$\alpha > \beta$'. Since you're using f-strings, I'll assume you have at least Python 3.6. Not all of these options are supported for older versions but any of the following prefixes are valid in Python 3.6+ in any combination of caps and lowers: r, u, f, rf, fr, b, rb, br The b-strings are binary literals. In Python 2 they do nothing and only exist so that the source code is compatible with Python 3. In Python 3, they allow you to create a bytes object. Strings can be thought of as a view of the underlying bytes, often restricted as to which combinations are allowed. The distinction in types helps to prevent errors from blindly applying text techniques to raw data. In Python 3, note that 'A'==b'A' is False. These are not the same thing. The u-strings are unicode literals. Strings are unicode by default in Python 3, but the u prefix is allowed for backward compatibility with Python 2. In Python 2, strings are ASCII by default, and the u prefix allows you to include non-ASCII characters in your str…
type: Answer
answers question: http://stackoverflow.com/q/52360537
has comment: http://stackoverflow.com/comment/91666202
has comment: http://stackoverflow.com/comment/91666699
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91666978
accepted answer of: http://stackoverflow.com/q/52360537
upvote count: 102

http://stackoverflow.com/comment/91493005
has text: what do u mean?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52272903

http://stackoverflow.com/a/52408379
upvote count: 30
has body: It turned out that I just had to restart my computer after I installed ms-python.python and tht13.python and formulahendry.code-runner extensions on the VS Code and added python's Scripts folder in PATH. Now both py and python commands work from anywhere like cmd or Run Code in the right click menu.
has comment: http://stackoverflow.com/comment/135367691
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/98118611
answers question: http://stackoverflow.com/q/52332554
type: Answer
score: 29
downvote count: 1
accepted answer of: http://stackoverflow.com/q/52332554
has comment: http://stackoverflow.com/comment/99031298

http://stackoverflow.com/comment/91729396
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52389675
has text: This is perfect - exactly what is need. If you make it an answer, I will accept it :)
score: 0

http://stackoverflow.com/q/52423654
tagged with: dataframe
type: Question
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52426129
has title: Split dataframe into multiple dataframes based on both groupby and binning
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
favorite count: 0
type: UnansweredQuestion
upvote count: 1
has body: I have a dataframe in pandas containing information that I would like sort into groups based on their id ('square'). I want to obtain the mean brightness for each group, and based on this mean brightness I want to bin the dataframe into 4 categories, and get 4 output dataframes. Example dataframe: squares = pd.DataFrame({'square': {0: 1.0, 1: 1.0, 2: 2.0, 3: 2.0, 4: 5.0, 5: 6.0, 6: 7.0, 7: 8.0}, 'time': {0: 1.0, 1: 2.0, 2: 1.0, 3: 2.0, 4: 3.0, 5: 3.0, 6: 4.0, 7: 5.0 }, 'x': {0: 243, 1: 293, 2: 189, 3: 189, 4: 176, 5: 374, 6: 111, 7: 239}, 'y': {0: 233, 1: 436, 2: 230, 3: 233, 4: 203, 5: 394, 6: 171, 7: 284}, 'brightness': {0: 1000, 1: 1200, 2: 4000, 3: 5000, 4: 2000, 5: 8000, 6: 1300, 7: 4300 }}) squares = squares.set_index('time') squares brightness square x y time 1.0 1000 1.0 243 233 2.0 1200 1.0 293 436 1.0 4000 2.0 189 230 2.0 5000 2.0 189 233 3.0 2000 5.0 176 203 3.0 6000 6.0 374 394 4.0 1300 7.0 111 171 5.0 4300 8.0 239 284 Desired end result: squares_1 brightness square x y time 1.0 1000 1.0 243 233 2.0 1200 1.0 293 436 3.0 2000 5.0 176 203 4.0 1300 7.0 111 171 squares_2 NaN squares_3 brightness square x y time 1.0 4000 2.0 189 230 2.0 5000 2.0 189 233 5.0 4300 8.0 239 284 squares_4 brightness square x y time 3.0 6000 6.0 374 394 I've started out with the following: import pandas as pd import numpy as np from matplotlib import pyplot as plt avg = squares.groupby('square')['brightness'].mean() n, bins, patches = plt.hist(avg, bins = 4) inds = np.digitize(avg, bins) I'm not quite sure how to continue though. Any help appreciated!
tagged with: binning
score: 1

http://stackoverflow.com/comment/91594177
type: AnswerComment
has text: I've updated my answer so it strips commas from every line in a string. Please give it a try.
comment on: http://stackoverflow.com/a/52323416
type: Comment
score: 0

http://stackoverflow.com/comment/91681707
type: Comment
comment on: http://stackoverflow.com/a/52367337
has text: @IamNik what would your desired output be from the multiple columns?
type: AnswerComment
score: 0

http://stackoverflow.com/a/52557840
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52413158
type: Answer
has body: You can add any additional data into log using logging.Formatter. Just an example: log.py import logging from flask import request class __RequestFormatter(logging.Formatter): def format(self, record): # you can set here everything what you need # I just added url and id from GET parameter record.id = request.args.get('id') record.url = request.url return super().format(record) # format of our log record. # print url and id of record which was set in format() __stream_handler = logging.StreamHandler() __stream_handler.setFormatter(__RequestFormatter( '[%(asctime)s %(levelname)s] requested: %(url)s, id: %(id)s in %(module)s: %(message)s' )) logger = logging.getLogger('my_loger') logger.setLevel(logging.INFO) logger.addHandler(__stream_handler) app.py from flask import Flask from log import logger from other_file import other_module app = Flask(__name__) @app.route('/test') def test(): logger.info('/test was called') other_module() return 'hi' other_file.py from log import logger def other_module(): logger.info("My second message") Now let's call /test?id=example_id, /test?id=example_id2 and check logs: [2018-09-28 17:40:48,669 INFO] requested: http://127.0.0.1:5000/test?id=example_id, id: example_id in app: /test was called [2018-09-28 17:40:48,670 INFO] requested: http://127.0.0.1:5000/test?id=example_id, id: example_id in other_file: My second message [2018-09-28 17:40:51,475 INFO] requested: http://127.0.0.1:5000/test?id=example_id2, id: example_id2 in app: /test was called [2018-09-28 17:40:51,476 INFO] requested: http://127.0.0.1:5000/test?id=example_id2, id: example_id2 in other_file: My second message As you can see all messages include id of request. So you can use Formatter to customize everything what you need. Also you can try to use flask-log-request-id. Hope this helps.
upvote count: 1

http://stackoverflow.com/comment/91689935
comment on: http://stackoverflow.com/a/52371589
type: AnswerComment
score: 0
type: Comment
has text: Using projection might help you... No other option

keyboard
tags question: http://stackoverflow.com/q/52403967
tag name: keyboard
tags question: http://stackoverflow.com/q/52390106
type: Tag
tags question: http://stackoverflow.com/q/52310791

http://stackoverflow.com/a/55250017
answers question: http://stackoverflow.com/q/52291739
type: Answer
has body: You can use the following code to get a string from frozenset type columns and then cast the string to unicode. rules["antecedents"] = rules["antecedents"].apply(lambda x: list(x)[0]).astype("unicode") rules["consequents"] = rules["consequents"].apply(lambda x: list(x)[0]).astype("unicode")
upvote count: 7
score: 7
accepted answer of: http://stackoverflow.com/q/52291739
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/100717082

http://stackoverflow.com/comment/91636890
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52345203
type: Comment
has text: I note that this is implied in most polynomials such as a straight line "y = a * x^0 + b * x^1" or a quadratic "y = a * x^0 + b * x^1 + c * x^2" because x^0 = 1.

http://stackoverflow.com/q/52389892
has answer: http://stackoverflow.com/a/52391185
tagged with: dataframe
type: Question
has body: I have a pandas dataframe where 5 matching strings, lets call them "xyz" occurs x lines after a initial matching string, lets call them "intial string1" and "intial string2" index col0 col3 500 data " initial string1" .. .. .. 600 data "xyz" ... ... ... 1343 data "intial string1" .. .. .. 1443 data "xyz" ... ... ... 2432 data "intial string2" .. .. .. 2453 data "xyz" .. .. .. 2467 data "intial string2" .. .. .. 2487 data "xyz" I want to be able to iterate through the dataframe starting at these indices, to find the first occurrence of "xyz" and write the rows where these "xyz" occurs to a new dataframe, and then to excel, based on which initial string it has encountered. IE store all xyz corresponding to intial string1 in a dataframe, and store all xyz corresponding to intial string2 in a another dataframe. I am not sure how to use the combinations of iterrorws, and df["column"].str.match ("matching string") to carry out these iterations. Appreciate the help!
score: 0
has answer: http://stackoverflow.com/a/52390137
tagged with: pandas
has title: Finding matching string in Pandas Dataframe, starting at specific indices
answer count: 4
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52390565
has answer: http://stackoverflow.com/a/52436540

http://stackoverflow.com/q/52389087
type: AnsweredQuestion
score: -1
possible better answer: http://stackoverflow.com/a/52389297
type: Question
answer count: 2
downvote count: 1
has body: I need a regular expression in python to add {\an8} in the start of every line below the lines contains the two words 'position:50.00%' and 'line:10.00%' at the same time, in a format like this one, thanks. file_content = re.sub(r'line:10.00%[^\n]*(\n*)([\w\W .,:%])', r'\1{\\an8}\2', file_content) Like this example: 00:05:31.957 --> 00:05:34.835 position:50.00%,start align:start size:25.24% line:10.00% {\an8}Not yet.
favorite count: 0
has title: What is the way of adding a word to the line below using regular expression in python?
accepted answer: http://stackoverflow.com/a/52389219
tagged with: regex
has answer: http://stackoverflow.com/a/52389297
upvote count: 0
has answer: http://stackoverflow.com/a/52389219
tagged with: python

http://stackoverflow.com/comment/91631799
score: 1
has text: You need a comma after `box` to make it a tuple. A string is a sequence and it's being unpacked character-by-character
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52342780

http://stackoverflow.com/comment/91773735
comment on: http://stackoverflow.com/q/52414962
type: Comment
type: QuestionComment
has text: Quick question, why are you converting it to a float to test if it is an integer or float?
score: 1

http://stackoverflow.com/comment/91626334
type: QuestionComment
has text: You need to help us to help you. :-)
comment on: http://stackoverflow.com/q/52339274
score: 0
type: Comment

http://stackoverflow.com/q/52297627
type: Question
tagged with: opencv
has body: I'm trying to make a live sketcher using openCV module but the cv2.imshow function is showing error.I have attached the screenshot of the error. Kindly help.. import cv2 def sketch(img): img_gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) img_gray_blur=cv2.GaussianBlur(img_gray,(5,5),0) canny_edges=cv2.Canny(img_gray_blur,10,70) ret,mask=cv2.threshold(canny_edges,70,255,cv2.THRESH_BINARY) return mask cap=cv2.VideoCapture(0) while True: ret,frame=cap.read() cv2.imshow('live sketcher',sketch(frame)) if cv2.waitKey(): break cap.release() cv2.destroyAllWindows()
has comment: http://stackoverflow.com/comment/91555301
has comment: http://stackoverflow.com/comment/91590667
has comment: http://stackoverflow.com/comment/91592490
answer count: 1
has comment: http://stackoverflow.com/comment/91543419
has comment: http://stackoverflow.com/comment/91562891
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: opencv3.0
score: 1
has comment: http://stackoverflow.com/comment/91563083
has answer: http://stackoverflow.com/a/57614989
has title: making a live sketcher via webcam using openCV
downvote count: 1

http://stackoverflow.com/comment/134623190
score: 0
type: Comment
has text: What is this "universe" thing? Can it be trusted (or to what degree)?
comment on: http://stackoverflow.com/a/52394612
type: AnswerComment

http://stackoverflow.com/comment/91650728
comment on: http://stackoverflow.com/q/52352847
score: 1
has text: Not that the builtin `int` function takes a base argument (up to 36)... so you could do `int('ffeb109e', 16)` if 16 was your base and get your number that way. And there's builtin formatting to make a number binary, octal or hex representations so that'd cover outputs of bases 2, 8 and 16... (anything else you'd have to do yourself but that's not too tricky)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52407996
type: Answer
has comment: http://stackoverflow.com/comment/91826845
has comment: http://stackoverflow.com/comment/91764294
has comment: http://stackoverflow.com/comment/91764001
downvote count: 0
has comment: http://stackoverflow.com/comment/91828214
has comment: http://stackoverflow.com/comment/91763928
has comment: http://stackoverflow.com/comment/91764243
has comment: http://stackoverflow.com/comment/91826968
has comment: http://stackoverflow.com/comment/91764178
score: 1
has comment: http://stackoverflow.com/comment/91764626
accepted answer of: http://stackoverflow.com/q/52407377
has comment: http://stackoverflow.com/comment/91763645
has comment: http://stackoverflow.com/comment/91764237
has comment: http://stackoverflow.com/comment/91763694
answers question: http://stackoverflow.com/q/52407377
has body: According to your comment: [The] data i have is like t-48, t-47, t-46, ..... , t-1 as the past data and t+1, t+2, ......, t+12 as the values that I want to forecast you may not need to use a TimeDistributed layer at all: first, just remove the resturn_sequences=True argument of the LSTM layer. After doing it, the LSTM layer would encode the input timeseries of the past in a vector of shape (50,). Now you can feed it directly to a Dense layer with 12 units: # make sure the labels have are in shape (num_samples, 12) y = np.reshape(y, (-1, 12)) power_in = Input(shape=(X.shape[1:],)) power_lstm = LSTM(50, recurrent_dropout=0.4128, dropout=0.412563, kernel_initializer=power_lstm_init)(power_in) main_out = Dense(12, kernel_initializer=power_lstm_init)(power_lstm) Alternatively, if you would like to use a TimeDistributed layer and considering that the output is a sequence itself, we can explicitly enforce this temporal dependency in our model by using another LSTM layer before the Dense layer (with the addition of a RepeatVector layer after the first LSTM layer to make its output a timseries of length 12, i.e. same as the output timeseries length): # make sure the labels have are in shape (num_samples, 12, 1) y = np.reshape(y, (-1, 12, 1)) power_in = Input(shape=(48,1)) power_lstm = LSTM(50, recurrent_dropout=0.4128, dropout=0.412563, kernel_initializer=power_lstm_init)(power_in) rep = RepeatVector(12)(power_lstm) out_lstm = LSTM(32, return_sequences=True)(rep) main_out = TimeDistributed(Dense(1))(out_lstm) model = Model(power_in, main_out) model.summary() Model summary: _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_3 (InputLayer) (None, 48, 1) 0 _________________________________________________________________ lstm_3 (LSTM) (None, 50) 10400 _________________________________________________________________ repeat_vector_2 (RepeatVecto (None, 12, 50)…
has comment: http://stackoverflow.com/comment/91764596
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91764395
has comment: http://stackoverflow.com/comment/91828329
has comment: http://stackoverflow.com/comment/91764676
has comment: http://stackoverflow.com/comment/91829064
has comment: http://stackoverflow.com/comment/91764041
upvote count: 1

http://stackoverflow.com/q/52400391
tagged with: python
has answer: http://stackoverflow.com/a/60467167
tagged with: installation
has answer: http://stackoverflow.com/a/63119216
tagged with: tensorflow
type: Question
has title: Could not find a version that satisfies the requirement tensorflow (from versions:) No matching distribution found for tensorflow
has body: While installing TensorFlow for my pc the following error appeared Could not find a version that satisfies the requirement TensorFlow (from versions:) No matching distribution found for TensorFlow I have a 64-bit Widows operating system. And Python 3.7.0 64-bit. I already updated my pip from version 10.0 to 18.0 still error remains the same.
has answer: http://stackoverflow.com/a/52400482
score: 0
answer count: 3
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/a/52285916
has body: The documentation for max mentions: builtin max max(iterable, *[, key, default]) max(arg1, arg2, *args[, key]) ... If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned. In the first case you have one positional argument, in the second case you have multiple. To get what you want, which is the maximal entry in a matrix you could try max(entry for row in matrix for entry in row) This will pass one argument to the max function which is a generator that iterates over all the entries in the matrix - triggering the first case which finds the maximum of an iterable.
downvote count: 0
score: 8
upvote count: 8
answers question: http://stackoverflow.com/q/52285862
type: Answer

http://stackoverflow.com/comment/91621097
type: AnswerComment
comment on: http://stackoverflow.com/a/52327211
has text: @Vamshi I use Anaconda and Win Command Prompt. Tried the code in Jupyter Notebook and got no result with infinite running time. So probably it is Jupyter related issue where processes do not know how they are related to the main process.
type: Comment
score: 0

http://stackoverflow.com/comment/91793810
has text: This seems to solve the problem, thank you! BUT when hovering above "import ClassA" in the code PyCharm complains: "No module named ClassA" even though I can use ClassA. Why is this?
score: 1
comment on: http://stackoverflow.com/a/52425147
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91621551
score: 1
type: AnswerComment
has text: @DYZ The answer was edited about three times after my comment.
type: Comment
comment on: http://stackoverflow.com/a/52337123

object-detection
tags question: http://stackoverflow.com/q/52382499
tag name: object-detection
tags question: http://stackoverflow.com/q/52425985
tags question: http://stackoverflow.com/q/52346399
tags question: http://stackoverflow.com/q/52424348
type: Tag
tags question: http://stackoverflow.com/q/52361885
tags question: http://stackoverflow.com/q/52385215
tags question: http://stackoverflow.com/q/52317034

http://stackoverflow.com/q/52330853
has comment: http://stackoverflow.com/comment/91608303
favorite count: 0
has answer: http://stackoverflow.com/a/52331258
accepted answer: http://stackoverflow.com/a/52331258
upvote count: 1
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91608396
tagged with: file
linked to: http://stackoverflow.com/q/44310764
downvote count: 1
type: Question
answer count: 1
has body: I have a file with the following structure and a varying number of newlines between the entries: n Name1 MiddleName1 Surname1 multiline string1 n Name2 MiddleName2 Surname2 multi line string2 n Name3 MiddleName3 Surname3 multiline string3 How can I read this file into a dictionary which contains: {"n Name1 MiddleName1 Surname1" : "multiline\nstring1", ...} I attempted to extract the keys with a regular expression, like so: with open('file') as infile: content = infile.read() match = re.search(r'n .*', content) But I don't know where to go from there. All similar questions I was able to find have some sort of split (like '=') which can be used to seperate the keys from the objects.
has title: In Python, how do I read a file into a dictionary with multiple line entries?
score: 0

http://stackoverflow.com/comment/91530904
score: 0
comment on: http://stackoverflow.com/a/52291091
type: AnswerComment
has text: Oh, you're right. My bad! How would you take into account the caveat that not all years have 365 days?
type: Comment

http://stackoverflow.com/comment/91580739
comment on: http://stackoverflow.com/q/52316343
score: 1
has text: This code doesn't do what you want at all. It downloads it to the server, not to the client. While you're in development those are the same machine, but once you deploy to production it won't download it to the user's machine at all. Instead you need to stream the file to the user and return that stream in the response.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52306279
tagged with: pytorch
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/56146731
upvote count: 3
has answer: http://stackoverflow.com/a/53710248
has title: pytorch gradient / derivative / difference along axis like numpy.diff
type: Question
tagged with: numpy
has body: I have been struggling with this for quite some time. All I want is a torch.diff() function. However, many matrix operations do not appear to be easily compatible with tensor operations. I have tried an enormous amount of various pytorch operation combinations, yet none of them work. Due to the fact that pytorch hasn't implemented this basic feature, I started by simply trying to subtract the element i+1 from element i along a specific axis. However, you can't simply do this element-wise (due to the tensor limitations), so I tried to construct another tensor, with the elements shifted along one axis: ix_plus_one = [0]+list(range(0,prediction.size(1)-1)) ix_differential_tensor = torch.LongTensor(ix_plus_one) diff_one_tensor = prediction[:,ix_differential_tensor] But now we have a different problem - indexing doesn't really work to mimic numpy in pytorch as it advertises, so you can't index with a "list-like" Tensor like this. I also tried using the tensor scatter functions So I'm still stuck with this simple problem of trying to get a gradient on a pytoch tensor. All of my searching leads to the marvelous capabilities of pytorchs' "autograd" function - which has nothing to do with this problem.
downvote count: 0
answer count: 3
score: 3
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/70675349

http://stackoverflow.com/comment/91781916
type: Comment
has text: The thing is , when i remove the read_only on the fields in the serializers, the **comment** and **author** be availbale , but when i add them the ***comment_id*** and ***author_id*** becomes null
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52418106

arrays
tags question: http://stackoverflow.com/q/52348870
tags question: http://stackoverflow.com/q/52352063
tags question: http://stackoverflow.com/q/52427726
tags question: http://stackoverflow.com/q/52396785
type: Tag
tags question: http://stackoverflow.com/q/52335900
tags question: http://stackoverflow.com/q/52381171
tags question: http://stackoverflow.com/q/52379158
tags question: http://stackoverflow.com/q/52352511
tags question: http://stackoverflow.com/q/52280499
tags question: http://stackoverflow.com/q/52279286
tags question: http://stackoverflow.com/q/52383364
tags question: http://stackoverflow.com/q/52410540
tags question: http://stackoverflow.com/q/52345762
tags question: http://stackoverflow.com/q/52291342
tags question: http://stackoverflow.com/q/52284137
tags question: http://stackoverflow.com/q/52392644
tags question: http://stackoverflow.com/q/52409479
tags question: http://stackoverflow.com/q/52357926
tags question: http://stackoverflow.com/q/52295024
tags question: http://stackoverflow.com/q/52322833
tags question: http://stackoverflow.com/q/52390359
tags question: http://stackoverflow.com/q/52356615
tags question: http://stackoverflow.com/q/52323575
tags question: http://stackoverflow.com/q/52349423
tags question: http://stackoverflow.com/q/52378730
tags question: http://stackoverflow.com/q/52418839
tags question: http://stackoverflow.com/q/52420450
tags question: http://stackoverflow.com/q/52371062
tags question: http://stackoverflow.com/q/52397513
tags question: http://stackoverflow.com/q/52301276
tags question: http://stackoverflow.com/q/52364583
tags question: http://stackoverflow.com/q/52428601
tags question: http://stackoverflow.com/q/52404476
tags question: http://stackoverflow.com/q/52271619
tags question: http://stackoverflow.com/q/52314573
tags question: http://stackoverflow.com/q/52299533
tags question: http://stackoverflow.com/q/52392923
tags question: http://stackoverflow.com/q/52366421
tags question: http://stackoverflow.com/q/52355207
tags question: http://stackoverflow.com/q/52355110
tags question: http://stackoverflow.com/q/52305670
tags question: http://stackoverflow.com/q/52335733
tags question: http://stackoverflow.com/q/52349377
tags question: http://stackoverflow.com/q/52354777
tags question: http://stackoverflow.com/q/52359803
tag name: arrays
tags question: http://stackoverflow.com/q/52360995
tags question: http://stackoverflow.com/q/52367739
tags question: http://stackoverflow.com/q/52395579
tags question: http://stackoverflow.com/q/52329167
tags question: http://stackoverflow.com/q/52376009
tags question: http://stackoverflow.com/q/52342514
tags question: http://stackoverflow.com/q/52343946
tags question: http://stackoverflow.com/q/52333067
tags question: http://stackoverflow.com/q/52323208
tags question: http://stackoverflow.com/q/52352395
tags question: http://stackoverflow.com/q/52323524
tags question: http://stackoverflow.com/q/52280146
tags question: http://stackoverflow.com/q/52418325
tags question: http://stackoverflow.com/q/52374935
tags question: http://stackoverflow.com/q/52273115
tags question: http://stackoverflow.com/q/52313506
tags question: http://stackoverflow.com/q/52427905
tags question: http://stackoverflow.com/q/52345424
tags question: http://stackoverflow.com/q/52307822
tags question: http://stackoverflow.com/q/52349524
tags question: http://stackoverflow.com/q/52424437
tags question: http://stackoverflow.com/q/52369746
tags question: http://stackoverflow.com/q/52346241
tags question: http://stackoverflow.com/q/52359612
tags question: http://stackoverflow.com/q/52322207
tags question: http://stackoverflow.com/q/52345983
tags question: http://stackoverflow.com/q/52387673
tags question: http://stackoverflow.com/q/52352524
tags question: http://stackoverflow.com/q/52358507
tags question: http://stackoverflow.com/q/52341085
tags question: http://stackoverflow.com/q/52373844
tags question: http://stackoverflow.com/q/52303258
tags question: http://stackoverflow.com/q/52357594

http://stackoverflow.com/comment/91944580
has text: @d_kennetz, could I kindly ask you to take a look at my version of the code? I updated the question. The values differ from yours, so I'm not sure where I'm getting it wrong
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52371959

http://stackoverflow.com/q/52397646
has answer: http://stackoverflow.com/a/52420116
type: Question
has answer: http://stackoverflow.com/a/53310379
tagged with: aws-glue
has answer: http://stackoverflow.com/a/52399828
has answer: http://stackoverflow.com/a/66174884
tagged with: amazon-web-services
score: 0
has answer: http://stackoverflow.com/a/52420542
has body: Here are some bullet points in terms of how I have things setup: I have CSV files uploaded to S3 and a Glue crawler setup to create the table and schema. I have a Glue job setup that writes the data from the Glue table to our Amazon Redshift database using a JDBC connection. The Job also is in charge of mapping the columns and creating the redshift table. By re-running a job, I am getting duplicate rows in redshift (as expected). However, is there way to replace or delete rows before inserting the new data? BOOKMARK functionality is Enable but not working. How can I connect to redshift, delete all data as a part of JOB before pushing data to redshift in Python?
tagged with: amazon-redshift
answer count: 5
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/47081088
has title: AWS Glue to Redshift: duplicate data?
tagged with: amazon-s3

http://stackoverflow.com/a/52285573
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91519616
has comment: http://stackoverflow.com/comment/91621755
has comment: http://stackoverflow.com/comment/91609382
has body: async is a keyword of Python > 3.4. You have to check your python version and the library is supported your python version.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52285525

http://stackoverflow.com/q/52353962
type: Question
tagged with: testing
tagged with: automated-tests
downvote count: 0
upvote count: 11
answer count: 1
has comment: http://stackoverflow.com/comment/91652595
has title: Django initialize data test for all test classes
favorite count: 0
has comment: http://stackoverflow.com/comment/91676411
linked to: http://stackoverflow.com/q/43594519
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91667075
has comment: http://stackoverflow.com/comment/91676587
tagged with: django
tagged with: python
has body: I need to add test to my django project, I need to create data test before execute tests. I read about setUp test data in this question. I can create data in setUpClass for all test in a class. Creating my complete data test is time consuming approach so I want to run it once for all of test classes, is any approach to set up data for all test classes once?
score: 11
has answer: http://stackoverflow.com/a/52367869
accepted answer: http://stackoverflow.com/a/52367869
type: AnsweredQuestion

http://stackoverflow.com/a/52315156
score: 3
answers question: http://stackoverflow.com/q/52315095
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91578144
type: Answer
has comment: http://stackoverflow.com/comment/91577800
has body: Instead of using string concatenation (which creates a new string each time) you could use str.join(): def human_readable_address(self): ''' Return human readable address If address1 is empty, return None ''' if not self.address1: return None return ', '.join(filter(None, [self.address1, self.address2, self.city, self.postal_code, self.country]))
has comment: http://stackoverflow.com/comment/91577477
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52315095

http://stackoverflow.com/comment/110890464
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52384378
has text: good evening dear Dakshinarmurty Karra: many thanks for steppin up the plate with this great answer: i got stuck with the exactly same issue: – cf https://stackoverflow.com/questions/62595317/login-to-page-with-selenium-works-parsing-with-bs4-works-but-not-the-combina - well i think i have to digg deeper into your ideas and approach. - look forward to hear from you. Regards zero

http://stackoverflow.com/comment/91663981
type: AnswerComment
has text: I would have gone the simple way: `url_text.replace('https://', 'https://user@pass')`
type: Comment
comment on: http://stackoverflow.com/a/52359525
score: 4

http://stackoverflow.com/a/52314299
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52313506
answers question: http://stackoverflow.com/q/52313506
has body: You can do this by constraining your first array (OPEN) to the positions where the condition you want your second array (CLOSED) to be true: constrained = OPEN[CLOSED!=1] and then find the first position of the minimum value with argmin(): pos = constrained.argmin() The only problem with this is that constrained is a 1D array, which means that you need to map pos back to an index pair in the original OPEN. You can do this using np.where(), which returns you a tuple of index arrays where a certain condition is fulfilled: valid_positions = np.where(CLOSED!=1) Turning this tuple into an array and indexing it with pos gives you the index pair that corresponds to pos: idx = np.asarray(valid_positions)[:,pos]
downvote count: 0
type: AcceptedAnswer
upvote count: 2

http://stackoverflow.com/comment/91596293
has text: The type is list
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52324464

http://stackoverflow.com/a/52406932
score: 0
type: Answer
has body: Provide the complete path: var2 = open("C:/Users/Matthew/AppData/Local/Programs/Python/Python37-32/password.txt","r") Edit: As you said in the comment that it worked but the password was marked as incorrect, so I have fixed issues with your code. You cannot read data directly by opening a file. You will have to use the command read to get the data: file = open("C:/Users/Matthew/AppData/Local/Programs/Python/Python36/password.txt","r") var2 = file.read() file.close() Your second code problem is setting new password. The code you made: answer = input("Do you wish to change your password (Y/N): ") if input == "Y" or "y": var2 = input("Enter new password: ") elif input == "N" or "n": break Don't use input to see the value, use the variable in which you stored the input data. Also lower the string to make it easy: answer = input("Do you wish to change your password (Y/N): ") if answer.lower() == "y": var2 = input("Enter new password: ") elif answer.lower() == "n": break The full code can be like: import os import time def password(): while True: username = input ("Enter Username: ") password = input ("Enter Password: ") var1 = "admin" file = open("C:/Users/Matthew/AppData/Local/Programs/Python/Python36/password.txt","r") var2 = file.read() file.close() if username == var1 and password == var2: time.sleep(1) print ("Login successful!") answer = input("Do you wish to change your password (Y/N): ") if answer.lower() == "y": var2 = input("Enter new password: ") elif answer.lower() == "n": break logged() break else: print ("Incorrect Information!") def logged(): time.sleep(1) print ("Welcome to the Encryption program.") password() def main(): result = 'Your message is: ' message = '' choice = 'none' while choice != '-1': choice = input("\nDo you want to encrypt or decrypt the message?\nEnter 1 to Encrypt, 2 to Decrypt, -1 to Exit Program: ") if choice == '1': message = input("\nEnter the message to encrypt: ") for i in range(0, len(message)): result = result + chr(ord(message…
answers question: http://stackoverflow.com/q/52406884
has comment: http://stackoverflow.com/comment/91758925

http://stackoverflow.com/comment/91538365
has text: @ClaraDocej, sure. For instance, you can use [pygame.mixer.music.load](https://www.pygame.org/docs/ref/music.html#pygame.mixer.music.load) to load the music for playback…
type: AnswerComment
comment on: http://stackoverflow.com/a/52284520
score: 0
type: Comment

http://stackoverflow.com/a/52417376
has comment: http://stackoverflow.com/comment/91815153
type: Answer
has comment: http://stackoverflow.com/comment/91778566
has body: You get only the last batter because you are overwriting the value of csk each time in your first loop. Initialize the empty list bat_data first and then add each batter to it. bat_data= [] for batter_row in blah: csk = blah bat_data.append(csk) This will give you a list of all batters, ['Abreu,Jose0.01', 'Acuna,Ronald0.01', 'Adam,Jason0.01', ...] Then loop through this list but you don't have to check if string is in the name. Just do x.replace('0.01', '') and then check if the string is empty. To reverse the order of the names substring = substring.split(',') substring.reverse() nn = " ".join(substring) Then append nn to the result. You are getting the quotes and the brackets because you are printing the list. Instead iterate through the list and print each item. Your code edited assuming you got bat_data correctly: for x in bat_data : substring = x.replace(string,'') if substring != "": substring = substring.split(',') substring.reverse() substring = ' '.join(substring) result.append(substring) for x in result: print(x)
score: 0
has comment: http://stackoverflow.com/comment/91778254
answers question: http://stackoverflow.com/q/52416986

http://stackoverflow.com/q/52427270
tagged with: python
has title: How can I get the text from an element without any class/id/whatever from a website w/ selenium python?
tagged with: selenium-chromedriver
tagged with: selenium
has body: I need to get the string ': 1:30 pm' in the following piece of html code using python and selenium: https://gyazo.com/faa95c118c25db13f5f71361eb795d6c I wouldn't know how to do it since it seems like I can't use anything to identify it. Update bigger section of the html code: https://gyazo.com/dec5665f771945b7671ef6a811b08dfe That is all I have, and I would need a program that returns me the string with the time, which changes everyday.
type: Question
has comment: http://stackoverflow.com/comment/91797772
has comment: http://stackoverflow.com/comment/91797865
score: 0
has comment: http://stackoverflow.com/comment/91800139
answer count: 1
has answer: http://stackoverflow.com/a/52427661
type: UnansweredQuestion

http://stackoverflow.com/comment/91649174
comment on: http://stackoverflow.com/q/52352005
score: 0
type: Comment
type: QuestionComment
has text: why it dose not returns [1,6] and [0,2,3,4,5] how it distributed?

http://stackoverflow.com/comment/91779332
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52418047
type: Comment
has text: @Jamiewp Sorry it was a type `os.path.abspath(f)`

http://stackoverflow.com/comment/91545475
score: 0
type: Comment
type: QuestionComment
has text: I agree that it must be something else in the project. I'd be looking for any code that sets up or modifies the root logger.
comment on: http://stackoverflow.com/q/52298365

http://stackoverflow.com/a/52301661
has comment: http://stackoverflow.com/comment/91557574
type: Answer
has comment: http://stackoverflow.com/comment/91585437
score: 2
accepted answer of: http://stackoverflow.com/q/52300954
upvote count: 2
has body: Creating a list of columns of interest : cols = [ *orig.columns.difference(df.columns),'Sex_x','Pclass_x', 'Title_x', 'Survived_x', 'Age_x', 'Age_y', 'Fare' ] Doing a left merge (join) on columns Sex, PClass and Title and filling the NaN values with values from Age_y : orig = orig.merge(df, on=['Sex', 'PClass', 'Title'], how='left')[cols] orig['Age'] = df['Age_x'].fillna(df['Age_y']) Dropping the now redundant Age_x and Age_y columns : orig.drop(columns=['Age_x', 'Age_y'], inplace=True)
answers question: http://stackoverflow.com/q/52300954
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52415981
answers question: http://stackoverflow.com/q/52415929
has body: The case when functions have to share variables is a classical motivation of the object-oriented programming. You can turn those function to be members of a class with an attribute self.model, initialized in __init__(self) as self.model = None: class MyClass(object): def __init__(self): self.model = None def gen(self, sentence): self.model = gensim.models.word2vec.Word2Vec([sentence],min_count=1, workers=1, size=3) ... def name(self, sentence): ... # below is a test if __name__ == '__main__': sentence = 'sadfdsafesafsdf' my_obj = MyClass() something_returned = my_obj.gen(sentence) something_else_returned = my_obj.name(sentence) Then you modify that variable by calling the function gen() and use it in the function name().
type: Answer
has comment: http://stackoverflow.com/comment/91775890
has comment: http://stackoverflow.com/comment/91775952
has comment: http://stackoverflow.com/comment/91775555
score: 0

http://stackoverflow.com/q/52324230
tagged with: join
upvote count: 3
type: Question
has body: I am trying to reference a list of expired orders from one spreadsheet(df name = data2), and vlookup them on the new orders spreadsheet (df name = data) to delete all the rows that contain expired orders. Then return a new spreadsheet(df name = results). I am having trouble trying to mimic what I do in excel vloookup/sort/delete in pandas. Please view psuedo code/steps as code: Import simple.xls as dataframe called 'data' Import wo.xlsm, sheet name "T" as dataframe called 'data2' Do a vlookup , using Column "A" in the "data" to be used to as the values to be matched with any of the same values in Column "A" of "data2" (there both just Order Id's) For all values that exist inside Column A in 'data2' and also exist in Column "A" of the 'data',group ( if necessary) and delete the entire row(there is 26 columns) for each matched Order ID found in Column A of both datasets. To reiterate, deleting the entire row for the matches found in the 'data' file. Save the smaller dataset as results. import pandas as pd data = pd.read_excel("ors_simple.xlsx", encoding = "ISO-8859-1", dtype=object) data2 = pd.read_excel("wos.xlsm", sheet_name = "T") results = data.merge(data2,on='Work_Order') writer = pd.ExcelWriter('vlookuped.xlsx', engine='xlsxwriter') results.to_excel(writer, sheet_name='Sheet1') writer.save()
has answer: http://stackoverflow.com/a/52331232
tagged with: pandas
score: 3
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91601616
favorite count: 0
type: UnansweredQuestion
has title: Pandas - merge/join/vlookup df and delete all rows that get a match
tagged with: python

http://stackoverflow.com/comment/91670949
score: 0
has text: Thanks, looks nice!
type: AnswerComment
comment on: http://stackoverflow.com/a/52333792
type: Comment

http://stackoverflow.com/q/52276295
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/66006367
linked to: http://stackoverflow.com/q/11352528
linked to: http://stackoverflow.com/q/31543444
tagged with: hough-transform
score: 9
type: Question
has comment: http://stackoverflow.com/comment/91502272
answer count: 2
has comment: http://stackoverflow.com/comment/91501494
has comment: http://stackoverflow.com/comment/91501035
favorite count: 0
has answer: http://stackoverflow.com/a/52279922
accepted answer: http://stackoverflow.com/a/52279922
has title: OpenCV+python: HoughLines accumulator access since 3.4.2
linked to: http://stackoverflow.com/q/3265987
tagged with: python
has body: In OpenCV 3.4.2 the option to return the number of votes (accumulator value) for each line returned by HoughLines() was added. In python this seems to be supported as well as read in the python docstring of my OpenCV installation: "Each line is represented by a 2 or 3 element vector (ρ, θ) or (ρ, θ, votes) ." It is also included in the docs (with some broken formatting). However I can find no way to return the 3 element option (ρ, θ, votes) in python. Here is code demonstrating the problem: import numpy as np import cv2 print('OpenCV should be at least 3.4.2 to test: ', cv2.__version__) image = np.eye(10, dtype='uint8') lines = cv2.HoughLines(image, 1, np.pi/180, 5) print('(number of lines, 1, output vector dimension): ', lines.shape) print(lines) outputs OpenCV should be at least 3.4.2 to test: 3.4.2 (number of lines, 1, output vector dimension): (3, 1, 2) [[[ 0. 2.3212879]] [[ 1. 2.2340214]] [[-1. 2.4609141]]] The desired behavior is an extra column with the amount of votes each line received. With the vote values more advanced options than the standard thresholding can be applied, as such it has been often requested and asked about on SE (here, here, here and here) with sometimes the equivalent for HoughCircles(). However both the questions and answers (such as modifying source and recompiling) are from before it was added officially, and therefore do not apply to the current situation.
upvote count: 9
downvote count: 0
linked to: http://stackoverflow.com/q/28718956
has answer: http://stackoverflow.com/a/66006367
tagged with: opencv

http://stackoverflow.com/a/52276599
score: 0
has body: So, basically the only way that I found to create shapes in a loop is to create the json object that represents the "layout" myself. In this way I can include as many entries in the dictionary (layout) as I want.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52274271
answers question: http://stackoverflow.com/q/52274271
type: Answer

http://stackoverflow.com/a/52391966
type: Answer
score: 7
upvote count: 7
has body: You seem to be used to a language with deterministic object destruction and dedicated methods for performing that destruction. Python doesn't work that way. Python has no destructors, and even if it had destructors, there is no guarantee that del myData.contA would render the Container object eligible for destruction, let alone actually destroy it. Probably the simplest way is to just define a remove_container paralleling your add_container: def remove_container(self, name): self._containers.remove(name) delattr(self, name) If you really want the syntax for this operation to be del myData.contA, then hook into attribute deletion, by implementing a __delattr__ on Data: def __delattr__(self, name): self._containers.remove(name) super().__delattr__(name)
downvote count: 0
answers question: http://stackoverflow.com/q/52391850
accepted answer of: http://stackoverflow.com/q/52391850
type: AcceptedAnswer

http://stackoverflow.com/comment/91656166
comment on: http://stackoverflow.com/a/52352717
type: Comment
score: 0
type: AnswerComment
has text: @ayush Why do you wanna use DRF's Response class?

http://stackoverflow.com/q/52375784
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52375864
score: 1
upvote count: 1
type: Question
has body: I have a dataframe with dates and tick-data like below Date Bid 0 20160601 00:00:00.020 160.225 1 20160601 00:00:00.136 160.226 2 20160601 00:00:00.192 160.225 3 20160601 00:00:00.327 160.230 4 20160601 00:00:01.606 160.231 5 20160601 00:00:01.613 160.230 I want to filter out unique values in the 'Bid' column at set intervals E.g: 2016-06-01 00:00:00 - 00:15:00, 2016-06-01 00:15:00 - 00:30:00... The result will be a new dataframe (keeping the filtered values with its datetime). Here's the code I have so far: #Convert Date column to index with seconds as base df['Date'] = pd.DatetimeIndex(df['Date']) df['Date'] = df['Date'].astype('datetime64[s]') df.set_index('Date', inplace=True) #Create new DataFrame with filtered values ts = pd.DataFrame(df.loc['2016-06-01'].between_time('00:00', '00:30')['Bid'].unique()) With the method above I loose the [Dates] (datetime) of the filtered values in the process of creating a new DataFrame plus I have to manually input each date and time interval which is unrealistic. Output: 0 0 160.225 1 160.226 2 160.230 3 160.231 4 160.232 5 160.228 6 160.227 Ideally I'm looking for an operation where I can set the time interval as a timedelta and have an operation done on the whole file (about 8Gb) at once, creating a new DataFrame with Date and Bid columns of the unique values within the set interval. Like this Date Bid 0 20160601 00:00:00.020 160.225 1 20160601 00:00:00.136 160.226 2 20160601 00:00:00.327 160.230 3 20160601 00:00:01.606 160.231 ... 805 20160601 00:15:00.606 159.127 PS. I also tried using pd.rolling() &amp; pd.resample() methods with apply(lambda x: function (eg. pd['Bid'].unique()) but it never was able to cut it, maybe someone better at it could attempt.
has comment: http://stackoverflow.com/comment/91696889
tagged with: pandas
has answer: http://stackoverflow.com/a/52375864
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91696654
has title: Filter out unique values of a column within a set time interval
favorite count: 0

http://stackoverflow.com/comment/91627512
has text: I am getting it as a list. but throwing an error at the same point.
comment on: http://stackoverflow.com/a/52340103
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/72419994
type: Answer
has body: Simply, use gunicorn to easen the burden. Within the project directory, with the virtual environment activated, install gunicorn as follows: pip install gunicorn If you're using pipenv you can try: pipenv install gunicorn Update the requirements.txt file to include the new installed gunicorn module by running: pip freeze &gt; requirements.txt Update the Procfile as follows: web: gunicorn your_django_project_name.wsgi --log-file - N.B: There should be space between the web: and gunicorn as well as between --log-file and the - next to it. Lastly, add, commit and push the changes
answers question: http://stackoverflow.com/q/52274578
score: 0

http://stackoverflow.com/comment/91722483
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52365956
score: 0
has text: @fdeslaur awesome glad to hear that. could you please share your version of different lttng entities and write an answer to this question with output I will upvote your answer. Appreciate your help.

image-processing
tags question: http://stackoverflow.com/q/52385215
tags question: http://stackoverflow.com/q/52274378
tags question: http://stackoverflow.com/q/52400838
tags question: http://stackoverflow.com/q/52424812
tags question: http://stackoverflow.com/q/52384386
tags question: http://stackoverflow.com/q/52414542
tags question: http://stackoverflow.com/q/52346399
tags question: http://stackoverflow.com/q/52324937
tags question: http://stackoverflow.com/q/52387590
tags question: http://stackoverflow.com/q/52299913
tags question: http://stackoverflow.com/q/52373938
tags question: http://stackoverflow.com/q/52295087
tags question: http://stackoverflow.com/q/52370466
tags question: http://stackoverflow.com/q/52316556
tags question: http://stackoverflow.com/q/52349669
tags question: http://stackoverflow.com/q/52365190
tags question: http://stackoverflow.com/q/52429910
tags question: http://stackoverflow.com/q/52398237
tags question: http://stackoverflow.com/q/52395121
tags question: http://stackoverflow.com/q/52315895
tags question: http://stackoverflow.com/q/52309291
type: Tag
tags question: http://stackoverflow.com/q/52358819
tags question: http://stackoverflow.com/q/52297189
tags question: http://stackoverflow.com/q/52398468
tags question: http://stackoverflow.com/q/52353944
tags question: http://stackoverflow.com/q/52295414
tags question: http://stackoverflow.com/q/52283791
tags question: http://stackoverflow.com/q/52299833
tags question: http://stackoverflow.com/q/52399017
tags question: http://stackoverflow.com/q/52312513
tag name: image-processing
tags question: http://stackoverflow.com/q/52424021
tags question: http://stackoverflow.com/q/52366207
tags question: http://stackoverflow.com/q/52411321
tags question: http://stackoverflow.com/q/52352678
tags question: http://stackoverflow.com/q/52321305
tags question: http://stackoverflow.com/q/52374197
tags question: http://stackoverflow.com/q/52291284

http://stackoverflow.com/comment/91791747
score: 0
comment on: http://stackoverflow.com/q/52424370
has text: Just a quick hint: it is generally not recommended to use `ctypes` directly. [cffi](https://cffi.readthedocs.io/en/latest/using.html) provides a much easier and robust interface.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91782888
type: Comment
has text: Ok but you have this template a lot of times in your code or do your wrap that one time around the whole code?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52419712

http://stackoverflow.com/a/52305749
downvote count: 2
upvote count: 1
score: -1
answers question: http://stackoverflow.com/q/52305685
has body: You can use the below approach too: myList=[1,50,30,15,14] sorted_ind_list=[] for a in sorted((e,i) for i,e in enumerate(myList)): sorted_ind_list.append(a[1]) print(sorted_ind_list[0:2]) sort has Better performance over heap. comparison
type: Answer
has comment: http://stackoverflow.com/comment/91558849

http://stackoverflow.com/q/52323897
tagged with: heroku
has comment: http://stackoverflow.com/comment/91626030
has comment: http://stackoverflow.com/comment/91625613
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52325243
has title: Failed to push some refs in Git
linked to: http://stackoverflow.com/q/4181861
score: 0
has body: I am trying to upload my bot to Heroku and i ended up getting this error. I don't know what to do now. I tried to do what someone else on Stack Overflow said to do on someone else's problem and it didn't help me. &gt; git push heroku master error: src refspec master does not match any. error: failed to push some refs to 'https://git.heroku.com/flankebot.git' I have tried to do the git pull --rebase then tried to repush it and it done nothing.
answer count: 1
tagged with: github
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91595037

http://stackoverflow.com/comment/91513206
type: Comment
comment on: http://stackoverflow.com/a/52282313
has text: @Komal: literally, if you add `global Message` inside `run_code_1`, you will not get that error. Though, adding confusion to the problem is that a) you're importing `Message` from tkinter, b) you're using `Message` to refer to a `StringVar`, and you're also using `Message` to refer to the text widget.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91605434
has text: Thank you! This one helped alot
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52304106
score: 1

lttng
tags question: http://stackoverflow.com/q/52365956
type: Tag
tag name: lttng

http://stackoverflow.com/comment/91725629
comment on: http://stackoverflow.com/q/52389889
has text: I'm trying to find a better way of doing it, I'm not overly familiar with this method so I'm learning as I go
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52393770
duplicate of: http://stackoverflow.com/q/14964805
duplicate of: http://stackoverflow.com/q/10768724
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52393991
tagged with: python
has comment: http://stackoverflow.com/comment/91733235
has comment: http://stackoverflow.com/comment/91732868
has body: I am writing a simple bash calculator for class and have almost completed it, but I am running into problems with two issues: I am using an if/then argument to try to deal with divide by zero errors. I continue to get an error from this section of the script I use python to return non-integer numbers and it works on all operations except division. I'm not sure why this one specific operation is not working. I have looked at all the posts it gave me at the top of the screen and I also google queried site:stackoverflow.com for a number of tags and didn't find anything that worked to fix either of these issues. If I'm in the wrong forum or it's already been answered -this is my first time using the site - so I apologize in advance. Any insight would be most helpful. Thanks in advance! Here are the sections: Problem 1: if command returns an error, how would I go about fixing so that it opts out if divide by zero? if [ $n3 -eq 4 $$ $n2 -eq 0 ] then echo "Oops, cannot divide by zero. Your answer is undefined." if End of first problem. Problem 2: the below equation does not output non-integer numbers, (e.g. 1 divided by three shows 0, I want it to show 0.333 or similar), why? 4) quotient=$(python -c "print $n1/$n2") echo "The quotient of $n1 and $n2 is $quotient" ;; End of problem area 2. *) echo "Invalid Option. Pick a number between 1-4 for your operator." ;; esac
has comment: http://stackoverflow.com/comment/91732991
type: Question
has comment: http://stackoverflow.com/comment/91733039
has title: bash: divide by zero error and dividing only shows integer answers
has comment: http://stackoverflow.com/comment/91732932
score: 0
tagged with: bash
linked to: http://stackoverflow.com/q/14964805
answer count: 1
linked to: http://stackoverflow.com/q/10768724
tagged with: shell

http://stackoverflow.com/comment/91527388
comment on: http://stackoverflow.com/q/52282108
score: 0
has text: why are you blocking the training of the last 2 layers , in transfer learning those 2 should be the most important when you are training your model. its either that the model is changing but without the allowing the change to the last two layers your model cant learn properly or that you are somehow over fitting on the batches .
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52379109
upvote count: 1
downvote count: 1
type: Answer
has body: Dictionary order is not preserved by default. If you want that for any reason then you need to use OrderedDict instead
answers question: http://stackoverflow.com/q/52379082
has comment: http://stackoverflow.com/comment/91702547
score: 0

http://stackoverflow.com/a/52335461
has body: This is happening because you have two channels (conda-forge and defaults), both of which contain NumPy (and its dependencies), but possibly at different version / build numbers. For example, say you want to install SciPy (which depends on NumPy) and the state of the world is: conda-forge: NumPy v1.14 and SciPy v1.0 defaults: NumPy v1.15 and SciPy v1.0 And you have conda-forge above defaults in your channel order. If you say conda install scipy, then Conda will grab SciPy from conda-forge (because it is the highest version number). While scanning SciPy's dependencies it will notice that there is a newer version of NumPy available on defaults. Thinking it is being helpful, Conda will install the newer version of NumPy from defaults even though you already had it installed from conda-forge. If there are packages that NumPy depends on that then have to be downgraded to make this work, so be it. By saying instead, conda install scipy numpy or conda config --add pinned_packages conda-forge::numpy you are skipping the dependency lookup for that part of the graph, that then causes the Conda solver to hop to a different channel. This is a relatively simple example and definitely doesn't cover all of the weird edge cases that come up on a daily basis. That said, Conda v4.6 (which isn't out yet) will add a notion of "strict channel priority." This will ensure that the solver looks for packages in the channel order given first and only hops to a different channel if a dependency cannot be found. This will solve a lot of these rampant upgrade/downgrade issues we have all been living with.
downvote count: 0
upvote count: 8
type: Answer
answers question: http://stackoverflow.com/q/52305421
score: 8
has comment: http://stackoverflow.com/comment/92437671

http://stackoverflow.com/q/52327384
has answer: http://stackoverflow.com/a/52341467
upvote count: 8
tagged with: python
score: 8
tagged with: metaclass
has body: We can use functions as metaclass and my understanding is they are not derived from type as shown below : def test_meta(name, bases, atts): print("testmeta called for " + name) return type(name,bases,atts); class Computer: __metaclass__ = test_meta def __init__(self,brand,model,price): self.brand = brand self.model = model self.price = price # # ob = Computer('p1','core2duo',21985.25) However when we write metaclass it should be inherited from type and i could not understand the reasoning behind this : class MyMeta: def __new__(meta, name, bases, dct): print ('-----------------------------------') print ("Allocating memory for class", name) print (meta) print (bases) print (dct) return type.__new__(meta, name, bases, dct) def __init__(cls, name, bases, dct): print ('-----------------------------------') print ("Initializing class", name) print (cls) print (bases) print (dct) type.__init__(cls,name, bases, dct) def __call__(mcs, *args, **kwargs): print ('-----------------------------------') print ("calling class") print mcs class Computer: __metaclass__ = MyMeta def __init__(self,brand,model,price): self.brand = brand self.model = model self.price = price # # ob = Computer('p1','core2duo',21985.25) For example in above code I could not understand why MyMeta class should be inherited from type when we are explicitly calling type functions i.e. new,init,call. Also the error "descriptor 'init' requires a 'type' object but received a 'instance'" is coming only when i=instance (ob) is created.
has comment: http://stackoverflow.com/comment/91602082
accepted answer: http://stackoverflow.com/a/52341467
type: AnsweredQuestion
type: Question
has title: Why metaclass should inherit from type?
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/52339411
has answer: http://stackoverflow.com/a/52340216
tagged with: python
tagged with: selenium
tagged with: web-scraping
tagged with: google-chrome
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91626272
has comment: http://stackoverflow.com/comment/91637058
has answer: http://stackoverflow.com/a/52339615
has title: TypeError when sending keys to text field with Selenium in Python
has comment: http://stackoverflow.com/comment/91626156
score: 0
type: UnansweredQuestion
has body: I'm experiencing a very strange issue when trying to send text to a text field with Python. This is my code: keyword_text_field = driver.find_element_by_xpath('//*[@id="558450155"]') keyword_text_field.clear() keyword_text_field.send_keys('Ford') search_button = driver.find_element_by_xpath('//*[@id="mountNode"]/div/div[4]/div[3]/div[1]/div[1]/div/div[2]/div/div[18]/div[2]/button') search_button.click() The url is the following: https://www.autotrader.com/cars-for-sale/searchresults.xhtml?zip=84025&amp;keywordPhrases=rebuilt%20title&amp;startYear=2014&amp;endYear=2018&amp;sellerTypes=p&amp;searchRadius=0&amp;sortBy=derivedpriceDESC&amp;numRecords=25&amp;firstRecord=0 This is the error I get: File "/Users/rodrigopeniche/Documents/workspace/WebScraping/AutoTraderScraper.py", line 34, in search_for_keyword keyword_text_field.send_keys('Ford') File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webelement.py", line 478, in send_keys {'text': "".join(keys_to_typing(value)), File "/Library/Python/2.7/site-packages/selenium/webdriver/common/utils.py", line 150, in keys_to_typing for i in range(len(val)): TypeError: object of type 'WebElement' has no len() My environment techinical specs are the following: Python 2.7 Chrome 68.0.3440.106 Chromedriver 2.42 Selenium 3.13 Any idea why this is happening? I have no problem sending keys to other text fields in the same site.

http://stackoverflow.com/q/52392577
has comment: http://stackoverflow.com/comment/91730368
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/91732167
has body: I have 2 windows machine (A and B) both have tensorflow-gpu 1.10 installed. I have a training.py which train and save the best full model checkpoint = tf.keras.callbacks.ModelCheckpoint(params['filepath_best'], monitor='val_loss', verbose=0, save_best_only=True, save_weights_only=False, mode='auto', period=1) callbacks_list = [checkpoint, tf.keras.callbacks.TensorBoard(log_dir=params['log_dir'])] model.compile(optimizer='adam', loss='MSE', metrics=['MSE']) history = model.fit(keras_input_fn(filenames=training_files, mode=tf.estimator.ModeKeys.TRAIN).batch(16).repeat(1000), epochs=1000, steps_per_epoch=625, validation_data=keras_input_fn(filenames=training_files, mode=tf.estimator.ModeKeys.EVAL).batch(16).repeat(1000), validation_steps=625, callbacks=callbacks_list) I also have a detect.py which load the trained model and do predictions model = load_model(params['filepath_best']) training.py and detect.py runs separately. training runs fine, and detect.py in machine A can load the model generated by the training.py on machine A. However, detect.py in machine A can NOT load the copied model generated by the training.py on machine B. In the same way, detect.py in machine B can only load the model generated from machine B, it can't load a copied model generated from machine A. the training.py and detect.py in both machines are identical but the dir is different. It seems that the saved model contains the info of local dir of the specific machine which generates the model thus it can't be used on another machine. The copied model is in the correct dir for loading. In training.py, I have a function relu_advanced(x) which basically truncate the maximum to 255, and it is called when construct the keras model. def relu_advanced(x): return K.relu(x, max_value=255) # in model construction part net = tf.keras.layers.Lambda(function = relu_advanced)(net) When I run detec.py on machine B using copied model from machine A, it complains the relu_advanced function using the dir of t…
tagged with: tensorflow
type: Question
has title: Keras model saved in ModelCheckpoint in tensorflow can't be loaded on another machine
tagged with: keras
score: 0
answer count: 0

http://stackoverflow.com/a/52300471
type: Answer
has body: Code prints position and length of series: s = 'TCAAAAACCABBBT' start = 0 for i in range(1, len(s) + 1): if (i==len(s) or s[i] != s[i-1]): if (i - start &gt; 1): print(start, i - start) start = i &gt;&gt;2 5 7 2 10 3
score: 0
answers question: http://stackoverflow.com/q/52300300

http://stackoverflow.com/comment/91520627
has text: instead of `df[cols] = ...`, use `df = pd.concat((df,df[cols].add(1)),axis=1)`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52285732

http://stackoverflow.com/comment/91659890
type: Comment
has text: Can't get to your expected output with the sample input you provided, but `df.groupby(df.TIME.dt.hour).count()` is probably a good start for you
comment on: http://stackoverflow.com/q/52357676
score: 0
type: QuestionComment

http://stackoverflow.com/a/52417391
type: Answer
answers question: http://stackoverflow.com/q/52417059
score: 1
upvote count: 1
has body: If you want to limit the query to 2 results with distinct user_ids, simply use distinct() two_rows = Table.query.filter_by(category='category1').distinct(Table.user_id).limit(2).all() more precisions here, there, and of course the basics here
accepted answer of: http://stackoverflow.com/q/52417059
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52305499
has comment: http://stackoverflow.com/comment/91558445
has answer: http://stackoverflow.com/a/52307555
type: AnsweredQuestion
has body: I have a list of objects ['P1','P2','P3'] with [0.8,0.1,0.1] as corresponding weights. I found out numpy choice takes weight as input, but I dont see the output list to exactly match the input probability Code: draw = [choice(['P1','P2','P3'],p=[0.8,0.1,0.1]) for _ in range(10)] from collections import Counter print(Counter(draw)) I expected draw to be always contain 8 instances of P1, 1 of P2 and 1 of P3. But I see that it varies from run to run when using the above code. Sample output: Run 1: Counter({'P1': 7, 'P2': 2, 'P3': 1}) Run 2: Counter({'P1': 10}) Run 3: Counter({'P1': 9, 'P2': 1}) Am I missing something or is this expected output?
type: Question
tagged with: numpy
answer count: 2
possible better answer: http://stackoverflow.com/a/52307555
score: 0
has comment: http://stackoverflow.com/comment/91559380
has title: Weighted Choice in Numpy does not return list with exact input probability
has answer: http://stackoverflow.com/a/52305577
accepted answer: http://stackoverflow.com/a/52305577
has comment: http://stackoverflow.com/comment/91559248
tagged with: python

fractions
type: Tag
tags question: http://stackoverflow.com/q/52383948
tag name: fractions

http://stackoverflow.com/q/52285502
tagged with: list
downvote count: 0
type: UnansweredQuestion
type: Question
tagged with: list-comprehension
upvote count: 2
has answer: http://stackoverflow.com/a/52285519
answer count: 1
tagged with: string
favorite count: 0
has body: I would like to iterate through a list of strings and replace each instance of a character ('1', for example) with a word. I am confused why this would not work. for x in list_of_strings: x.replace('1', 'Ace') Side note, the strings within the lists are multiple characters long. ('1 of Spades)
has title: Replace function in list of strings
tagged with: python
score: 2
tagged with: python-3.x

http://stackoverflow.com/comment/91801526
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52425849
has text: Although this is a splendid idea I would like to accomplish this task with mostly my own code, I am just trying to figure it out :) Thank you though
score: 0

http://stackoverflow.com/comment/91880768
has text: You're right, doing it on small blocks (for example 1024 samples, i.e. ~23ms at 44.1Khz sampling rate) makes it work in the "sliding case": https://stackoverflow.com/a/52469397/1422096. The important part is to care about the initial condition parameter.
type: AnswerComment
comment on: http://stackoverflow.com/a/52451378
score: 0
type: Comment

http://stackoverflow.com/q/52289959
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/91530780
has comment: http://stackoverflow.com/comment/91530139
has title: How to install optparse module?
has comment: http://stackoverflow.com/comment/91527980
has comment: http://stackoverflow.com/comment/91530903
tagged with: openwrt
has comment: http://stackoverflow.com/comment/91529388
upvote count: 1
tagged with: optparse
has comment: http://stackoverflow.com/comment/91528313
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91528711
has comment: http://stackoverflow.com/comment/91535479
has comment: http://stackoverflow.com/comment/91527922
has comment: http://stackoverflow.com/comment/91530430
has comment: http://stackoverflow.com/comment/91528813
score: 1
has body: I'm going to build one package under ubuntu and I'm starting the configure script. Problem: optparse module is not installed: sh-4.3$ ./configure Traceback (most recent call last): File "./configure", line 29, in &lt;module&gt; import optparse ImportError: No module named optparse I'm not sure, but I'm presuming that this is the python module and it has to be installed somehow with opkg install python-optparse, but this doesn't work. Is this a part of some other module? How can I install it? My version of python is 2.7.9. Thank you! Aleksej.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/91528523
has answer: http://stackoverflow.com/a/62412471

http://stackoverflow.com/comment/91535669
type: QuestionComment
has text: yeah this is working, I laso started update via conda prompt. But the main window isnt opening.
comment on: http://stackoverflow.com/q/52293956
score: 0
type: Comment

http://stackoverflow.com/comment/91575769
comment on: http://stackoverflow.com/q/52310042
has text: @rakwen I've read the document and try two examples online but still cannot apply the principle to my case. It would be great if you have time to help me on this. Thanks.
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/q/52329718
has comment: http://stackoverflow.com/comment/91606237
type: Question
linked to: http://stackoverflow.com/q/3134691
upvote count: 0
score: -2
has title: How to match python strings similar to like in mysql
answer count: 2
has comment: http://stackoverflow.com/comment/91607582
favorite count: 0
type: UnansweredQuestion
has body: a = "This is some text" b = "This text" I want to compare the variable b in a and should return true even if the text contains more than two words like a = "This is another text here" b = "This another here" even if I compare b in a should return true in python Condition: True == All words in b found, the same order, in a. In the above examples, the words have to be in the same order and upper/lowercase.
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/91607310
has answer: http://stackoverflow.com/a/52331927
downvote count: 2
has answer: http://stackoverflow.com/a/52329860

http://stackoverflow.com/comment/102874539
has text: This is horrible programming practice tho. They are inventing unnecessary edge cases. Now I have to write different code for the case where there is only 1 subplot
score: 31
type: AnswerComment
comment on: http://stackoverflow.com/a/52273900
type: Comment

http://stackoverflow.com/q/52419411
has comment: http://stackoverflow.com/comment/91782661
has comment: http://stackoverflow.com/comment/91782581
has comment: http://stackoverflow.com/comment/91781965
has comment: http://stackoverflow.com/comment/91782883
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91782755
has title: Problem when modifying function that closes over some variable. Old closure does not fit. Empty closure crashes interpreter
has answer: http://stackoverflow.com/a/52420584
tagged with: dynamic
tagged with: metaprogramming
has comment: http://stackoverflow.com/comment/91783288
type: Question
tagged with: types
answer count: 1
has comment: http://stackoverflow.com/comment/91782449
has comment: http://stackoverflow.com/comment/91782490
has body: I want to dynamically add arguments to a function run_func that calls another function. If I do not copy the __closure__ object from run_func to modified_func, Python crashes as soon as I try to call modified_func. If I try to copy the old closure object to the modified function, it does not fit: "#ValueError: run_func requires closure of length 0, not 1" How can I do the modification properly so the modified function does not crash? import types def make_facade(func, param_names): def run_func(): return func() code = run_func.__code__ modified_code = types.CodeType( len(param_names), #code.co_argcount code.co_kwonlyargcount, len(param_names), #code.co_nlocals code.co_stacksize, code.co_flags, code.co_code, code.co_consts, code.co_names, tuple(param_names), #code.co_varnames code.co_filename, code.co_name, code.co_firstlineno, code.co_lnotab ) #modified_func = types.FunctionType(modified_code, run_func.__globals__, closure=run_func.__closure__) #ValueError: run_func requires closure of length 0, not 1 modified_func = types.FunctionType(modified_code, run_func.__globals__) return modified_func def ffff(dict): print(dict) ffff_facade = make_facade(ffff, ['arg1', 'arg2']) help(ffff_facade) #Help on function run_func in module __main__: run_func(arg1, arg2) ffff_facade(1, 2) #Crash
tagged with: python

http://stackoverflow.com/q/52398546
has comment: http://stackoverflow.com/comment/91761344
upvote count: 0
has answer: http://stackoverflow.com/a/53755020
has comment: http://stackoverflow.com/comment/91762074
favorite count: 0
has comment: http://stackoverflow.com/comment/91766575
type: UnansweredQuestion
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/91761683
has answer: http://stackoverflow.com/a/52398787
has comment: http://stackoverflow.com/comment/91771810
tagged with: matplotlib
has title: Error installing matplotlib for python on windows 10
score: -1
has comment: http://stackoverflow.com/comment/91755932
type: Question
has body: So I've been doing python coding in my Aer E 160 class. I had to install python on my computer to finish a project, and while it installed on my Desktop just fine, my laptop is having an issue. I was able to install python from python.org just fine, Idle works. I was also able to use the command prompt to install numpy. My real issue is I can't install matplotlib on my laptop, even though I had no issue with it on my desktop. I keep getting the error: Command "python setup.py egg_info" failed with error code 1 in C:\Users\david\AppData\Local\Temp\pip-install-ye8uykcy\matplotlib. How do I fix this? I've tried solutions on google but none of them have worked. Please help!
answer count: 2

http://stackoverflow.com/a/52335583
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91618411
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52335490
has comment: http://stackoverflow.com/comment/91618361
has comment: http://stackoverflow.com/comment/91618305
has body: import re filename='A11 - A22 - '#A## - A## - re.sub(filename,r'^[A-Z]\d\d\s-\s[A-Z]\d\d\s-\s', '')

http://stackoverflow.com/q/52354640
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: http://stackoverflow.com/tag/json
downvote count: 2
type: Question
score: -2
tagged with: flask
has body: I make a server with Flask. I want to get form with data and convert it to json file. example test and I expect to this: { "your_name" : "my_name", "animal":[ { "name": "mono", "age":"12" }, { "name": "jir", "age":"34" } ] } } if someone know how to do it, thanks
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52354806
has title: Convert form data to JSON with sub arrays

multivariate-testing
tags question: http://stackoverflow.com/q/52285109
tag name: multivariate-testing
type: Tag

performance
tags question: http://stackoverflow.com/q/52363433
tags question: http://stackoverflow.com/q/52300481
tags question: http://stackoverflow.com/q/52272229
tags question: http://stackoverflow.com/q/52274356
tags question: http://stackoverflow.com/q/52425332
tags question: http://stackoverflow.com/q/52321549
tags question: http://stackoverflow.com/q/52378578
tags question: http://stackoverflow.com/q/52279699
tags question: http://stackoverflow.com/q/52334593
tags question: http://stackoverflow.com/q/52280499
tags question: http://stackoverflow.com/q/52297308
tags question: http://stackoverflow.com/q/52291007
tags question: http://stackoverflow.com/q/52298118
tags question: http://stackoverflow.com/q/52329820
tag name: performance
tags question: http://stackoverflow.com/q/52429260
tags question: http://stackoverflow.com/q/52370748
type: Tag
tags question: http://stackoverflow.com/q/52299082
tags question: http://stackoverflow.com/q/52360686
tags question: http://stackoverflow.com/q/52334338
tags question: http://stackoverflow.com/q/52418777
tags question: http://stackoverflow.com/q/52406563
tags question: http://stackoverflow.com/q/52343188
tags question: http://stackoverflow.com/q/52326479

http://stackoverflow.com/q/52313685
has comment: http://stackoverflow.com/comment/91585619
has comment: http://stackoverflow.com/comment/91574678
type: Question
tagged with: trigonometry
tagged with: python
accepted answer: http://stackoverflow.com/a/52441009
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91585785
tagged with: vertices
has comment: http://stackoverflow.com/comment/91575067
has title: moving arrowhead across its body
has answer: http://stackoverflow.com/a/52441009
has comment: http://stackoverflow.com/comment/91617008
tagged with: vector
type: AnsweredQuestion
has body: I have created the following function which gets two line points and outputs three points of an arrowhead triangle. What I need to add is a length according to which the arrowhead will be poisitioned away from the point B across the line AB. To explain it better, I would like it like this: A----->--B where the two dashes are equal to the length def create_arrowhead(A, B): """ Calculate the arrowheads vertex positions according to the edge direction. Parameters ---------- A : array x,y Starting point of edge B : array x,y Ending point of edge Returns ------- B, v1, v2 : tuple The point of head, the v1 xy and v2 xy points of the two base vertices of the arrowhead. """ w = 0.005 # half width of the triangle base h = w * 0.8660254037844386467637 # sqrt(3)/2 mag = math.sqrt((B[0] - A[0])**2.0 + (B[1] - A[1])**2.0) u0 = (B[0] - A[0]) / (mag) u1 = (B[1] - A[1]) / (mag) U = [u0, u1] V = [-U[1], U[0]] v1 = [B[0] - h * U[0] + w * V[0], B[1] - h * U[1] + w * V[1]] v2 = [B[0] - h * U[0] - w * V[0], B[1] - h * U[1] - w * V[1]] return (B, v1, v2)

http://stackoverflow.com/comment/91619023
has text: How do you check the output?
score: 0
comment on: http://stackoverflow.com/q/52335920
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52353943
type: Question
has comment: http://stackoverflow.com/comment/91652609
duplicate of: http://stackoverflow.com/q/1207406
answer count: 1
downvote count: 0
has title: Program skips over list element
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52354118
score: 1
has body: I'm trying to make a program that tracks how an (example) cell colony would grow. It's very simple; cell starts at age 0 at age 1 cell is adult able to reproduce, creating 1 cell each year (slow, I know) at age m cell dies we want the number of cells after n years Example:n = 6 and m = 3 results in 4 cells I tried to solve this by creating two lists: babies = [0] (one starting cell) adults = [] My plan was moving each baby_cell to the adult list after the baby would be age 1, this is also where the problem lies. This is what I wrote: index = 0 for baby in babies: if baby == 1: adults.append(baby) del babies[index] index += 1 It only moves one cell, so if babies = [1, 1] it will only remove one of the two and leave the other one there. Over time these accumulate, and you end up with a babies list full of adults... I have never been this stuck since I started programming. I'm probably overlooking something simple, but still, I need help!
upvote count: 1
linked to: http://stackoverflow.com/q/1207406

http://stackoverflow.com/comment/91507400
type: AnswerComment
comment on: http://stackoverflow.com/a/52275970
score: 0
type: Comment
has text: What about the case if the data is not incrementing every month?

peewee
tag name: peewee
type: Tag
tags question: http://stackoverflow.com/q/52285458
tags question: http://stackoverflow.com/q/52311278

http://stackoverflow.com/comment/91609190
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52331082
type: QuestionComment
has text: Or try `mask = (data['sender'] == 'me').values & (data['status'] == 'done').values`

http://stackoverflow.com/a/52379946
answers question: http://stackoverflow.com/q/52373266
score: 0
type: Answer
has body: Here is another variation on how to achieve the desired results. Not as pretty as I would like though, so I expect there is a much more elegant way. Probably more regex than is really necessary if you spent a bit more time on this, and also seems like the break approach to handling the final key is probably just an indicator that the loop logic could be improved to eliminate that sort of manual intervention. That said, hopefully this is helpful in the process of refining your approach here. import re def unflatten(data): results = {} list_rgx = re.compile(r'[^\[\]]+\[\d+\]') idx_rgx = re.compile(r'\d+(?=\])') key_rgx = re.compile(r'[^\[]+') for text, value in data.items(): cur = results keys = text.split('.') idx = None for i, key in enumerate(keys): stop = (i == len(keys) - 1) if idx is not None: val = value if stop else {} if len(cur) &gt; idx: cur[idx] = {key: val} else: for x in range(len(cur), idx + 1): cur.append({key: val}) if x == idx else cur.append(None) if stop: break else: cur[idx].get(key) idx = None if stop: cur[key] = value break elif re.match(list_rgx, key): idx = int(re.search(idx_rgx, key).group()) key = re.search(key_rgx, key).group() cur.setdefault(key, []) else: cur.setdefault(key, {}) cur = cur.get(key) print(results) Output: d = {"a.b.c[0].key1": 1, "a.b.c[1].key2": 2, "a.b.c[3].key3": 3} unflatten(d) # {'a': {'b': {'c': [{'key1': 1}, {'key2': 2}, None, {'key3': 3}]}}}

http://stackoverflow.com/comment/91773729
comment on: http://stackoverflow.com/q/52414599
type: Comment
score: 1
type: QuestionComment
has text: Is that really the expected result? What happened to the `'A': ['A4']` from df2? Should df3 have `'A': ['E4']` or `'E': ['E4']`?

http://stackoverflow.com/a/52428529
downvote count: 0
score: 7
has body: You don't need the parentheses with iloc: self.landmarks_frame.iloc[index, 0]
type: AcceptedAnswer
upvote count: 7
type: Answer
answers question: http://stackoverflow.com/q/52428472
accepted answer of: http://stackoverflow.com/q/52428472

http://stackoverflow.com/comment/91533345
comment on: http://stackoverflow.com/q/52292599
score: 0
type: Comment
type: QuestionComment
has text: @Arne There is some info relevant to Python 3 there, but it's not obvious. In fact, it's not easy to tell when most of those answers are talking about old-style vs new-style classes.

http://stackoverflow.com/q/52288029
has body: I want to create a function that calculates and returns the projection of a vector x on a vector b as well as the reconstruction error. My code is the following: def reconstruction_error(x, b): '''The function calculates the projection and reconstruction error from projecting a vector x onto a vector b''' b = np.matrix(b) x_projection_on_b = (b.T @ b/ float((b@b.T))) @ x reconstruction_error = (x - x_projection_on_b) @ (x - x_projection_on_b).T return( x_projection_on_b, float(reconstruction_error)) However the reconstruction error is not correct. E.g., x = np.array([1,1,1]) b = np.array([5, 10, 10]) a, error = reconstruction_error(x, b) a matrix([[0.55555556, 1.11111111, 1.11111111]]) error 0.2222222222222222
has answer: http://stackoverflow.com/a/52290082
downvote count: 0
score: 1
type: Question
tagged with: numpy
tagged with: projection
has answer: http://stackoverflow.com/a/66077299
has title: Function that computes projection and recostruction error using numpy - python
has comment: http://stackoverflow.com/comment/91530693
has comment: http://stackoverflow.com/comment/91524551
answer count: 2
upvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91741301
has text: Also, there is no purpose in calling `dictjson = json.dumps(jsondata)`, nor in calling the result `dictjson` when `dumps()` returns a string. You are just getting back the same JSON string you read in `line`.
comment on: http://stackoverflow.com/a/52397953
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91537757
type: QuestionComment
comment on: http://stackoverflow.com/q/52294071
has text: You are actually trying to access 11 elements, not 10 (numbers start from 0, so, from 0 to 10 you have 11 elements). Probably enough to change 'h <= 10' to 'h < 10'
score: 1
type: Comment

http://stackoverflow.com/comment/91713886
type: QuestionComment
comment on: http://stackoverflow.com/q/52384096
score: 0
type: Comment
has text: Can you add the full stacktrace of the error?

http://stackoverflow.com/a/52320145
has body: I haven't used reduceat much, but it looks like you can only have one open ended range, one add to the end. One way around that is to pad the array (yes, I do normally rail against using np.append :) ): In [165]: np.add.reduceat(np.append(x,0),[0,6,3]) Out[165]: array([15, 0, 12]) or with a full pairing of ranges: In [166]: np.add.reduceat(np.append(x,0),[0,6,3,6]) Out[166]: array([15, 0, 12, 0]) I omitted the usual [::2] to clarify what is going on.
has comment: http://stackoverflow.com/comment/91587660
upvote count: 4
has comment: http://stackoverflow.com/comment/126890188
type: AcceptedAnswer
score: 4
has comment: http://stackoverflow.com/comment/129355829
has comment: http://stackoverflow.com/comment/91589448
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52319504
type: Answer
answers question: http://stackoverflow.com/q/52319504

http://stackoverflow.com/comment/91567347
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52310042
has text: @DanielRoseman hi Daniel, what if I don't want to create a number of instances? What is the meaning of creating instances? I did that is because the example did so and I cannot find an alternative method to change that. Thanks for your quick reply.
type: Comment

http://stackoverflow.com/q/52387920
answer count: 1
has title: Python: running tally of iterator values without building a list
score: 0
has answer: http://stackoverflow.com/a/52388002
tagged with: python
type: AnsweredQuestion
has body: I would like to calculate unique values of an iterator, but without having to build a list first. Using a list, I would do for example: from collections import Counter from itertools import combinations my_counts = Counter([sum(x) for x in combinations([1,2,3,4,5])],2) But above, a list was made, and then Counter was applied. But is there a way to keep a running tally, so that the entire list does not need to stored in memory?
duplicate of: http://stackoverflow.com/q/47789
type: Question
accepted answer: http://stackoverflow.com/a/52388002
has comment: http://stackoverflow.com/comment/91720673
tagged with: iterator
linked to: http://stackoverflow.com/q/47789

http://stackoverflow.com/comment/91493040
type: QuestionComment
comment on: http://stackoverflow.com/q/52272850
has text: @jpp yes, so my current operation for producing RevenueCAGR is wrong...
score: 0
type: Comment

http://stackoverflow.com/comment/91741713
has text: Sorround the statement or code block in `try: except: Exception, e` to catch the network exceptions and do whatever you want in catch/except section.
comment on: http://stackoverflow.com/q/52398769
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/91498636
has text: you *optionally* sets `price` attribute on `self` *but always* read it in `price_book` method. Your code may causing AttributeError
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52275560
type: Comment

http://stackoverflow.com/comment/91509526
comment on: http://stackoverflow.com/q/52280718
has text: What is the `self` in `self.Grandma.sayHello()`?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52318017
has title: constraint that calls for the previous/next set member in indexed Set
linked to: http://stackoverflow.com/q/43047684
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91584031
tagged with: python
has comment: http://stackoverflow.com/comment/91608208
has body: Does this example somehow also work with (string-)indexed Sets? In my case I get the following Error: 'IndexedSet' object has no attribute 'next' Working example with non indexed Sets: m.s = Set(initialize=['A','B','C'], ordered=True) m.v = Var(m.s) def _c_rule(m, i): if i == 'A': return Constraint.Skip return m.v[i] &lt;= m.v[m.s.prev(i)] m.c = Constraint(m.s, rule=_c_rule) # Or the opposite way def _c2_rule(m, i): if i == 'C': return Constraint.Skip return m.v[m.s.next(i)] &lt;= m.v[i] m.c2 = Constraint(m.s, rule=_c2_rule) src: Constraint that calls for the previous set member Not working: model = ConcreteModel() model.S = Set(("A", "B", "C"),initialize=("A", "B", "C"), ordered=True) print(model.S.next(model.S["A"])) If not, is there a work-around?
type: Question
tagged with: pyomo
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52336020

subprocess
tags question: http://stackoverflow.com/q/52305112
tag name: subprocess
tags question: http://stackoverflow.com/q/52288775
tags question: http://stackoverflow.com/q/52333558
tags question: http://stackoverflow.com/q/52375998
tags question: http://stackoverflow.com/q/52378007
tags question: http://stackoverflow.com/q/52335195
tags question: http://stackoverflow.com/q/52341165
tags question: http://stackoverflow.com/q/52274383
tags question: http://stackoverflow.com/q/52290482
tags question: http://stackoverflow.com/q/52356102
tags question: http://stackoverflow.com/q/52409827
tags question: http://stackoverflow.com/q/52289557
tags question: http://stackoverflow.com/q/52364601
tags question: http://stackoverflow.com/q/52319537
tags question: http://stackoverflow.com/q/52418187
tags question: http://stackoverflow.com/q/52297000
tags question: http://stackoverflow.com/q/52325215
tags question: http://stackoverflow.com/q/52372489
type: Tag
tags question: http://stackoverflow.com/q/52330553
tags question: http://stackoverflow.com/q/52407318
tags question: http://stackoverflow.com/q/52369810
tags question: http://stackoverflow.com/q/52288485
tags question: http://stackoverflow.com/q/52324228
tags question: http://stackoverflow.com/q/52417442
tags question: http://stackoverflow.com/q/52408841
tags question: http://stackoverflow.com/q/52374445
tags question: http://stackoverflow.com/q/52423507
tags question: http://stackoverflow.com/q/52320232
tags question: http://stackoverflow.com/q/52423031
tags question: http://stackoverflow.com/q/52370412
tags question: http://stackoverflow.com/q/52394697

http://stackoverflow.com/comment/91607838
score: 1
has text: Could you please add how your user input is stored? How does the user input the undefined character `_`?
type: QuestionComment
comment on: http://stackoverflow.com/q/52330370
type: Comment

http://stackoverflow.com/q/52347921
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91641286
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/91641344
type: Question
linked to: http://stackoverflow.com/q/4383571
has title: Error importing file in the above directory
has comment: http://stackoverflow.com/comment/91641815
linked to: http://stackoverflow.com/q/52335995
has comment: http://stackoverflow.com/comment/91641297
has body: I have the fallowing directory tree: foo_project/ ├── foo/ │ ├── foo_conversor.py │ ├── __init__.py │ └── __pycache__/ │ ├── foo.py └── __pycache__/ I'm trying to import a class named Foo that is inside foo.py at foo_conversor.py, I've tried a lot of ways but I can't understand how to do this import. Can someone help me? It's any problem with __init__.py? I already tried: from ..foo import Foo from .. import Foo from . import Foo from foo import Foo I've already read a lot fo answers here but none helped me.

http://stackoverflow.com/q/52281369
type: UnansweredQuestion
tagged with: python
tagged with: amazon-s3
has answer: http://stackoverflow.com/a/52281584
type: Question
answer count: 2
tagged with: amazon-cloudtrail
tagged with: boto3
tagged with: amazon-web-services
has body: I'm trying to develop a way of breaking down S3 by which users/projects using CloudTrail. Does CloudTrail offer the ability to see which IAM user uploaded a a particular object to a bucket? UPDATE: I have a CloudTrail turned on that monitors object-level activities (for all s3 buckets, including read and write activities), however, when I try to list "PutObject" events in my update above, it doesn't work (i.e. the list of events comes up blank). ct_client = boto3.client('cloudtrail') response = ct_client.lookup_events( LookupAttributes=[ { 'AttributeKey': 'EventName', 'AttributeValue': 'PutObject' }], StartTime=datetime(2018, 3, 1), EndTime=datetime.now(), MaxResults=50 ) UPDATE 2 Images of my bucket properties and CloudTrail in the console:
score: 0
has title: Using boto3 to query AWS CloudTrail to determine which IAM user uploaded a file to S3?
has answer: http://stackoverflow.com/a/52283459

http://stackoverflow.com/q/52338552
has body: I created a toy dataset which has dim of (n_rows, 51) 50 features and 1 truth. When I do a simple linear regression keras works. Yet once a attempt to use a GRU or LSTM nothing works. Below is an attempt to make this easy on myself. Can someone help me figure out whats wrong. ` model = Sequential() model.add(GRU(50)) model.add(Flatten()) model.add(Reshape((None, 50))) model.add(Dense(units=1, activation='softmax')) model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy']) model.fit(x_train, y_train, epochs=10, batch_size=20) `
has comment: http://stackoverflow.com/comment/91625663
type: Question
has title: keras GRU won't take my simple 2-d arrays
score: 0
answer count: 1
tagged with: keras
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52341920

http://stackoverflow.com/q/52393021
has title: insert enum datatype via pandas.to_sql
score: 0
answer count: 2
tagged with: pandas
linked to: http://stackoverflow.com/q/15655820
tagged with: postgresql
type: UnansweredQuestion
tagged with: python
has body: I have a pandas dataframe as follows: In [93]: df = pd.DataFrame([[1, 'a'], [2, 'b'], [3, 'a']], columns=['val', 'types']) In [94]: df Out[94]: val types 0 1 a 1 2 b 2 3 a In [95]: df.dtypes Out[95]: val int64 types object dtype: object # convert the 'types' column to category In [96]: df.types = pd.Categorical(df.types) Assuming I already have a postgres table with column types as ENUM, how do I insert data into my DB via sqlachemy types with pandas to_sql method? I tried this but couldn't make it work: In [101]: class myEnum(enum.Enum): ...: a = 1 ...: b = 2 ...: In [102]: from sqlalchemy.types import * In [103]: sql_dtypes = {'val' : SmallInteger(), 'types': Enum(myEnum)} In [104]: df.to_sql('tablename', conn, if_exists='replace', index=False, dtype=sql_dtypes) running which gives me the following error: sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) type "myEnum" already exists [SQL: "CREATE TYPE myEnum AS ENUM ('a', 'b')"] (Background on this error at: http://sqlalche.me/e/f405) Specifying with the schema option from pd.io.json.build_table_schema too didn't help.
has answer: http://stackoverflow.com/a/52400499
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/76699693
has comment: http://stackoverflow.com/comment/109390787

http://stackoverflow.com/q/52384645
has comment: http://stackoverflow.com/comment/91713629
has title: Nested Dictionaries within a Dictionary Structure in Python, Would like to output in a specific manner
has answer: http://stackoverflow.com/a/52385044
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52385044
has answer: http://stackoverflow.com/a/52385101
tagged with: file
upvote count: 1
tagged with: output
has answer: http://stackoverflow.com/a/52385072
has comment: http://stackoverflow.com/comment/91713913
type: Question
has body: I have done analysis around stack overflow for an answer to this but it feels a bit specific, happy to go to your links if you suggest them. A. I've got a dictionary holding a bunch of dictionaries in this format: Key : {Nested_Key: Nested_Value} Key = Document ID, Data Type is String Nested Key = Token ID, Data Type is Integer Nested Value = Count of Token ID, Data Type is Integer Example: d = { '441' : {201:1, 220:1, 232:1, ..., 23231:4}, '4452' : {203:43, 2202: 45} } B: I'd like to be able to output them into a text file in this format: document_(key), nested_key:nested value, nested_key:nested value \n document_(key+1), nested_key:nested value, nested_key: nested value \n I'm able to get fairly close to what I want using this code: with open("text.txt", "w") as f: for key, token in dict.items(): f.write('doc%s,%s\n' % (key, token)) But as you would expect it outputs the nested key and nested value in its dictionary doc_441,{201: 1, 220: 1, 232: 1, 240: 1, 241: 1, 242: 1, 243: 1, 245: 1, 246: 1, 250: 1, 255: 1, 260: 1, 271: 1, 493: 1, 494: 1, 540: 1, 608: 1, 609: 1, 610: 1, 611: 1, 612: 1, 613: 1, 614: 1, 835: 1, 836: 1, 965: 1, 966: 1, 967: 1, 986: 1, 1291: 1, 1292: 1, 1734: 1, 1735: 1, 1736: 1, 1748: 1, 1749: 1, 1762: 1, 1763: 1, 1818: 1, 1819: 1, 1820: 1, 1821: 1, 1822: 1, 1875: 1, 1881: 1, 1882: 1, 1883: 1, 1890: 1, 1891: 1, 1941: 1, 1947: 1, 1948: 1} doc_577,{201: 1, 205: 1, 217: 1, 232: 1, 233: 1, 235: 1, 236: 1, 237: 1, 238: 1, 241: 1, 242: 1, 243: 1, 244: 1, 245: 1, 246: 1, 247: 1, 248: 1, 249: 1, 250: 1, 251: 1, 280: 1, 448: 1, 493: 1, 494: 1, 537: 1, 540: 1, 571: 1, 572: 1, 573: 1, 574: 1, 575: 1, 669: 1, 670: 1, 671: 1, 672: 1, 673: 1, 674: 1, 675: 1, 690: 1, 731: 1, 732: 1, 733: 1, 734: 1, 735: 1, 736: 1, 770: 1, 771: 1, 772: 1, 773: 1, 777: 1, 947: 1, 948: 1, 949: 1, 950: 1} I've tried some ridiculously convoluted code to try and cajole the code into what I want but this one only outputs the last line in the nested dictionary's nested key: nested tok…
has comment: http://stackoverflow.com/comment/91713949
answer count: 3
has comment: http://stackoverflow.com/comment/91713880
has comment: http://stackoverflow.com/comment/91713794
has comment: http://stackoverflow.com/comment/91714141
downvote count: 0
tagged with: nested
accepted answer: http://stackoverflow.com/a/52385072
score: 1
favorite count: 0

http://stackoverflow.com/q/52275258
score: 0
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
has body: I have a df that has many columns. I need to make a pie using the users columns and appear according to the number column. users number col1 col2 user1 1 12 abc user2 34 13 .. user3 56 12 user4 45 .. user5 4 user1 3 user5 11 user1 3 How to do the pie according to the percent that users have in the number column?So it can be clear who has the higher number as a percentage of the whole. If you need clarification ask me. Thanks I did: plt.pie(x['users'],x['number']) but it says: ValueError: could not convert string to float: 'user11'
has answer: http://stackoverflow.com/a/52275424
upvote count: 1
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91498024
has answer: http://stackoverflow.com/a/52275452
accepted answer: http://stackoverflow.com/a/52275452
tagged with: matplotlib
has title: Make a pie in matplotlib from a column
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/52275424
favorite count: 0
tagged with: statistics

http://stackoverflow.com/comment/91496825
score: 0
type: Comment
has text: I mean to put the figsize in one line during the `plt.bar(x['user'], x['number'], color="blue")` as a parameter in this line. Is it possible?
comment on: http://stackoverflow.com/a/52274708
type: AnswerComment

http://stackoverflow.com/comment/91551623
type: Comment
has text: `filtered_wordlist` seems to be a list of lists. Hence you might be ending up passing a list rather than a string.
type: QuestionComment
comment on: http://stackoverflow.com/q/52301716
score: 0

http://stackoverflow.com/comment/91621459
comment on: http://stackoverflow.com/a/52327211
score: 0
type: Comment
has text: I found this which states that there is a problem from Jupyter https://stackoverflow.com/questions/47313732/jupyter-notebook-never-finishes-processing-using-multiprocessing-python-3/47374811#47374811.
type: AnswerComment

http://stackoverflow.com/a/52277166
has comment: http://stackoverflow.com/comment/91514771
has comment: http://stackoverflow.com/comment/91511444
type: Answer
has comment: http://stackoverflow.com/comment/91509893
has comment: http://stackoverflow.com/comment/91505855
upvote count: 1
has comment: http://stackoverflow.com/comment/91511061
has comment: http://stackoverflow.com/comment/91504570
has comment: http://stackoverflow.com/comment/91510006
score: 1
has body: Just having trouble seeing where you are hung up, if it's retrieving the prices or setting them to the instance. def __init__(self, **kwargs): for k, v in kwarg.items(): setattr(self, k, v) self.price = [] for k, v in kwargs.items(): for i in range(len(v)): self.price.append(v[i]['price']) (xenial)vash@localhost:~/python/AtBS$ python3.7 comphren.py [13.55, 7.99] Suggestion by Request One thing I would I didn't do because I'm unsure I think the use of data creates unneeded nesting that unless you are going to have books and say movies otherwise you could just call this whole thing books and remove one level of nesting. Also this method logs duplicates, which I worked around using set but you could avoid appending duplicates with more code, didn't want to do too much because still unsure of entire task. But if the goal was just to create these lists of each piece of data this code will work: pages = [] publish_dates = [] subjects = [] titles = [] prices = [] for v in data.values(): for i in range(len(v)): for w, x in v[i].items(): pages.append(v[i]['number_of_pages']) publish_dates.append(v[i]['publish_date']) titles.append(v[i]['title']) prices.append(v[i]['price']) for a in v[i]['subjects']: subjects.append(a) print(f"Pages: {set(pages)}\nPublish Dates: {set(publish_dates)}\n" \ f"Subjects: {set(subjects)}\nTitles:{set(titles)}\n" \ f"Prices: {set(prices)}") Output (xenial)vash@localhost:~/python/AtBS$ python3.7 comphren.py Pages: {849, 732} Publish Dates: {2011, 1999} Subjects: {'Time travel', 'Widows', 'Authors', 'Widowers', 'Assassination', 'Haunted houses', 'Grandfathers', "Writer's block", 'Novelists', 'Trials (Custody of children)', 'Custody of children'} Titles:{'11/22/63', 'Bag of bones'} Prices: {13.55, 7.99}
accepted answer of: http://stackoverflow.com/q/52275560
answers question: http://stackoverflow.com/q/52275560
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91513407
has comment: http://stackoverflow.com/comment/91513501

http://stackoverflow.com/a/52331588
downvote count: 0
score: 6
upvote count: 6
accepted answer of: http://stackoverflow.com/q/52331557
answers question: http://stackoverflow.com/q/52331557
type: AcceptedAnswer
has body: Use pandas.get_dummies with sum: df = pd.get_dummies(a, prefix_sep='', prefix='').sum(axis=1, level=0) print (df) financial game food social sport 0 1 0 0 2 0 1 0 1 1 0 1 2 0 2 0 0 1 Or stack with SeriesGroupBy.value_counts and Series.unstack: df = a.stack().groupby(level=0).value_counts().unstack(fill_value=0) print (df) financial food game social sport 0 1 0 0 2 0 1 0 1 1 0 1 2 0 0 2 0 1
type: Answer

http://stackoverflow.com/a/55485079
has comment: http://stackoverflow.com/comment/112308833
has comment: http://stackoverflow.com/comment/112308897
type: Answer
has comment: http://stackoverflow.com/comment/114394885
upvote count: 9
answers question: http://stackoverflow.com/q/52337870
has body: According to this issue posted on the OpenCV GitHub, this is a known issue that the developer states is damn near impossible to fix. It is apparently caused by a conflict in any Qt installations on the system with the Qt that is shipped with OpenCV. There are some suggestions floating around to remove the libqt5x11extras5 package from the system. This may fix it for some but anyone running these libraries on a Linux distribution that uses a window manager based on Qt will render their desktop environment unusable by removing this package (having tried it myself). You can try building OpenCV from source using the WITH_GTK=ON option when running cmake which will use GTK instead of Qt, circumventing the conflict. However, this is hard to make use of in Python when using virtual environments.
has comment: http://stackoverflow.com/comment/112560014
has comment: http://stackoverflow.com/comment/112495806
has comment: http://stackoverflow.com/comment/112529971
downvote count: 0
score: 9
has comment: http://stackoverflow.com/comment/112595698
has comment: http://stackoverflow.com/comment/110401409

http://stackoverflow.com/q/52390576
possible better answer: http://stackoverflow.com/a/57246799
type: Question
has body: I have a dataclass whose instances I want to hash and order, using the id member as a key. from dataclasses import dataclass, field @dataclass(eq=True, order=True) class Category: id: str = field(compare=True) name: str = field(default="set this in post_init", compare=False) I know that I can implement __hash__ myself. However, I would like dataclasses to do the work for me because they are intended to handle this. Unfortunately, the above dataclass fails: a = sorted(list(set([ Category(id='x'), Category(id='y')]))) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'Category'
has answer: http://stackoverflow.com/a/57246799
has answer: http://stackoverflow.com/a/77174679
has answer: http://stackoverflow.com/a/52390734
accepted answer: http://stackoverflow.com/a/52390734
upvote count: 181
downvote count: 1
tagged with: python-dataclasses
favorite count: 0
has answer: http://stackoverflow.com/a/52390731
tagged with: python-3.x
tagged with: hash
has comment: http://stackoverflow.com/comment/93995355
tagged with: python
score: 180
has title: How can I make a python dataclass hashable?
linked to: http://stackoverflow.com/q/47955263
answer count: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/91583676
has text: I think we are almost there. Using; with open ('diff.csv', 'w') as outFile: outFile.write(json.dumps(fileOne_dict)) I get a continuous line rather than the original layout eg; test1 Pass Failed test 2 Pass test 3 FailedToBuild etc
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52316923

http://stackoverflow.com/q/52363390
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91670937
type: AnsweredQuestion
score: 1
has title: AttributeError: 'tuple' object has no attribute 'get' in Django
type: Question
has comment: http://stackoverflow.com/comment/91671132
accepted answer: http://stackoverflow.com/a/52363562
upvote count: 1
answer count: 1
downvote count: 0
has body: I want to add a multiple choice field to my project app. This field should allow the user for select more than one choice. But I get an error. Before I added the multiple choice field, this part did not give any error. Where is my mistake? my views.py def project_new(request): if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): project = Project() ... project.lang_choices = form.cleaned_data['select_lang'] project.save() return redirect('projects') else: form = ProjectForm() return render(request, 'blog/project_new.html', {'form': form}) @login_required(login_url='/login/') def project_details(request, pk): project = get_object_or_404(Project, pk=pk) return render(request, 'blog/project_detail.html', {'project': project}) my models.py class ProgrammingLanguage(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Project(models.Model): ... select_langs = models.ManyToManyField(ProgrammingLanguage) ... slug = models.UUIDField(default=uuid.uuid4) ... forms.py class ProjectForm(forms.Form): ... select_lang = forms.ChoiceField( label='diller: ', widget=forms.CheckboxSelectMultiple() ) def __init__(self, *args, **kwargs): super(ProjectForm, self).__init__(args, kwargs) self.fields['select_lang'].choices = [(l.id, l.name) for l in ProgrammingLanguage.objects.all()] class Meta: model = Project fields = ( 'first_name', 'last_name', 'email', 'project_name', 'project_description', 'project_notes', 'select_langs') And this is my traceback Internal Server Error: /project/new/ Traceback (most recent call last): File "/home/eda/.local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/eda/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/eda/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _…
favorite count: 0
has answer: http://stackoverflow.com/a/52363562
has comment: http://stackoverflow.com/comment/91670904

http://stackoverflow.com/a/52306251
type: Answer
has body: Looks like you are creating two dataframes out of the same dataframe, and then processing them. Two things that may cut your time. First, you are iterating over both dataframes and checking for a condition: for _, row in carq_data.iterrows(): for _, arow in final_df.iterrows(): if arow['POSDATETIME'] == row['POSDATETIME']: # do something by using both tables This is essentially an implementation of a join. You are joining carq_data with final_df on 'POSDATETIME'. As a first step, you should merge the tables: merged = carq_data.merge(final_df, on=['POSDATETIME']) At this point you will get multiple rows for each similar 'POSDATETIME'. In the below, let's assume column b is POSDATETIME: &gt;&gt;&gt; a a b 0 1 11 1 1 33 &gt;&gt;&gt; b a b 0 1 2 1 1 3 2 1 4 &gt;&gt;&gt; merged = a.merge(b, on=['a']) &gt;&gt;&gt; merged a b_x b_y 0 1 11 2 1 1 11 3 2 1 11 4 3 1 33 2 4 1 33 3 5 1 33 4 Now, to do your conditional calculations, you can use the apply() function. First, define a function: def calc_dist_error(row): return int(round(haversine(row['b_x'], row['b_y'], miles=True))) if row['a'] != 0.0 else None Then apply it to every row: merged['dist_error'] = merged.apply(calc_dist_error, axis=1) Continuing my small example: &gt;&gt;&gt; merged['c'] = [1, 0, 0, 0, 2, 3] &gt;&gt;&gt; merged a b_x b_y c 0 1 11 2 1 1 1 11 3 0 2 1 11 4 0 3 1 33 2 0 4 1 33 3 2 5 1 33 4 3 &gt;&gt;&gt; def foo(row): ... return row['b_x'] - row['b_y'] if row['c'] != 0 else None ... &gt;&gt;&gt; merged['dist_error'] = merged.apply(foo, axis=1) &gt;&gt;&gt; merged a b_x b_y c dist_error 0 1 11 2 1 9.0 1 1 11 3 0 NaN 2 1 11 4 0 NaN 3 1 33 2 0 NaN 4 1 33 3 2 30.0 5 1 33 4 3 29.0 This should help you reduce run time (see also this for how to check using %timeit). Hope this helps!
score: 0
answers question: http://stackoverflow.com/q/52305104

http://stackoverflow.com/q/52358707
score: 3
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/52358783
tagged with: python
answer count: 1
has title: How to use Python in solving Lambert W function?
downvote count: 1
upvote count: 4
has body: I am working on this function named lambert W function. It is usually applied when questions of the format 2^x= 5x comes in and the property xe^x=y then x=w(y) where w is Lambert function. Although MATLAB can effectively dissolve it, but I also want to see if Python can be used to get same quality result.
type: UnansweredQuestion

http://stackoverflow.com/comment/120522860
type: Comment
has text: Note that (Ana)conda has a license agreement. So depending on your context, this might not be an option.
comment on: http://stackoverflow.com/a/62323213
type: AnswerComment
score: 0

http://stackoverflow.com/q/52323681
has comment: http://stackoverflow.com/comment/91594682
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91594577
type: Question
tagged with: numpy
has title: Ignoring multiple NaNs when calculating standard deviation
score: 4
has comment: http://stackoverflow.com/comment/91594615
tagged with: pandas
has body: I have the following pandas dataframe which contains some 5 minute intraday data. DeltaBetweenClose is NaN for the first trade bar in the day when market opens(9:30 EST). time Date symbol DeltaBetweenClose 9:35 2017-07-17 spy NaN 9:40 2017-07-17 spy -1.2 .......................................... .......................................... 16:00 2018-07-17 spy 1.7 9:35 2017-07-18 spy NaN 9:40 2017-07-18 spy 0.3 .......................................... .......................................... 9:35 2018-07-17 nflx NaN I am trying to create a column CloseDelta_sd that calculates a rolling standard deviation of DeltaBetweenClose column grouped by symbols that looks into the prior 30 bars and calculates standard deviation while ignoring NaNs. My following attempt returns all NaNs. It works when there is only one NaN at the top of the DeltaBetweenClose column. df['CloseDelta_sd'] = df.groupby('symbol').DeltaBetweenClose.transform(lambda x: x.rolling(30).std())
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52323815
favorite count: 0
has comment: http://stackoverflow.com/comment/91594725
has answer: http://stackoverflow.com/a/52323815
upvote count: 4
has comment: http://stackoverflow.com/comment/91594635
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/52348874
score: 0
has comment: http://stackoverflow.com/comment/91643146
has comment: http://stackoverflow.com/comment/91644478
has body: I am looking for a clean way to model data that is optional, but if included will contain a reference to other data. In example below, the cleanest relational modeling is to separate person, insurance plan, and insurance company. class InsurancePlan(models.Model): name = models.CharField(max_length=100, default="Not Indicated") insurancecompany = models.ForeignKey(InsuranceCompany, on_delete=models.CASCADE, null=True, blank=True) claims_address = models.OneToOneField(UsLocation, on_delete=models.CASCADE, blank=True, null=True) class InsuranceCompany(models.Model): name = models.CharField(max_length=50) some_important_id = models.CharField(max_length=50) class Insured(models.Model): name = models.CharField(max_length=50) plan = models.ForeignKey(InsurancePlan, on_delete=models.CASCADE) and then either add a member_id field to the insured model or create an Insured_Plan table that links them. However, what if the business requirements say that having InsurancePlan information is optional, because we can get by just knowing member ID and InsuranceCompany? is it ok to have: class Insured(models.Model): name=... plan = models.ForeignKey(InsurancePlan, on_delete=models.CASCADE, null=True, blank=True) insurance_summary = models.ForeignKey(InsuranceCompany, on_delete=models.CASCADE) member_id = models.CharField() Im a bit rusty on relational modeling, but I think having a fk from A to B, and another from A to C where C has a fk to B as well is not good practice. Update: I think the best approach is class Insured(models.Model): name=models.CharField(max_length=20) class InsurancePlan(models.Model): name=models.CharField(max_length=20, defualt="unknown/not_applicable") members=ManyToManyField(Insured, through='Membership') claims_address=models.OneToOneField(UsLocation, blank=True, null=True) insurance_company=models.ForeignKey(InsuranceCompany, on_delete=models.CASCADE) class Membership(models.Model): insured=ForeignKey(Insured, on_delete=models.CASCADE) plan=ForeignKey(Insu…
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91645117
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91643992
tagged with: django
has comment: http://stackoverflow.com/comment/91643266
has title: Models with optional fields with relations
has comment: http://stackoverflow.com/comment/91643396
tagged with: django-models
type: Question

http://stackoverflow.com/comment/91534491
comment on: http://stackoverflow.com/q/52293248
type: Comment
type: QuestionComment
score: 2
has text: @MosheSlavin What non-string are you talking about?

http://stackoverflow.com/comment/91774636
comment on: http://stackoverflow.com/a/52415556
type: AnswerComment
score: 0
type: Comment
has text: I see, while it is inefficient it is doing what the op asked.

http://stackoverflow.com/q/52322051
score: 1
has answer: http://stackoverflow.com/a/52322052
accepted answer: http://stackoverflow.com/a/52322052
type: Question
has comment: http://stackoverflow.com/comment/91591687
has comment: http://stackoverflow.com/comment/91591694
has comment: http://stackoverflow.com/comment/91591688
upvote count: 1
answer count: 1
favorite count: 0
has body: I have a python script that get started automatically as a service (activated with systemd). In this python script, I call a bash script using subprocess.call(script_file,shell=True). When I call the python script manually ($ python my_python_script.py), everything works perfectly. However, the automatically started program does not execute the bash script (however it does run, I checked this my making it edit a text file, which it indeed does). I (think) I gave everyone read-write permissions to the bash scripts. Does anyone have ideas as to what I'm doing wrong? Addendum: I want to write a small script that sends me my public IP address via telegram. The service file looks like this: [Unit] Description=IPsender After=networking.service [Service] Type=simple User=root WorkingDirectory=/home/pi/projects/tg_bot ExecStart=/home/pi/miniconda3/bin/python /home/pi/projects/tg_bot/ip_sender_tg.py Restart=always [Install] WantedBy=multi-user.target
has title: Python Script Not Starting Bash Script when running as service
has comment: http://stackoverflow.com/comment/91591693
tagged with: bash
has comment: http://stackoverflow.com/comment/91591689
has comment: http://stackoverflow.com/comment/91591691
has comment: http://stackoverflow.com/comment/91591695
tagged with: python
has comment: http://stackoverflow.com/comment/91591692
has comment: http://stackoverflow.com/comment/91591697
has comment: http://stackoverflow.com/comment/91591696
has comment: http://stackoverflow.com/comment/91591690
tagged with: systemd
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/91703455
has text: @Shawn: Very odd. I just tested strace with the additional `trace=getpid` on two separate systems (both the same version of ubuntu, 16.04, unfortunately). Both print the PID but show no call to `getpid`; only '+++ exited with 0 +++'.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52378927
score: 0

http://stackoverflow.com/comment/91611854
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52332509
has text: @jonrsharpe I get that too. Op, have you updated to the latest version of isodate (0.6.0?)

http://stackoverflow.com/comment/91603447
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52316774
has text: @RahulAgarwal and also the second value "T72_VAS_SCHEME_IDENTIFIER_3="

http://stackoverflow.com/a/52350641
has body: From How to get multiline input from user: no_of_lines = 5 lines = "" for i in range(no_of_lines): lines+=input()+"\n" print(lines) You can set the number of lines of input to whatever is necessary for you.
has comment: http://stackoverflow.com/comment/91646638
has comment: http://stackoverflow.com/comment/91646619
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52350581

http://stackoverflow.com/q/52386417
has comment: http://stackoverflow.com/comment/91717405
has body: I want to split sentences in a document but firstly I want to find decimals,version numbers etc. in document and change the points to commas. For example: I used the default "2.00" quality setting in Premiere 2.0.1, and specified a key frame every ten frames. I want change this sentence to the above form I used the default "2,00" quality setting in Premiere 2,0,1, and specified a key frame every ten frames. re.findall('\d*\.?\d+',s) this code finds decimal but I couldn't change points to commas
answer count: 3
has answer: http://stackoverflow.com/a/52386703
tagged with: python
has comment: http://stackoverflow.com/comment/91717683
has comment: http://stackoverflow.com/comment/91717202
type: UnansweredQuestion
has title: Find Points inside the Sentence and replace them with commas in Python
has answer: http://stackoverflow.com/a/52386702
type: Question
linked to: http://stackoverflow.com/q/16720541
tagged with: decimal
score: 0
has answer: http://stackoverflow.com/a/52386822

http://stackoverflow.com/comment/91656592
has text: I'm using it for the stock market, so during the weekdays each file contains data from 10:00 to 18:00
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52355953
score: 0

http://stackoverflow.com/q/52293475
tagged with: python
tagged with: append
type: AnsweredQuestion
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/52307825
has answer: http://stackoverflow.com/a/52307825
type: Question
has body: I have created a list of .txt file directories in Python and then wrote a function to combine these. def combine_directory_txt(FilePaths): """ This function will combine all files in a directory by importing each, and appending them to a single output. It only works for csv's (.txt) with a delimeter of "|" """ Output = pd.DataFrame() # Dataframe which will store the final table Increment = 0 Total = len(FilePaths) # Import each file and join them together for file in FilePaths: Increment += 1 Import = pd.read_csv(file, sep = '|', error_bad_lines = False, low_memory = False, encoding='mbcs' ) Output = Output.append(Import) print (Increment, " of ", Total, " joined") del Import return Output This works fine, except my PC is struggling with MemoryErrors. Is there a more efficient way to do this? I realise I've used "low_memory = false", this process is to be repeated monthly so I cannot know what the columns will look like and my code was failing very early due to all the dtype warnings. Is this the correct approach? Should I have written code to work out what the dtypes are then assign them to cut down on memory?
has comment: http://stackoverflow.com/comment/91537799
answer count: 2
tagged with: http://stackoverflow.com/tag/csv
upvote count: 1
has title: Memory efficiency .txt appending Python
has comment: http://stackoverflow.com/comment/91537828
favorite count: 0
tagged with: memory-management
has answer: http://stackoverflow.com/a/52296035
has comment: http://stackoverflow.com/comment/91535361
accepted answer: http://stackoverflow.com/a/52296035
has comment: http://stackoverflow.com/comment/91535196

http://stackoverflow.com/q/52323524
tagged with: arrays
answer count: 1
score: 0
has body: I didn't expect them to be different, until it just cost me 2 hours to find a bug. Here is an example showing the difference I noticed, but I couldn't make sense of it. &gt;&gt;&gt; a = np.array([[1, 2], [3, 4]]) &gt;&gt;&gt; a[0][0] 1 &gt;&gt;&gt; a[np.array(0)][np.array(0)] 1 &gt;&gt;&gt; a[0][0] = 5 &gt;&gt;&gt; a array([[5, 2], [3, 4]]) &gt;&gt;&gt; a[np.array(0)][np.array(0)] = 6 &gt;&gt;&gt; a array([[5, 2], [3, 4]]) It looks like using numpy scalar as index the element can't be changed. Is a copy of the original array element instead of the reference being returned? However, with tuple indexing, the problem is gone. &gt;&gt;&gt; a[np.array(0), np.array(0)] = 6 &gt;&gt;&gt; a array([[6, 2], [3, 4]]) What's happening here? I understand sementically chain bracket indexing and tuple indexing are different, but in principle shouldn't they both access the same element regardless? Out of curiosity, I tried it with one dimensional array. The result is different. &gt;&gt;&gt; a = np.array([1, 2]) &gt;&gt;&gt; a[np.array(0)] = 3 &gt;&gt;&gt; a array([3, 2]) This time the element has been modified. The lesson I learned is that I should use tuple index for numpy arrays as much as possible just to be safe. But I would really like an explanation for these inconsistent effects. Thanks!
linked to: http://stackoverflow.com/q/52164376
has title: What's the difference when indexing a numpy array between using an integer and a numpy scalar?
has comment: http://stackoverflow.com/comment/91594326
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52323595
tagged with: indexing
has comment: http://stackoverflow.com/comment/91594287
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91594344

http://stackoverflow.com/a/52322931
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52322843
answers question: http://stackoverflow.com/q/52322843
upvote count: 1
type: AcceptedAnswer
has body: The fact that complex and fractions.Fraction have attributes with those names and meanings doesn't mean ints don't also have such attributes. Different classes are free to have similar attributes: &gt;&gt;&gt; (5).denominator 1 &gt;&gt;&gt; (5).imag 0 &gt;&gt;&gt; (5).numerator 5 &gt;&gt;&gt; (5).real 5 They're not some kind of universal attribute or anything. The int type just implements descriptors for those attributes, for interoperability with other numeric types. Specifically, they were implemented to conform to PEP 3141.
type: Answer

http://stackoverflow.com/a/52316923
has comment: http://stackoverflow.com/comment/91581857
score: 0
has comment: http://stackoverflow.com/comment/91591122
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91672693
accepted answer of: http://stackoverflow.com/q/52315920
has comment: http://stackoverflow.com/comment/91672667
has comment: http://stackoverflow.com/comment/91583676
has comment: http://stackoverflow.com/comment/91582664
type: Answer
has comment: http://stackoverflow.com/comment/91613505
has comment: http://stackoverflow.com/comment/91582820
has comment: http://stackoverflow.com/comment/91602324
answers question: http://stackoverflow.com/q/52315920
has comment: http://stackoverflow.com/comment/91582401
has body: Each row in your csv has a key value pair, so it makes sense to write your csv to a dictionary, and then you can easily compare both values based on keys with open(sys.argv[1], 'r') as t1, open(sys.argv[2], 'r') as t2: # Convert lines of Csv to list reader1 = list(csv.reader(t1)) reader2 = list(csv.reader(t2)) # Create a dictionary of key value pairs for t1 fileOne_dict = {col[0]: [col[1]] for col in reader1} # compare values based on keys and append if different for col in reader2: if fileOne_dict.get(col[0]): if fileOne_dict[col[0]][0] != col[1]: fileOne_dict[col[0]].append(col[1]) else: fileOne_dict[col[0]] = ["", col[1]] out = [[key]+value for key, value in fileOne_dict.items()] print(out) with open ('diff.csv', 'w') as outFile: writer = csv.writer(outFile) writer.writerows(out) This should leave you with a dictionary containing the information you want
has comment: http://stackoverflow.com/comment/91583354
has comment: http://stackoverflow.com/comment/91583082
has comment: http://stackoverflow.com/comment/91672648

http://stackoverflow.com/comment/91582669
score: 0
has text: Easiest way is to use `pandas`. Highlight the column entries and copy. Then use `l = pd.to_clipboard().values` Note that you will need a title for your column to make it work really easily. Also don't assign variables to `list` this will prevent you from using the function `list(stuff)`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52317636

http://stackoverflow.com/comment/91688042
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52371382
score: 1
has text: @DYZ: Actually, for glob-like pattern matching, `fnmatch` is more appropriate. It's actually implemented using `re` under the hood (with caching so repeated use of the same glob pattern doesn't require reconverting/recompiling the equivalent regex over and over), but it works with shell wildcard patterns directly, no need to rewrite them into regular expressions.

http://stackoverflow.com/q/52328800
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/52329029
tagged with: python
has answer: http://stackoverflow.com/a/52329174
type: Question
has answer: http://stackoverflow.com/a/52329224
linked to: http://stackoverflow.com/q/31436783
score: 0
has body: I have 3 dictionaries( 2 of them are setdefault dicts with multiple values)- Score_dict- {'Id_1': [('100001124156327', 0.0), ('100003643614411',0.0)], 'Id_2': [('100000435456546',5.7), ('100000234354556',3.5)]} post_dict- {'Id_1':[(+,100004536)], 'Id_2' :[(-,100035430)]} comment_dict- {'Id_1':[(+,1023434234)], 'Id_2':[(-,10343534534) (*,1097963644)]} My current approach is to write them into 3 different csv files and then merging them,I want to merge them according to a common first row(ID_row). But I am unable to figure out how to merge 3 csv files into a single csv file. Also , Is there any way which I can write all the 3 dictionaries into a single csv without writing them individually. Output required- Ids Score_Ids Post_Ids Comment_Ids Id_1 100001124156327',0.0 +,100004536 +,1023434234 100003643614411',0.0 Id_2 100000435456546',5.7 -,100035430 -,10343534534 100000234354556',3.5 *,1097963644 How to do this in a correct way with the best approach?
answer count: 3
has title: Writing 3 python dictionaries to a csv
tagged with: http://stackoverflow.com/tag/csv
favorite count: 0

http://stackoverflow.com/comment/123247822
type: AnswerComment
type: Comment
has text: Thanks for the excellent explanation! @PaulBissex
score: 1
comment on: http://stackoverflow.com/a/52351829

http://stackoverflow.com/a/52307436
score: 3
has body: You created a variable called list, so when you try to call the list constructor, you're met with an error, since list now refers to a list, instead of a type constructor. Don't use builtin names as variable names. You could also just use dataset.columns.tolist()
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/52307410
type: Answer

http://stackoverflow.com/a/52368737
has comment: http://stackoverflow.com/comment/91681861
answers question: http://stackoverflow.com/q/52368556
has body: Have you ever heard of Levenshtein's distance? I suggest the following algorithm: Split the lists into elements (string1.split(" ")) Loop through list(string1). Inside it loop through list(string2) and if Levenshtein's distance for the two elements is say, less than 3, push the element to the result array. Return result. for i in list(string1): for k in list(string2): if levenshtein(i,k) &lt; 3: res.append(i)
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/q/52396315
upvote count: 3
has title: Printing Numpy arrays without brackets
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/37084812
possible better answer: http://stackoverflow.com/a/52396368
downvote count: 0
accepted answer: http://stackoverflow.com/a/52396418
has comment: http://stackoverflow.com/comment/91737476
favorite count: 0
has answer: http://stackoverflow.com/a/52396335
has answer: http://stackoverflow.com/a/52396786
has answer: http://stackoverflow.com/a/52396368
tagged with: python
has answer: http://stackoverflow.com/a/52396418
answer count: 4
has body: predictions = [x6,x5,x4,x3,x2,x1] predictions Calling the above list yields the following arrays: [array([782.36739152]), array([783.31415872]), array([726.90474426]), array([772.08910103]), array([728.79734162]), array([753.67887657])] Yet I would like to print or call just the numbers inside, no array or brackets around the numbers. Using the function below cleanly saves just the numbers to CSV, but I DON'T want to save the numbers, I want to call them inside iPython: np.savetxt("P:/Earnest/Old/R/OutputPython.csv", predictions, delimiter=",") How can I achieve this?
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/91737501

http://stackoverflow.com/q/52398079
downvote count: 2
tagged with: orm
has answer: http://stackoverflow.com/a/76458540
type: Question
has title: what does this expression do ? default=lambda self: _('New'))
has comment: http://stackoverflow.com/comment/91740361
tagged with: odoo
answer count: 2
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: I am working on Odoo Erp and during code analysis i found this expression in a field definition default=lambda self: _('New') the exact expression is: reference = fields.Char(string='Schedule Reference', required=True, copy=False, readonly=True, states={'draft': [('readonly', False)]}, index=True, default=lambda self: _('New')) i want to know what is _('New') do here.
has answer: http://stackoverflow.com/a/52398178
score: 0

http://stackoverflow.com/q/52375305
favorite count: 0
possible better answer: http://stackoverflow.com/a/52588926
has body: I have trained a super-resolution model. The inference works: def inference(self, filename): img_in = misc.imread(filename) / 255.0 res = self.sess.run(self.out, feed_dict={ self.x: [img_in], self.is_training: False, self.lr_input: 0.0 })[0] * 255.0 image = misc.toimage(res, cmin=0, cmax=255) fn_res = filename.replace(".png", "_result.png").replace(".jpg", "_result.jpg") misc.imsave(fn_res, image) But when the image is larger than 600x600px, it says: terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted (core dumped) I'm using 16GB RAM and 16GB swapfile, inferencing using CPU. But the swapfile set up in Ubuntu 16.04 doesn't help despite it being enough. I know I can workaround this by splitting image into pieces and processing them in order. But in the output there are visible marks of splitting. Why doesn't it work? Is there any way I can implement memory swapfile using Python or Tensorflow? Are there any other workarounds?
has answer: http://stackoverflow.com/a/52588926
upvote count: 2
has comment: http://stackoverflow.com/comment/91769032
has comment: http://stackoverflow.com/comment/91711568
tagged with: python
type: AnsweredQuestion
tagged with: ram
has comment: http://stackoverflow.com/comment/91697134
has answer: http://stackoverflow.com/a/52376843
tagged with: tensorflow
type: Question
has title: Tensorflow, large image inference - not enough memory
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/91773256
has comment: http://stackoverflow.com/comment/91766788
has comment: http://stackoverflow.com/comment/91698258
answer count: 2
score: 2
accepted answer: http://stackoverflow.com/a/52376843
downvote count: 0

http://stackoverflow.com/comment/91704229
comment on: http://stackoverflow.com/q/52379760
score: 0
has text: Can you connect to the process locally? telnet localhost 8000 There's so much that can be going wrong. The next thing to check is firewalling; use tcpdump on the server if the process accepts local network connections to see whether there's any connectivity at all ... can you ping the machine it's hosted on from your workstation?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52346653
has comment: http://stackoverflow.com/comment/91639109
type: Question
has answer: http://stackoverflow.com/a/52346852
has title: Write Python output neatly in a txt file?
has answer: http://stackoverflow.com/a/52346709
has answer: http://stackoverflow.com/a/52346894
has answer: http://stackoverflow.com/a/52346714
possible better answer: http://stackoverflow.com/a/52346894
downvote count: 0
has comment: http://stackoverflow.com/comment/91639089
favorite count: 0
has comment: http://stackoverflow.com/comment/91639467
linked to: http://stackoverflow.com/q/6159900
has comment: http://stackoverflow.com/comment/91638894
tagged with: python
has comment: http://stackoverflow.com/comment/91639025
answer count: 4
accepted answer: http://stackoverflow.com/a/52346714
type: AnsweredQuestion
score: 1
tagged with: file
upvote count: 1
has body: I am trying to create a program that lists and saves all running services on my Windows machine to a txt file. I got it to work but it is not listing line by line like in my output in the Python shell. Also, there are added parenthesis I do not want. See output vs txt file screenshot below. Also, my code is below. Output vs txt file My Code so far: import win32con import win32service #Define ListServices class def ListServices(): resume = 0 accessSCM = win32con.GENERIC_READ accessSrv = win32service.SC_MANAGER_ALL_ACCESS #Open Service Control Manager hscm = win32service.OpenSCManager(None, None, accessSCM) #Enumerate Service Control Manager DB typeFilter = win32service.SERVICE_WIN32 stateFilter = win32service.SERVICE_ACTIVE statuses = win32service.EnumServicesStatus(hscm, typeFilter, stateFilter) for (short_name, desc, status) in statuses: #Save output to txt file f=open('MyServices.txt', 'w') f.write(str(statuses)) f.close() #Print output and append 'Running' at the end of each line print(desc, status, '----------&gt; Running') ListServices();

http://stackoverflow.com/a/52444938
has body: You are looking for the summarize_graph tool. Run summarize_graph --in_graph=your_graph.pb and it will output. If you use docker you can find the summarize_graph on any tensorflow/tensorflow image with the devel tag. For example: wget http://download.tensorflow.org/models/mobilenet_v1_2018_02_22/mobilenet_v1_1.0_224.tgz tar xvf mobilenet_v1_1.0_224.tgz docker run --rm -it -v $PWD:/data tensorflow/tensorflow:1.10.1-devel-py3 # Inside docker cd /tensorflow bazel build tensorflow/tools/graph_transforms:summarize_graph # This may take a while, use --jobs 4 ./bazel-bin/tensorflow/tools/graph_transforms/summarize_graph --in_graph=/data/mobilenet_v1_1.0_224_frozen.pb The output will be: Found 1 possible inputs: (name=input, type=float(1), shape=[?,224,224,3]) No variables spotted. Found 1 possible outputs: (name=MobilenetV1/Predictions/Reshape_1, op=Reshape) Found 4254891 (4.25M) const parameters, 0 (0) variable parameters, and 0 control_edges Op types used: 138 Const, 138 Identity, 27 FusedBatchNorm, 27 Relu6, 15 Conv2D, 13 DepthwiseConv2dNative, 2 Reshape, 1 AvgPool, 1 BiasAdd, 1 Placeholder, 1 Shape, 1 Softmax, 1 Squeeze To use with tensorflow/tools/benchmark:benchmark_model try these arguments: bazel run tensorflow/tools/benchmark:benchmark_model -- --graph=/data/mobilenet_v1_1.0_224_frozen.pb --show_flops --input_layer=input --input_layer_type=float --input_layer_shape=-1,224,224,3 --output_layer=MobilenetV1/Predictions/Reshape_1
downvote count: 0
has comment: http://stackoverflow.com/comment/91838627
type: Answer
has comment: http://stackoverflow.com/comment/91841820
upvote count: 2
has comment: http://stackoverflow.com/comment/91841185
answers question: http://stackoverflow.com/q/52345699
score: 2

http://stackoverflow.com/a/52354573
has comment: http://stackoverflow.com/comment/91655024
has body: You can stack all dataframe in one by using pd.concat wich axis = 1 and take average of respective column df3 = pd.merge(df1,df2,on=['wave'],how ='outer',) df4 = df3.rename(columns = lambda x: x.split('_')[0]).T df4.groupby(df4.index).mean().T Out: EWs MeasredWave fwhm num stlines wave 0 22.535720 4050.319374 0.074430 3.0 0.284425 4050.32 1 44.708220 4208.981496 0.086690 5.5 0.484515 4208.98 2 87.033245 4374.935812 0.114330 9.0 0.715155 4374.94 3 30.395310 4379.769305 0.091025 9.5 0.313710 4379.74 4 49.309715 4398.013920 0.092285 14.5 0.501825 4398.01 5 8.216850 5520.484742 0.125560 1.0 0.061480 5520.50 6 60.678680 4502.223123 0.101140 9.0 0.563620 4502.21 7 85.884280 4508.291777 0.116000 3.0 0.695540 4508.28 8 19.387450 4512.999332 0.088910 2.0 0.204860 4512.9
has comment: http://stackoverflow.com/comment/91655745
has comment: http://stackoverflow.com/comment/91655376
has comment: http://stackoverflow.com/comment/91655184
has comment: http://stackoverflow.com/comment/91655827
accepted answer of: http://stackoverflow.com/q/52354246
answers question: http://stackoverflow.com/q/52354246
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91654105
type: Answer
has comment: http://stackoverflow.com/comment/91660056
has comment: http://stackoverflow.com/comment/91655494
has comment: http://stackoverflow.com/comment/91654709
score: 1
has comment: http://stackoverflow.com/comment/91655432
upvote count: 1
has comment: http://stackoverflow.com/comment/91654343

http://stackoverflow.com/a/56773773
type: Answer
has body: you are using doc.paragraphs which just returns all the paragraphs in the document. To access tables and images you need to use Table and inline_shape objects. You can find them here in the official documentation. Tabels Shapes and images
answers question: http://stackoverflow.com/q/52306726
score: 0

http://stackoverflow.com/comment/91617912
has text: what have you tried so far...?
score: 3
comment on: http://stackoverflow.com/q/52335418
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91705566
has text: How is that string being created? It's not standard dictionary syntax and it's also not valid JSON
score: 0
comment on: http://stackoverflow.com/q/52380638
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52423656
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Big dataset contour plot using pyplot and pandas
has body: I have a massive data sample and need to visualize it. Using pandas, I can create a dataframe with relevant variables- 3 arrays of length 20Million. These are x,y geometrical coordinates and z value on that (x,y) point. I need a "heatmap" of z at each (x,y) point. But no pyplot function works with numbers this big. What is the best way to go about it?
score: 1
has comment: http://stackoverflow.com/comment/91790400
has comment: http://stackoverflow.com/comment/91792184
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52428295
has comment: http://stackoverflow.com/comment/91799432
tagged with: matplotlib
linked to: http://stackoverflow.com/q/6163334
tagged with: pandas
has comment: http://stackoverflow.com/comment/91812604

http://stackoverflow.com/comment/133617325
type: AnswerComment
comment on: http://stackoverflow.com/a/52389343
type: Comment
has text: how do you get the samplewidth of the returned dat?
score: 0

http://stackoverflow.com/q/52387273
type: Question
has comment: http://stackoverflow.com/comment/91719266
has comment: http://stackoverflow.com/comment/91719009
has comment: http://stackoverflow.com/comment/91719978
has comment: http://stackoverflow.com/comment/91718981
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/91719020
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52387668
type: UnansweredQuestion
has title: Count appearance of a value in a pandas row
tagged with: count
tagged with: python
has body: Hey I am currently iterating through a column in pandas. Now i want to handle the case that a value appears only once in that column different than when it appears multiple times. I tried several approaches but none worked. Right now I get the error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I just try to filter first all rows with the id i into df_path_counterand than i count it is rows in the if clause. I don't know why it does not work. Any ideas? This is my code: df_path = pd.DataFrame([(1, 'Germany'), (1, 'France'), (1, 'Indonesia'), (1, 'France'), (2, 'France'), (1, 'Germany'), (1, 'UK'), ], columns=['id', 'country'] for i, g in df_path.groupby('id'): df_path_counter=df_path.loc[df_path['id'] == i] if(df_path_counter.count()&lt;=1): #...do sth
tagged with: loops
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/54175392
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52395887
accepted answer of: http://stackoverflow.com/q/52395887
type: AcceptedAnswer
downvote count: 0
has body: In my case I just rewrite the escape method in class 'pymysql.connections.Connection', which obviously adds "'" arround your string. I don't know whether it is a bad idea, but there seems no better ways, if anyone knows, just let me know. Here's my code: from pymysql.connections import Connection, converters class MyConnect(Connection): def escape(self, obj, mapping=None): """Escape whatever value you pass to it. Non-standard, for internal use; do not use this in your applications. """ if isinstance(obj, str): return self.escape_string(obj) # by default, it is :return "'" + self.escape_string(obj) + "'" if isinstance(obj, (bytes, bytearray)): ret = self._quote_bytes(obj) if self._binary_prefix: ret = "_binary" + ret return ret return converters.escape_item(obj, self.charset, mapping=mapping) config = {'host':'', 'user':'', ...} conn = MyConnect(**config) cur = conn.cursor()
type: Answer

http://stackoverflow.com/q/52293548
tagged with: beautifulsoup
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52293701
has title: Extract text from HTML with beautifulSoup
tagged with: html-parsing
type: Question
has answer: http://stackoverflow.com/a/52293701
has body: I am trying to parse an html with beautiful soup 4 but unable to get the data A Show Film : Gladiator Location : example street, London, UK Phone : +83817447184 I am able to get the string "A Show" by using soup = BeautifulSoup(html, "html.parser") a_show = soup.find('b').get_text() How can I get values of strings Film, Location and Phone seperately?
score: 0
answer count: 1

http://stackoverflow.com/a/52316202
has comment: http://stackoverflow.com/comment/91583166
score: 6
answers question: http://stackoverflow.com/q/52316063
has body: You can use a list comprehension with f-strings (available in Python 3.6+): res = [f'{k} {w}' for k, v in data.items() for w in v] ['soft1 v1', 'soft1 v2', 'soft2 v1', 'soft2 v2', 'soft3 v1'] For earlier versions of Python you can use str.format: res = ['{0} {1}'.format(k, w) for k, v in data.items() for w in v] This will be more efficient as: Formatted string literals are more efficient than other methods of string concatenation. Extracting key-value pairs via dict.items is more efficient than iterating keys and accessing values separately. map + lambda with non built-in functions are less efficient than list comprehensions.
upvote count: 6
type: Answer
has comment: http://stackoverflow.com/comment/91583272
downvote count: 0

http://stackoverflow.com/a/52396084
downvote count: 0
has comment: http://stackoverflow.com/comment/91739194
type: Answer
answers question: http://stackoverflow.com/q/52396039
has body: You just have to iterate through the indices: l = [7, 5, 9, 4, 7, 11] res = [l[i] + l[i+1] for i in range(len(l)-1)] print(res) Output: [12, 14, 13, 11, 18]
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/91739125

http://stackoverflow.com/comment/91580729
comment on: http://stackoverflow.com/q/52316354
has text: You are probably using a python interpreter different from the one linked to pip.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52402519
has body: I have a function that connects to a database and fetches some data and returns this data. This entire process is surrounded by a try except finally block. In the finally block, I release the resources if they exist even in case of an error. So what is the pythonic way to do the following: def fetch_data(): db_conn = None try: db_conn = DBConnection() data = db_conn.get_data() except Exception as ex: print(f"Exception occurred when fetching data: {ex}") finally: if db_conn: db_conn.close() The initialization of db_conn = None and the finally block don't look elegant or pythonic enough and I was wondering if there was a better way of doing this?
has comment: http://stackoverflow.com/comment/91748813
type: Question
linked to: http://stackoverflow.com/q/39023423
has answer: http://stackoverflow.com/a/52402598
accepted answer: http://stackoverflow.com/a/52402598
has title: What is the pythonic way to use try/except/finally when having to release connections?
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91748847
tagged with: python
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: refactoring

http://stackoverflow.com/a/52347642
has body: Using lux.txt: ################################################## 2018-09-13_18-57-33_ ################################################## Lux no flash Code: content = [] with open('lux.txt', 'r') as f: for line in f: content.append(line.strip('\n')) for i in content: if 'Lux no flash' == i: print("Done") else: pass Better @pygo with open('lux.txt', 'r') as f: content = f.read() if 'Lux no flash' in content: print("Done") else: print("No else, this works :)") Output: (xenial)vash@localhost:~/python/stack_overflow$ python3.7 lux.py Done
accepted answer of: http://stackoverflow.com/q/52347148
type: Answer
answers question: http://stackoverflow.com/q/52347148
score: 2
downvote count: 0
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/91695906
comment on: http://stackoverflow.com/a/52375474
score: 0
type: AnswerComment
has text: Thanks!! Also, is there a connection between `np.random.seed` and `random.seed`?
type: Comment

http://stackoverflow.com/q/52315920
has body: I have a test output csv that looks like the following; test1 test success test2 test failed regtest failed to build column 1 contains unique strings and column 2 contains one of the following three strings; test success, test failed, failed to build. I run this test every so often on new builds and I want to compare the csv from the latest test with the previous test. I would like to produce a new csv containing all the tests whose state(column 2) has changed. Preferably in the format of; TestName OldState NewState Here is my current attempt which gets all the differences between the two files but it looks like this; test1 test success test2 test failed regtest failed to build test2 test success I need a way to merge the second test2 with the first one so it looks like this; test1 test success test2 test failed test success regtest failed to build My current code; import csv import sys with open(sys.argv[1], 'r') as t1, open(sys.argv[2], 'r') as t2, open(sys.argv[2], 'r') as t3, open(sys.argv[1], 'r') as t4: fileOne = t1.readlines() fileTwo = t2.readlines() fileThree = t3.readlines() fileFour = t4.readlines() with open(sys.argv[3], 'w') as outFile: for line in fileTwo: if line not in fileOne: outFile.write("From File 2," + line) for line in fileFour: if line not in fileThree: outFile.write("\r\nFrom File 1," + line)
has comment: http://stackoverflow.com/comment/91581722
type: Question
answer count: 1
has title: merging and removing duplicates in two csv's without using pandas
score: 0
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/52316923
accepted answer: http://stackoverflow.com/a/52316923
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/52395525
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52395174
has body: There is the ~ (tilde) in standard cross-referencing syntax. If you prefix the content with ~, the link text will only be the last component of the target. For example, :py:meth:`~Queue.Queue.get` will refer to Queue.Queue.get but only display get as the link text. This does not work with all cross-reference roles, but is domain specific. There is also the directive .. currentmodule:: with some documentation and an example in another SO answer.
answers question: http://stackoverflow.com/q/52395174
score: 12
upvote count: 12
type: AcceptedAnswer

apache
tag name: apache
tags question: http://stackoverflow.com/q/52357753
tags question: http://stackoverflow.com/q/52284749
tags question: http://stackoverflow.com/q/52300222
type: Tag
tags question: http://stackoverflow.com/q/52319053

http://stackoverflow.com/a/52338663
type: Answer
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/52338163
has body: Try this code: import sys def func1(isCold, isRainy): s = '' if isCold: s = s + 'cold and ' else: s = s + 'warm and ' if isRainy: s = s + 'rainy' else: s = s + 'dry' print(s) isCold= sys.argv[1] == 'True' isRainy= sys.argv[2] == 'True' func1(isCold, isRainy) Then, run it by using the following command in your linux terminal: python3 your_file_name.py False True Or if you are a Windows user: your_file_name.py False True

http://stackoverflow.com/a/52292785
has body: Use Style Sheet Syntax from PyQt5 import QtCore, QtWidgets StyleSheet = ''' QPushButton#BlueButton { background-color: #2196f3; /* Ограничьте минимальный размер */ min-width: 96px; max-width: 96px; min-height: 96px; max-height: 96px; border-radius: 48px; /* круглый */ } QPushButton#BlueButton:hover { background-color: #64b5f6; color: #fff; } QPushButton#BlueButton:pressed { background-color: #bbdefb; } ''' class Window2(QtWidgets.QDialog): def __init__(self, value, parent=None): super().__init__(parent) self.setGeometry(750, 100, 300, 300) self.parent = parent self.setWindowTitle('Window2') self.setWindowIcon(self.style().standardIcon(QtWidgets.QStyle.SP_FileDialogInfoView)) label1 = QtWidgets.QLabel(value) self.button = QtWidgets.QPushButton() self.button.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.button.setIcon(self.style().standardIcon(QtWidgets.QStyle.SP_ArrowLeft)) self.button.setIconSize(QtCore.QSize(200, 200)) layoutV = QtWidgets.QVBoxLayout() self.pushButton = QtWidgets.QPushButton(self) self.pushButton.setStyleSheet('background-color: rgb(0,0,255); color: #fff') self.pushButton.setText('Click me!') self.pushButton.clicked.connect(self.goMainWindow) layoutV.addWidget(self.pushButton) layoutH = QtWidgets.QHBoxLayout() layoutH.addWidget(label1) layoutH.addWidget(self.button) layoutV.addLayout(layoutH) self.setLayout(layoutV) def goMainWindow(self): self.parent.show() self.close() class Widget(QtWidgets.QWidget): def __init__(self, parent=None): super(Widget, self).__init__(parent) self.setGeometry(400, 100, 300, 300) hlay = QtWidgets.QHBoxLayout() hlay.addStretch(1) vlay = QtWidgets.QVBoxLayout(self) vlay.addStretch(1) self.btn = QtWidgets.QPushButton("Press me", objectName="BlueButton") self.btn.clicked.connect(self.btn_onClick) self.btn.installEventFilter(self) hlay.addWidget(self.btn) hlay.addStretch(1) vlay.addLayout(hlay) self.lineEdit = QtWidgets.QLineEdit("Type here what you want to transfer for [Window2].") vlay.…
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52291734
answers question: http://stackoverflow.com/q/52291734
type: Answer
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/91533992
has comment: http://stackoverflow.com/comment/91535058
has comment: http://stackoverflow.com/comment/91536721
score: 4
has comment: http://stackoverflow.com/comment/91536185

http://stackoverflow.com/a/52378971
answers question: http://stackoverflow.com/q/52378147
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52378147
has body: You can use the parameter: seaborn.barplot color: matplotlib color, optional Color for all of the elements, or seed for a gradient palette. Used for visualization the sample example: Horizontal bar plots Here is an example without color so result is "rainbow": import seaborn as sns import matplotlib.pyplot as plt sns.set(style="whitegrid") # Initialize the matplotlib figure f, ax = plt.subplots(figsize=(6, 15)) # Load the example car crash dataset crashes = sns.load_dataset("car_crashes").sort_values("total", ascending=False) # Plot the crashes where alcohol was involved sns.set_color_codes("muted") sns.barplot(x="alcohol", y="abbrev", data=crashes, label="Alcohol-involved", orient = "h") Now we specify the color='b' #blue: import seaborn as sns import matplotlib.pyplot as plt sns.set(style="whitegrid") # Initialize the matplotlib figure f, ax = plt.subplots(figsize=(6, 15)) # Load the example car crash dataset crashes = sns.load_dataset("car_crashes").sort_values("total", ascending=False) # Plot the crashes where alcohol was involved sns.set_color_codes("muted") sns.barplot(x="alcohol", y="abbrev", data=crashes, label="Alcohol-involved", orient = "h", color='b')
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91678651
comment on: http://stackoverflow.com/q/52366219
type: Comment
type: QuestionComment
score: 1
has text: Hi @zhangwei da, can you add some sample data. I think this can be sped up significantly using basic Pandas functions like DataFrame.sum and DataFrame.mean but cannot figure it out without some data.

http://stackoverflow.com/comment/91635410
score: 0
type: Comment
type: QuestionComment
has text: can you post your code ??
comment on: http://stackoverflow.com/q/52322039

http://stackoverflow.com/comment/91577993
score: 0
type: QuestionComment
has text: len(naive(p,t) works when t has a defined text. But if I am calling t from a file placed in directory it does not work. any suggestions
comment on: http://stackoverflow.com/q/52315002
type: Comment

http://stackoverflow.com/comment/91736233
type: Comment
comment on: http://stackoverflow.com/q/52395499
score: 0
type: QuestionComment
has text: I tried that and still didn't work.

http://stackoverflow.com/a/52370584
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/52370489
has body: Using diff find the whether it continue or not (equal to 1 ), then cumsum with the condition match , then we using groupby + transform szie s=df.time.diff().fillna(1).ne(1).cumsum() s.groupby(s).transform('size') Out[396]: 0 3 1 3 2 3 3 2 4 2 5 1 6 1 Name: time, dtype: int32
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/91686775

http://stackoverflow.com/comment/91773576
score: 0
comment on: http://stackoverflow.com/a/52327211
type: AnswerComment
has text: @ Poolka Can you help me with this one?? https://stackoverflow.com/questions/52413152/how-can-i-make-my-program-to-use-multiple-cores-of-my-system-in-python?noredirect=1
type: Comment

http://stackoverflow.com/a/52331989
answers question: http://stackoverflow.com/q/52331595
score: 0
has body: I will post it as a answer then : You can instantly unpack the kwargs values to the format function like this : "Your name is {} {} {}".format(first_name , *kwargs) But as a User @PM 2Ring mentioned You must be aware that doesn't guarantee that the names will be in the correct order.
type: Answer

http://stackoverflow.com/a/52314835
upvote count: 6
type: AcceptedAnswer
score: 6
type: Answer
accepted answer of: http://stackoverflow.com/q/52314599
answers question: http://stackoverflow.com/q/52314599
downvote count: 0
has body: You are setting the x and y tick labels of the axis you have just created. You are then plotting the seaborn heatmap which will overwrite the tick labels you have just set. The solution is to create the heatmap first, then set the tick labels: fig, ax = plt.subplots(figsize=(13,10)) sns.heatmap(jr_matrix, center=0, cmap="vlag", linewidths=.75, ax=ax, norm=LogNorm(vmin=jr_matrix.min(), vmax=jr_matrix.max())) # passing a list is fine, no need to convert to tuples ax.set_xticklabels(short_cols) ax.set_yticklabels(short_cols)

neural-network
tags question: http://stackoverflow.com/q/52273542
tags question: http://stackoverflow.com/q/52355145
tags question: http://stackoverflow.com/q/52405276
tags question: http://stackoverflow.com/q/52285501
tags question: http://stackoverflow.com/q/52411346
tags question: http://stackoverflow.com/q/52423501
tags question: http://stackoverflow.com/q/52326469
tags question: http://stackoverflow.com/q/52426885
tags question: http://stackoverflow.com/q/52281037
tags question: http://stackoverflow.com/q/52279355
tags question: http://stackoverflow.com/q/52284979
tags question: http://stackoverflow.com/q/52391757
tags question: http://stackoverflow.com/q/52305618
tags question: http://stackoverflow.com/q/52330532
tags question: http://stackoverflow.com/q/52293537
tags question: http://stackoverflow.com/q/52310905
tags question: http://stackoverflow.com/q/52362842
tags question: http://stackoverflow.com/q/52418749
type: Tag
tags question: http://stackoverflow.com/q/52417056
tags question: http://stackoverflow.com/q/52349169
tags question: http://stackoverflow.com/q/52366819
tags question: http://stackoverflow.com/q/52320059
tags question: http://stackoverflow.com/q/52425824
tags question: http://stackoverflow.com/q/52347906
tags question: http://stackoverflow.com/q/52390397
tags question: http://stackoverflow.com/q/52411530
tags question: http://stackoverflow.com/q/52360546
tags question: http://stackoverflow.com/q/52344570
tags question: http://stackoverflow.com/q/52358505
tags question: http://stackoverflow.com/q/52399923
tags question: http://stackoverflow.com/q/52398936
tag name: neural-network
tags question: http://stackoverflow.com/q/52402822
tags question: http://stackoverflow.com/q/52373318

http://stackoverflow.com/comment/91645392
type: QuestionComment
type: Comment
has text: @jmunsch I should be able to acheive what I'm looking to acheive using a queryset on the result model. However, within the template the code would be extremely unmanageable. If I'm able to create the dataset as I'd like then it would be two simple for loops. I've also added an image here to try and explain what I'm trying to acheive (Warning: Created in MS Paint): https://i.imgur.com/s14snwZ.png
score: 0
comment on: http://stackoverflow.com/q/52349811

http://stackoverflow.com/a/52383337
type: Answer
accepted answer of: http://stackoverflow.com/q/52383129
upvote count: 6
has comment: http://stackoverflow.com/comment/91711309
answers question: http://stackoverflow.com/q/52383129
has comment: http://stackoverflow.com/comment/91711774
score: 6
has body: Try the logspace from NumPy as plt.yticks(numpy.logspace(3, 15, 13)) Here you give the starting and the last exponent (powers of 10) and the number of data-points in between. If you print the above mesh, you get the following array([1.e+03, 1.e+04, 1.e+05, 1.e+06, 1.e+07, 1.e+08, 1.e+09, 1.e+10, 1.e+11, 1.e+12, 1.e+13, 1.e+14, 1.e+15])
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91711047
has comment: http://stackoverflow.com/comment/91711121

http://stackoverflow.com/a/52398376
answers question: http://stackoverflow.com/q/52396055
score: 0
type: Answer
has body: As per the HTML the element seems to be JavaScript based so you need to induce WebDriverWait and can use either of the following solutions: Using PARTIAL_LINK_TEXT: WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "もっと見る"))).click() Using XPATH: WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(.,'もっと見る')]"))).click() Note : You have to add the following imports : from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC

http://stackoverflow.com/comment/91534196
score: 0
has text: sounds like you could do this with a dict
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52293173

http://stackoverflow.com/comment/91775722
score: 0
comment on: http://stackoverflow.com/q/52416068
type: Comment
type: QuestionComment
has text: does this help? https://stackoverflow.com/questions/8802860/checking-whether-a-string-starts-with-xxxx

http://stackoverflow.com/comment/91850522
score: 0
comment on: http://stackoverflow.com/q/52416472
type: Comment
type: QuestionComment
has text: Is the `blockchain.stream()` call also blocking, or just the `post.refresh()`? Also, `map(blockchain.stream(...))` looks incorrect - `map` takes at least two arguments.

http://stackoverflow.com/q/52370112
tagged with: for-loop
has comment: http://stackoverflow.com/comment/91697659
has title: Error: setting an array element with a sequence
score: 0
tagged with: matrix
tagged with: python
has comment: http://stackoverflow.com/comment/91684925
answer count: 0
type: UnansweredQuestion
has body: When I run the following code, in order to initializing a bidimensional matrix: X_train_word2vec = np.array(X_train_word2vec) train_x = np.zeros([X_train_word2vec.shape[0], 150]) for i, sentence in enumerate(X_train_word2vec): for j, word in enumerate(sentence): train_x[i,j] = model_word2vec.wv[word] Where X_train_word2vec has shape (12481,), and train_x has shape (12481, 150). I get this error: ValueError: setting an array element with a sequence. Why? I suppose that there is something wrong about the shape of the arrays, but I'm not sure. Update: The traceback --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-7-bbd0ab46f676&gt; in &lt;module&gt;() 4 for i, sentence in enumerate(X_train_word2vec): 5 for j, word in enumerate(sentence): ----&gt; 6 train_x[i,j] = model_word2vec.wv[word] ValueError: setting an array element with a sequence. Update 2: I have found that the problem regards the assignment of an array as an element of train_x matrix, because it seems that we can assign only int or float as elements of a matrix.
type: Question

http://stackoverflow.com/q/52426355
tagged with: python-chess
has answer: http://stackoverflow.com/a/52427251
type: Question
accepted answer: http://stackoverflow.com/a/52427251
type: AnsweredQuestion
has body: Hello i recently started studying tkinter and decided to pick up chess board game. Below is my code: import tkinter as tk class GameBoard(tk.Frame): def __init__(self, parent, rows=8, columns=8, size=70, color1="white", color2="blue"): '''size is the size of a square, in pixels''' self.rows = rows self.columns = columns self.size = size self.color1 = color1 self.color2 = color2 self.pieces = {} canvas_width = columns * size canvas_height = rows * size tk.Frame.__init__(self, parent) self.canvas = tk.Canvas(self, borderwidth=0, highlightthickness=0, width=canvas_width, height=canvas_height, background="bisque") self.canvas.pack(side="top", fill="both", expand=True, padx=2, pady=2) root = tk.Tk() board = GameBoard(root) board.pack(side="top", fill="both", expand="true", padx=4, pady=4) black_rook_l = tk.PhotoImage(file=black_rook_img) black_rook_l = black_rook_l.subsample(2, 2) board.addpiece("black_rook_l", black_rook_l, 0,0) above code i is to add piece (black rook) to the board, which is working as expected. below is the helper functions: def addpiece(self, name, image, row=0, column=0): '''Add a piece to the playing board''' self.canvas.create_image(0,0, image=image, tags=(name, "piece"), anchor="c") self.placepiece(name, row, column) def placepiece(self, name, row, column): '''Place a piece at the given row/column''' self.pieces[name] = (row, column) x0 = (column * self.size) + int(self.size/2) y0 = (row * self.size) + int(self.size/2) # print(name, x0, y0) self.canvas.coords(name, x0, y0) But problem occurs when i try to place pawns with help of for loop. Below is the code: for i in range(8): bname = tk.PhotoImage(file=black_pawn_img) bname = bname.subsample(2, 2) board.addpiece("black_pawn_"+str(i), bname, 1,i) root.mainloop() it is placing only last Pawn piece. Please suggest/help me understand the issue. Thanks in advance.
has comment: http://stackoverflow.com/comment/91797193
tagged with: tkinter-canvas
answer count: 1
has comment: http://stackoverflow.com/comment/91797701
favorite count: 0
upvote count: 3
has title: python canvas create image in loop
downvote count: 1
tagged with: python
score: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91797393
tagged with: tkinter
has comment: http://stackoverflow.com/comment/91796015

http://stackoverflow.com/comment/91682443
type: QuestionComment
has text: Please post a proper MCVE, and make sure your code is correctly indented (in Python indentation is part of the language so a badly indented code is just garbage).
score: 0
comment on: http://stackoverflow.com/q/52368964
type: Comment

http://stackoverflow.com/comment/91723383
score: 0
comment on: http://stackoverflow.com/q/52316930
has text: Well I checked to see if `interpreterInfo.py` was in that location and it was not. I copied it from another instillation of Eclipse on a different PC and it worked. Thanks for the help.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91563133
has text: Of course, data has to be loaded somewhere. Note that this question is vague, as there is no detail as to which model, GPU, etc. It varies with model size.
type: QuestionComment
comment on: http://stackoverflow.com/q/52307460
type: Comment
score: 0

http://stackoverflow.com/a/52298904
has comment: http://stackoverflow.com/comment/91546137
has comment: http://stackoverflow.com/comment/91564412
answers question: http://stackoverflow.com/q/52290122
has comment: http://stackoverflow.com/comment/91546438
upvote count: 1
type: Answer
has body: The app.yaml file is only used for your application when deployed on App Engine. It specifies some configuration for your deployed app only. So by defining: libraries: - name: MySQLdb version: "latest" it basically instructs the App Engine platform to use that built-in library on the instance to run your code. Now, as explained here, on your local machine for development, you need to install the library yourself. You can do that by running: pip install MySQL-python Note that you don't have to install this library also in the lib folder. This is needed only if the library isn't listed in the Built-in Third-party Libraries so that the library is uploaded along with your app when you deploy it. If it is in the list then referencing it in the app.yaml file is enough. One last thing about the Cloud Shell. It is a small VM instance provided to you to ease resource management or testing. It isn't meant for development. Every time it starts up a default image is installed (thus any library or OS level tool you installed will be lost). Only your home folder is copied over. Some useful tools are installed by default though on the image like gcloud.
downvote count: 0
score: 1

http://stackoverflow.com/comment/91666790
has text: I see. For Python 2.7 you would have specify `u` for string literals that contain Unicode characters. I've updated my answer accordingly.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52360403

http://stackoverflow.com/a/52325231
has body: you can copy a file via the command line on windows: open cmd.exe then type cd "C:\ ..." then type copy yourfile destination. more info here you can make python do this for you: you will need the subprocess module which comes integrated into python so you dont have to donwload anything. like this: import subprocess subprocess.run('copy yourfile destionation') remember that for this to work your python script should be in the same folder as "yourfile", why? because i type "yourfile" as a relative path relative vs absolute path subprocess works for python 3.3 and newer versions so another way to do it would be: import os os.system('copy youfile destionation') to open specific documents with python take a quick look at here: https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
score: 0
answers question: http://stackoverflow.com/q/52324838
type: Answer

http://stackoverflow.com/comment/91703813
type: QuestionComment
comment on: http://stackoverflow.com/q/52379760
has text: If you are not seeing anything on the console it may mean that you haven't set up port forwarding correctly contrary to what you think.
score: 0
type: Comment

http://stackoverflow.com/comment/91803188
comment on: http://stackoverflow.com/q/52429696
has text: please can you add the file to your question. This will help others in future.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52318992
tagged with: code-completion
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/52337169
has title: How to enable code completion for a dictionary from method in Python?
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/76773653
accepted answer: http://stackoverflow.com/a/76773653
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91585822
tagged with: pycharm
has body: I am using Python 3.6 with PyCharm and it's kind of frustrating that there's no support for code completion for special cases of dictionary objects (with fixed key schema). Say for example I create and try to access a simple dictionary object like this: inventory = {'name': 'hammer', 'price': 2.3} inventory[''] When I position my cursor inside the quotes ' ' and hit Ctrl + Space i get code completion and the IDE correctly suggests all the possible keys in the dictionary object. That's great! But if i try to build it as a utility function that returns this same dict object, say with values that the user provide but with the same dict keys - then I don't get code completion anymore! def get_inventory(name: str, price: float): return {'name': name, 'price': price} inventory = get_inventory('hammer', 2.3) inventory[''] # &lt;- Pycharm can't offer any suggestions! Any workaround or solution for this? I searched already for similar solutions but I didn't find anything that works. I know I can just convert it into a class Inventory and access the properties that way but I don't want to do it for a couple of reasons: I need the object to be easily JSON convertable since i might pass it from / to JSON a lot and dict objects are the easiest for this purpose storing it as a class wouldn't make much sense since i just need it as a data container anyway, with minimal properties stored within it Any help or solution for how I can get my IDE to assist in code completion by recognizing the possible keys in such a dict object would be greatly appreciated!
has comment: http://stackoverflow.com/comment/91588700
score: 7
has answer: http://stackoverflow.com/a/52337169
upvote count: 7
has comment: http://stackoverflow.com/comment/91594786
has comment: http://stackoverflow.com/comment/91585979
type: Question
linked to: http://stackoverflow.com/q/15022804
tagged with: autocomplete

http://stackoverflow.com/a/52349335
accepted answer of: http://stackoverflow.com/q/52349227
answers question: http://stackoverflow.com/q/52349227
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: The date column seems to be unsorted. To reproduce consider e.g. import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame(np.random.rand(15,5), columns=list("ABCDE")) a = np.arange("2018-05-05", "2018-05-20", dtype="datetime64[D]") np.random.shuffle(a) df["date"] = a plt.plot("date", "C", data=df) plt.show() If we sort the dataframe by the date column now, df.sort_values(by="date", inplace=True) the result looks much nicer. A tangential remark here: I would recommend deciding for one style, either plt.plot("date", "C", data=df) or plt.plot(df["date"], df["C"]) and not mix the two by supplying the x argument as Series and the y as string.
type: Answer

http://stackoverflow.com/comment/91771532
comment on: http://stackoverflow.com/q/52413881
has text: yep the comprehension is an idomatic way
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52273742
type: UnansweredQuestion
tagged with: python
has title: If i search our web service on google, It seems that Google only brings meta data which is Korean. How can I apply meta data by language
type: Question
tagged with: javascript
tagged with: flask
has body: I’m developing web service using python/flask. My web service is consisted of 3 languages, which are English,Thai and Korean. By analyzing client ip of connecting time, we are rendering templates and static files that are made of relevant region. I confirmed that if someone access our service bypassing proxy ip, it shows the page corresponding region. However, If i search our web service on google, It seems that Google only brings meta data which is Korean. How can I apply meta data by language.
has comment: http://stackoverflow.com/comment/91494809
score: 0
has comment: http://stackoverflow.com/comment/91494882
tagged with: meta-tags
answer count: 0

zen-of-python
tags question: http://stackoverflow.com/q/52370575
tag name: zen-of-python
type: Tag

http://stackoverflow.com/comment/91529118
has text: no I dont use lstm_shape anywhere else other than main_inputs. where else do I need to use it? the error seems to say that the problem is in main_input...
comment on: http://stackoverflow.com/a/52289843
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91528343
type: Comment
has text: That's the path for linux. perhaps these question can help? https://stackoverflow.com/questions/45707756/linter-flake8-and-atom-windows-10-path-to-cmd-exe
type: QuestionComment
comment on: http://stackoverflow.com/q/52289061
score: 0

http://stackoverflow.com/comment/91783076
score: 2
comment on: http://stackoverflow.com/q/52419395
has text: Agreed, but admittedly, you wrap your `os.remove` call in a function as well :)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52300478
downvote count: 0
has comment: http://stackoverflow.com/comment/91572967
has body: The Python library development files need to be installed to compile extensions from source. Do you have libpython-dev installed ? apt-get install libpython-dev
score: 1
has comment: http://stackoverflow.com/comment/91551625
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52300429

http://stackoverflow.com/a/52321032
answers question: http://stackoverflow.com/q/52320850
upvote count: 1
has body: The sum of your for loop is simply the variable salary after the for loop has finished. Check your math though. That 2 seems off. EDIT: Based on your commments, just make use of your variable totalPay in the for loop: num_days_worked = int(input("Enter the amount of days worked: \n")) salary = 0.01 total_pay = 0.00 print( "Day\tSalary\n---\t----" ) for current_day in range(num_days_worked): salary += 2 * salary print (current_day + 1, "\t", salary) total_pay += salary Make sure to explain your questions better next time, there are a bunch of different results around here because of that!
has comment: http://stackoverflow.com/comment/91589585
downvote count: 0
has comment: http://stackoverflow.com/comment/91589618
type: Answer
score: 1

http://stackoverflow.com/comment/91571785
comment on: http://stackoverflow.com/q/52308367
type: Comment
type: QuestionComment
has text: But you probably mean that it's unfortunate that there is not a package-wide setting for future directives (and only those), as that would near-instantly make a package Python 2/3 compatible. I can agree with that sentiment, and I guess it's part of how modules have grown into packages over time; bit of a historical artefact perhaps, even if `from future` is not that old.
score: 0

http://stackoverflow.com/a/52363211
score: 1
answers question: http://stackoverflow.com/q/52361941
has comment: http://stackoverflow.com/comment/91671704
downvote count: 0
has body: I solved it thank you all def search_mahmoud_friends(self): if self.conn: c = self.conn.cursor() try: sql = '''SELECT * FROM ahmed WHERE mth_search = %s''' mth_search = self.lineEdit_3.text() c.execute(sql, [(mth_search)]) data = c.fetchall() for row in data : print(row) except mysql.connector.Error as err: print("Error: ", err)
type: Answer
upvote count: 1

http://stackoverflow.com/comment/91685107
has text: Note that your query should be equivalent to `Balance.objects.exclude(fax_date=F('paused_date'))`, no need for Q at all.
score: 1
comment on: http://stackoverflow.com/q/52369312
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91742027
has text: @uakfb `links = filter(lambda x: 'href' in x, links)` got nothing.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52398767
type: Comment

http://stackoverflow.com/comment/91681584
type: QuestionComment
type: Comment
has text: hey could you give us an example from the output of script and terminal?
comment on: http://stackoverflow.com/q/52368631
score: 0

http://stackoverflow.com/comment/91564315
type: Comment
type: QuestionComment
score: 0
has text: `src="https://websitewithdetailsD&amp;width=194&amp;height=284&amp;lat=18.111&amp;lon=98.111&amp;level=15&amp;returnImage=true"` parse_qs can't detect the url because it has no tld like .com .net .
comment on: http://stackoverflow.com/q/52308329

http://stackoverflow.com/comment/91707810
score: 0
comment on: http://stackoverflow.com/q/52362195
type: QuestionComment
type: Comment
has text: @Alvin My point was **not** to use this inside your module, but to define your dependency for when your module is installed. You have created a non-standard, difficult to maintain "solution" to fix a problem that does not exist!

http://stackoverflow.com/comment/91541148
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52296600
has text: You want to put the parts where you ask for input in a loop (basically the whole thing except where you declare the variables).

http://stackoverflow.com/comment/91718964
comment on: http://stackoverflow.com/q/52387191
type: Comment
type: QuestionComment
has text: @Denziloe always with this file
score: 0

http://stackoverflow.com/comment/91630779
type: QuestionComment
has text: Your code works just fine for me.
score: 0
comment on: http://stackoverflow.com/q/52342124
type: Comment

http://stackoverflow.com/comment/91756133
comment on: http://stackoverflow.com/a/52404983
has text: @AmitYadav: Just parse the time and discard all the records which are too old.
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/a/52273354
downvote count: 0
has comment: http://stackoverflow.com/comment/91494556
upvote count: 2
type: Answer
score: 2
has body: element = driver.find_element_by_xpath("//select[@class='m-tcol-c' and @id='searchBy']") Here, element is a web element. and in this call: driver.execute_script("arguments[0].removeAttribute('style')", element) You are passing element(Which is a web element) as a arguments[0] removeAttribute('style') must be a method in JS. and using arguments[0] you are invoking this method.
answers question: http://stackoverflow.com/q/52273298

http://stackoverflow.com/comment/91507104
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52278799
score: 0
has text: Did it. And thanks for your answer!

http://stackoverflow.com/comment/91604590
type: Comment
comment on: http://stackoverflow.com/a/52328230
score: 0
has text: still generates same error mentioned in the question.
type: AnswerComment

http://stackoverflow.com/q/52358107
type: Question
accepted answer: http://stackoverflow.com/a/52459980
has body: I'm currently working with a remote Jupyter notebook (through a docker image), and am having an issue with finding a folder that exists in the directory (where I'm running the notebook) but doesn't exist in the notebook tree. Command I'm using to execute the notebook: nvidia-docker run -it -p 8888:8888 --entrypoint /usr/local/bin/jupyter NAMEOFDOCKERIMAGE notebook --allow-root --ip=0.0.0.0 --no-browser Command I'm using to access the notebook remotely: ssh -N -f -L localhost:8888:localhost:8888 remote_user@remote_host What's weird is that if I navigate to the notebook's working directory (on the remote host / server) and add a folder + files, the notebook will not reflect the changes (i.e. mkdir new_folder in the working directory will not add new_folder to the notebook's tree). Would anyone know why this could be the case, and if so, how to "refresh" / "update" the tree? Thanks so much for all and any help!
tagged with: ubuntu
tagged with: docker
has title: Remote Jupyter Notebook + Docker -- Doesn't Update File Directory?
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52459980
tagged with: python
score: 13
upvote count: 13
tagged with: jupyter-notebook
type: AnsweredQuestion

http://stackoverflow.com/comment/91657464
comment on: http://stackoverflow.com/q/52356473
score: 5
type: QuestionComment
has text: Would you care to share your attempt at the problem? That way you are more likely to obtain answers
type: Comment

http://stackoverflow.com/a/52387589
score: 0
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/91719880
answers question: http://stackoverflow.com/q/52387118
has body: You can define custom input fields with HTML or Bootstrap, as long as you let Django know, which input field in your forms.py you mean. You do this by specifying the proper id to the HTML input field. For example, if you have a form which takes a DateField in your forms.py: from django import forms class YourForm(forms.Form): some_date = forms.DateField() # ... more stuff Then, your proper id for the input would be id='id_some_date'. (And name would be name='some_date'.) EDIT: In your case, you can try id='{{ form.date.id_for_label }}', so you do not need to hardcode the id. When the template is rendered, {{ form.date }} would render to the HTML input form, which is the form you specified in forms.py.
accepted answer of: http://stackoverflow.com/q/52387118

http://stackoverflow.com/comment/91614124
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52330119
has text: Thanks. That seems to be the problem, the db.generate_mapping() gave me the headache. Placed the db variable and db binding call in a module together with the entities and put the mapping call at the end of the module. Had the hard time looking for the answer because I had the difficulty looking for sample code that separates entity definition from the application logic.

http://stackoverflow.com/comment/91604473
comment on: http://stackoverflow.com/q/52319485
type: Comment
has text: Thank you. My problem is that I want to find the right config file matched to these tensorflow models **"mobilenet_v1_0.5_128" / "mobilenet_v1_1.0_224"** so that I can use them to train my custom model
score: 0
type: QuestionComment

http://stackoverflow.com/q/52274720
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/35612666
has answer: http://stackoverflow.com/a/52274783
accepted answer: http://stackoverflow.com/a/52274783
type: Question
has comment: http://stackoverflow.com/comment/91496815
answer count: 1
has title: Appending item to a list within dictionary without checking if the key exists
has comment: http://stackoverflow.com/comment/91496783
score: 0
has body: Currently, in order to do what I'm describing, I have a code like this: if key in dict: dict[key].append(item) else: dict[key] = [item] Is there any way I can append to list within dictionary without doing the explicit check? Can this be done using another data structure? What I need to do is to track all the items that have some parameter equal.
has comment: http://stackoverflow.com/comment/91496819
tagged with: python
tagged with: dictionary
duplicate of: http://stackoverflow.com/q/35612666
tagged with: python-3.x

http://stackoverflow.com/q/52319008
answer count: 1
has answer: http://stackoverflow.com/a/52319561
has title: parsing quote and escape characters CSV file
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: I need to Import large sets of data into SQL, the output file (text) is UTC-8 generated from an ABAP program where I can define the quote and escape characters , by default I'm using : \ as escape string " ( double quote) to quote characters ; (semi Colon) to separate the columns. My problem resides that most of the columns which type is text contains double quotes or escape characters and when trying to import this into SQL database the interface fails because of data wrong allocation of the columns. I manage to avoid the \n with below python scrip but I'm struggling with the Double quotes, Can you suggest any idea to replace the double quotes inside the quoting characters? Text fields like = banana from "Ecuador" its causing me a big mess since the data on the CSV file is stored as "banana from "Ecuador"" import csv filename = "0180914_074626.csv" with open(filename, 'r', encoding='utf8', errors='ignore') as inputfile, \ open(filename + '.log.csv', 'w', encoding="utf8") as outputfile_log: w = csv.writer(outputfile_log, delimiter=';', quotechar='"', lineterminator='\n') for record in csv.reader(inputfile): #print(record) w.writerow(tuple(s.replace("\n", '-') for s in record))
tagged with: text
score: 1
tagged with: import
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/91585484
tagged with: http://stackoverflow.com/tag/csv
upvote count: 1

http://stackoverflow.com/comment/91723362
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52389105
has text: Yes, that is, indeed, correct.

http://stackoverflow.com/q/52326242
upvote count: 0
type: UnansweredQuestion
has title: Why the outputs of a value in Jupiter sometime is correct, and some times not?
has body: I have written a code which was calculating a measure correctly for a specific data correctly. But after some time, some of the values are not shown correctly. The generated measure is between 0 and 1 (which was 0.8998 for few times of running); however, it shows -4.486000218950312e+183 value for the same data, which somethin irrelevant and generated by machine. Calculating Dice score by using medpy library: import medpy.metric.binary as metrics mean_dsc=np.ndarray(no_slices,dtype=float) for i in range(no_slices) segm=res_vol[:,:,i] gt=lbl[:,:,i] mean_dsc[i]=metrics.dc(segm, gt) print mean_dsc What is the reason for this? Is there any bug with jupyter or python? How can i resolve this issue? your help is appreciated
type: Question
score: -2
has answer: http://stackoverflow.com/a/52329421
tagged with: python-2.7
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/91599445
favorite count: 0
has comment: http://stackoverflow.com/comment/91599770
tagged with: python
tagged with: jupyter
tagged with: jupyter-notebook

http://stackoverflow.com/a/52349614
accepted answer of: http://stackoverflow.com/q/52349592
type: Answer
has comment: http://stackoverflow.com/comment/91645323
upvote count: 1
score: 1
has body: Division need's int, so: import sys x = input("How many days?") if x.isdigit(): x=int(x) else: print('non-numeric day') sys.exit() ... It's python 3 not python 2 anymore, so input from python 2 is removed and raw_input is renamed to input Btw at the end: print(f"{x} days is equivalent to {x/w} weeks.")
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52349592
has comment: http://stackoverflow.com/comment/91645353

http://stackoverflow.com/a/52275426
has comment: http://stackoverflow.com/comment/91501270
score: 1
has comment: http://stackoverflow.com/comment/91501356
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52273054
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52273054
has body: You have a - character in your input, together with the preceding and following characters that creates a range expression (where all codepoints between the first and second are all matched too): &gt;&gt;&gt; print(letters[195:198]) [u'\u0127', u'-', u'\xb2'] Because U+0127 is actually a later codepoint than U+00B2, that causes the exception: &gt;&gt;&gt; re.compile("[" + "".join(letters[195:198]) + "]+") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/re.py", line 194, in compile return _compile(pattern, flags) File "/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/re.py", line 251, in _compile raise error, v # invalid expression sre_constants.error: bad character range I found this section by bisecting letters into smaller subsets (halving the list each time) until I had the smallest list that would still produce it. You probably want to escape dashes rather than have them be interpreted as ranges. You'll need to escape any backslashes and ] characters too, for the same reasons; those have special meaning in sets too: setmeta = {u'\\': u'\\\\', u'-': u'\\-', u']': u'\\]'} regex = re.compile("[" + "".join([setmeta.get(l, l) for l in letters]) + "]+") With those metacharacters escaped, your letters list can be turned into a regex: &gt;&gt;&gt; re.compile("[" + "".join([setmeta.get(l, l) for l in letters]) + "]+") &lt;_sre.SRE_Pattern object at 0x7f8442503740&gt;

azure-iot-hub
type: Tag
tags question: http://stackoverflow.com/q/52398769
tag name: azure-iot-hub

http://stackoverflow.com/comment/91648212
comment on: http://stackoverflow.com/a/52351425
type: Comment
type: AnswerComment
has text: Line this instance = super().__new__(class) scares me, looks like an infinite recursion.
score: 0

http://stackoverflow.com/comment/91679546
type: AnswerComment
type: Comment
has text: Should I make another question and you make an answer related to the calculation of time shift ? :)
comment on: http://stackoverflow.com/a/52367241
score: 0

http://stackoverflow.com/a/52348793
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52348707
has body: In python if x is a list and i is an index (an integer). x[i:] means "all item in x starting at index i all the way to the end" You can also have x[i:j] "all item in x starting at index i all the way to, but not including j" x[:j] "all item in x starting at beginning all the way to, but not including j" y = x[:] "copy all elements of x in a new list and assign it to y" y = x[2:9:3] "every third element of x starting at index 2 and ending before index 9." There are more I'd suggest looking up list properties in Python.

http://stackoverflow.com/comment/91684939
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52315339
type: AnswerComment
has text: Why would it not work in pyspark data frames? Since it would seem it is an input issue and not an error in the module

http://stackoverflow.com/a/52385977
score: 2
answers question: http://stackoverflow.com/q/52385637
has comment: http://stackoverflow.com/comment/91717107
downvote count: 0
has body: What I would suggest is the following, using python's re module import re def rename(old_name): # Run a Regex to find the ending number match = re.search('lesson(\d+)', old_name) # If that was a match (that should be necessary, but # checking input is always a good idea) if match: # Retrieves the id and converts it to an integer id = int(match.group(1)) # Gets the formatted name out return '_{:03d}_lesson'.format(id) return None This is quite modular. You can change the regex next time you want to parse similar file names :).
has comment: http://stackoverflow.com/comment/91716308
upvote count: 2
type: Answer

http://stackoverflow.com/comment/91669425
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52360924
type: QuestionComment
has text: Use `$elemMatch` projection here... `db.collection.find({ "tags.tag.name": "A A" }, { "tags": { $elemMatch: { "tag.name": "A A" } } })`

http://stackoverflow.com/q/52341247
tagged with: python-3.x
has title: How to recover the mro of a class given its bases?
has answer: http://stackoverflow.com/a/52427184
tagged with: python
has comment: http://stackoverflow.com/comment/91630073
has comment: http://stackoverflow.com/comment/91629381
has comment: http://stackoverflow.com/comment/91640082
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91629512
possible better answer: http://stackoverflow.com/a/52427184
tagged with: metaclass
tagged with: method-resolution-order
has comment: http://stackoverflow.com/comment/91629660
has answer: http://stackoverflow.com/a/78945265
type: Question
score: 4
tagged with: class
upvote count: 4
has body: Suppose we are implementing a metaclass that needs to know the method resolution order before the class is instantiated. class Meta(type): def __new__(cls, name, bases, namespace): mro = ... Is there a builtin way to compute the mro, that is a way other than reimplementing the C3 algorithm?
answer count: 2
has comment: http://stackoverflow.com/comment/91629371
downvote count: 0
has comment: http://stackoverflow.com/comment/91629610
accepted answer: http://stackoverflow.com/a/78945265
favorite count: 0

http://stackoverflow.com/q/52339931
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/52339949
has body: My question is i have inp=[1,52,234,65,87,57,96,0,3] and output should be output=[0,1,52,3,234,65,96,87,57]. if the last digit is the same you leave them in same order as they are on input.increasing. inp=[1,52,234,65,87,57,96,0,3] output=[0,1,52,3,234,65,96,87,57] how you sort integers on last digit?
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91630015
has answer: http://stackoverflow.com/a/52339954
has answer: http://stackoverflow.com/a/52339959
type: Question
has title: Python sorting numbers on last digit?
score: -1
tagged with: sorting
downvote count: 2
linked to: http://stackoverflow.com/q/1129216

http://stackoverflow.com/a/52397644
upvote count: 2
answers question: http://stackoverflow.com/q/52385214
has body: In order to reference an aggregate within a filter transform, it needs to be computed within an aggregate transform rather than in the encoding shorthand. Something like this should work: alt.Chart(deliveries).transform_aggregate( total_runs='sum(batsman_runs)', groupby=['batsman'] ).transform_filter( "datum.total_runs &gt; 4000" ).mark_bar().encode( alt.X('batsman:Q', sort=alt.EncodingSortField(field='total_runs', op='count', order='descending')), alt.Y('total_runs:Q'), tooltip=['batsman:Q', 'total_runs:Q'] ).properties(height=600, width=3000).interactive()
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/q/52360488
tagged with: python-3.x
type: Question
has title: When does super() need arguments to function correctly?
tagged with: python
linked to: http://stackoverflow.com/q/17509846
upvote count: 1
has comment: http://stackoverflow.com/comment/91665450
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91665398
answer count: 0
downvote count: 0
score: 1
has body: EX: class Parent: def name(self): print("This is the parent method name()") class Child(Parent): def name(self): super(Child, self).name() super().name() dad = Parent() son = Child() dad.name() son.name() Output: This is the parent method name() This is the parent method name() This is the parent method name() I am confused as to why this works correctly in both cases, and I would like to know when I would have to use the super(Child, self).name() form in my code. Any help is greatly appreciated!
favorite count: 0

http://stackoverflow.com/comment/92126476
score: 0
type: Comment
has text: @Richard ok let me set it up freshly on my Windows and then I'll share all steps to be followed.
type: QuestionComment
comment on: http://stackoverflow.com/q/52397069

dialogflow-es
tag name: dialogflow-es
tags question: http://stackoverflow.com/q/52378289
type: Tag
tags question: http://stackoverflow.com/q/52342412

http://stackoverflow.com/q/52286228
has comment: http://stackoverflow.com/comment/91520669
type: Question
possible better answer: http://stackoverflow.com/a/52286411
score: 3
has answer: http://stackoverflow.com/a/52286411
answer count: 3
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52286266
accepted answer: http://stackoverflow.com/a/52286266
tagged with: yield-keyword
tagged with: python
has body: def mot (n) : if n==0 : yield n else : for m in mot(n-1) : yield [m] for k in range(0,n-1) : for l in mot(k) : for r in mot(n-2-k) : yield (l,r) def countFor(f,n) : for i in range(n) : count = 0 for t in f(i) : count+=1 yield count def countsFor(mes,f,n) : print(mes) print([c for c in countFor(f,n)]) print("") def showFor(mes,f,n) : print(mes) for t in f(n) : print(t) print("") showFor('Motzkin trees',mot,4) countsFor('Motzkin trees',mot,12) print("done") def test() : for n in range(6) : print(n,list(mot(n))) I have the following code that outputs the motzkin numbers, I want to change the yield expressions to another, more simple expressions or functions, how can I do that , what can I do? thanks
has title: How can I get rid of yield and use another function instead in my code
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/91520811
has answer: http://stackoverflow.com/a/52286426
tagged with: motzkin-numbers

http://stackoverflow.com/comment/91506752
type: AnswerComment
comment on: http://stackoverflow.com/a/52279334
has text: this removes non alpha characters even if it not in the front. so something like Hi-hello comes Hi
type: Comment
score: 0

darknet
tags question: http://stackoverflow.com/q/52417596
type: Tag
tag name: darknet

google-cloud-platform
tags question: http://stackoverflow.com/q/52306739
tags question: http://stackoverflow.com/q/52274071
tags question: http://stackoverflow.com/q/52329155
tags question: http://stackoverflow.com/q/52282896
tags question: http://stackoverflow.com/q/52328155
tags question: http://stackoverflow.com/q/52297527
tags question: http://stackoverflow.com/q/52374924
tags question: http://stackoverflow.com/q/52327673
tags question: http://stackoverflow.com/q/52394413
tags question: http://stackoverflow.com/q/52311029
tags question: http://stackoverflow.com/q/52396282
tags question: http://stackoverflow.com/q/52395626
tags question: http://stackoverflow.com/q/52429088
tags question: http://stackoverflow.com/q/52290122
type: Tag
tags question: http://stackoverflow.com/q/52401032
tags question: http://stackoverflow.com/q/52285033
tag name: google-cloud-platform
tags question: http://stackoverflow.com/q/52358821
tags question: http://stackoverflow.com/q/52417265
tags question: http://stackoverflow.com/q/52336941
tags question: http://stackoverflow.com/q/52395695
tags question: http://stackoverflow.com/q/52414249
tags question: http://stackoverflow.com/q/52396468
tags question: http://stackoverflow.com/q/52360409
tags question: http://stackoverflow.com/q/52398039
tags question: http://stackoverflow.com/q/52305075

http://stackoverflow.com/comment/91603978
has text: omg ... I will use for i in range(100) and then '_remainID{}'.format(i) .... the guy asks about this example not in general. In this case I will do it like in my example. If the case is with 100 variables, I will use the other approach. Anyway ... click Down vote and be happy ;)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52328338

http://stackoverflow.com/comment/91566603
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52309772
score: 0
has text: @user3483203 have to sort by length.

http://stackoverflow.com/q/52335866
has answer: http://stackoverflow.com/a/52335959
has answer: http://stackoverflow.com/a/52335946
score: 0
has body: I want to count the occurrence of first character of string in array elements in python ex. sample = ["abc","def","ade", "acf", "bal"] Output: a = 3 b = 1 d = 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91622004
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52336247
has title: Need help to use groupBy in python
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/91619365
type: Question
has answer: http://stackoverflow.com/a/52336044

http://stackoverflow.com/comment/91515201
type: AnswerComment
has text: This is essentially equivalent to [my answer](https://stackoverflow.com/a/52282310/5858851), except you replaced the list comp with a call to `map`. BTW, this won't work in python3. In any case, I still say that you should just use a loop.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52282587

http://stackoverflow.com/q/52286219
downvote count: 0
has body: I am looking into some code I have not written with pdb. (Pdb) self.function &lt;CFunctionType object at 0x000000DC768E0E18&gt; (Pdb) type(self.function) &lt;class 'ctypes.CFUNCTYPE.&lt;locals&gt;.CFunctionType'&gt; (Pdb) dir(self.function) ['__bool__', '__call__', '__class__', '__ctypes_from_outparam__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_argtypes_', '_b_base_', '_b_needsfree_', '_flags_', '_objects', '_restype_', 'argtypes', 'errcheck', 'restype'] (Pdb) self.function._flags_ 1 (Pdb) self.function._objects {'0': &lt;CDLL 'C:\path', handle 7ffe26465400 at 0xdc74ad2908&gt;} Is it possible for me to find out where self.function was defined, or what the name of the function is? self.function._objects points towards a DLL, but it's not clear to me how or if I can find the function's name so I can look it up in the source code. Further, is it possible to step into the function when it is called? It is called in the code in the following way: self.function(*self.args)
has answer: http://stackoverflow.com/a/52286812
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91521532
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91521447
tagged with: python
score: 3
has title: Python ctypes - get name of CFUNCTYPE
upvote count: 3
type: Question
tagged with: ctypes
tagged with: dll

http://stackoverflow.com/q/52367986
type: Question
has answer: http://stackoverflow.com/a/52372049
tagged with: ply
has body: I am trying to make a parser calculator in Python using PLY. I began with some PLY example code and worked my way from there. What I am trying to add is functionality for continuing calculations on the previous result. So if you type '4 + 5' the result is 9. If you then type '* 2 - 3', the new result should be 15, but with my code it is -9 because it parses '2 - 3' first, when it should parse '9 * 2' first. This issue occurs when I use multiplication or division as the first operator when doing a calculation with the previous result. As shown in my code excerpt I tried giving precedence to the expressions that used the previous result, but I still have the same problem. 'r' is a variable which stores the previous result. tokens = ( 'NUMBER', ) literals = ['=', '+', '-', '*', '/', '(', ')'] precedence = ( ('left', '+', '-'), ('right', 'RADD', 'RSUB'), ('left', '*', '/'), ('right', 'RMUL', 'RDIV'), ('right', 'UMINUS'), ) def p_statement_expr(p): 'statement : expression' p[0] = p[1] def p_expression_binop(p): '''expression : expression '+' expression | expression '-' expression | expression '*' expression | expression '/' expression''' if p[2] == '+': p[0] = p[1] + p[3] elif p[2] == '-': p[0] = p[1] - p[3] elif p[2] == '*': p[0] = p[1] * p[3] elif p[2] == '/': p[0] = p[1] / p[3] def p_expression_cont(p): '''statement : '+' expression %prec RADD | '-' expression %prec RSUB | '*' expression %prec RMUL | '/' expression %prec RDIV ''' if p[1] == '+': p[0] = r + p[2] elif p[1] == '-': p[0] = r - p[2] elif p[1] == '*': p[0] = r * p[2] elif p[1] == '/': p[0] = r / p[2] def p_expression_uminus(p): "expression : '(' '-' expression ')' %prec UMINUS" def p_expression_group(p): "expression : '(' expression ')'" p[0] = p[2] def p_expression_number(p): "expression : NUMBER" p[0] = p[1] I also attempted to change the grammar to p_expression_cont(p): '''expression : '+' expression %prec MORADD | '-' expression %prec MORSUB | '*' expression %prec MORMUL | '/' expression %prec MORDIV ''…
answer count: 1
downvote count: 0
tagged with: calculator
accepted answer: http://stackoverflow.com/a/52372049
has title: How do I modify my parser calculator grammar to continue calculations on previous result?
tagged with: parsing
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/q/52330799
score: 4
possible better answer: http://stackoverflow.com/a/72978446
has body: I'm trying to set up black to run on any files checked into git. I've set it up as follows: git config filter.black.clean 'black -' echo '*.py filter=black' &gt;&gt; .git/info/attributes As far as I understand, this should work ok as black with - as the source path will read from STDIN and output to STDOUT, which is what I think the git filter needs it to do. However this does not work. When I add an un-black file with git add I see the following output: reformatted - All done! ✨ ✨ 1 file reformatted. And the file is not changed on disk. What am I doing wrong?
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/72978446
answer count: 2
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52334703
accepted answer: http://stackoverflow.com/a/52334703
tagged with: git
has title: Using black with git clean filter
type: AnsweredQuestion

http://stackoverflow.com/comment/91741136
type: Comment
has text: If I try to open it using the Navigator, I get the same error.
comment on: http://stackoverflow.com/q/52349503
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91646757
type: AnswerComment
has text: this is a dataframe I converted from a dictionary and resulted in this werid format
type: Comment
comment on: http://stackoverflow.com/a/52350354
score: 0

http://stackoverflow.com/a/52366968
score: 15
upvote count: 15
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52366558
downvote count: 0
type: Answer
has body: You can convert values to ordered categorical with sorted catgories by natsorted and then use sort_values: import natsort as ns df['a'] = pd.Categorical(df['a'], ordered=True, categories= ns.natsorted(df['a'].unique())) df = df.sort_values('a') print (df) a b 5 a1 b1 2 a1 b11 4 a3 b4 3 a10 b22 6 a11 b12 1 a20 b2 0 a22 b5 df['b'] = pd.Categorical(df['b'], ordered=True, categories= ns.natsorted(df['b'].unique())) df = df.sort_values('b') print (df) a b 5 a1 b1 1 a20 b2 4 a3 b4 0 a22 b5 2 a1 b11 6 a11 b12 3 a10 b22
accepted answer of: http://stackoverflow.com/q/52366558

http://stackoverflow.com/comment/91597252
comment on: http://stackoverflow.com/q/52325152
score: 0
type: Comment
type: QuestionComment
has text: `print` is a relatively slow function, so it can potentially change the timing of functions that use it. Be careful as you may be just luckily hiding a race condition because of the addition of the `print` function.

http://stackoverflow.com/q/52310905
tagged with: python
tagged with: pytorch
type: UnansweredQuestion
has body: I write two types of liner-classifier in PyTorch: torch.manual_seed(0) fc = [] for i in range(n): fc.append(nn.Linear(feature_size, 1)) The other: torch.manual_seed(0) fc = nn.Linear(feature_size, n) And different results were obtained using these two types of fc in a multi-label classification model. Actually, those fc initialized differently and leads to different results. Which one is correct and what should I do if I want the similar results using two types of fc. Additional Information: I find out the reason lead to bad result: The first type FC not updates in training! But I don't know why there is no updating, my code as follow: x = self.features(input) res = [] for i in range(self.num_classes): res.append(self.fc[i](x.cpu())) res = torch.cat(res, 1) return res.cuda() Any idea about this?
tagged with: machine-learning
type: Question
has answer: http://stackoverflow.com/a/52312166
has title: nn.Linear(feature_size, 1)*n vs nn.Linear(feature_size, n) in PyTorch
tagged with: deep-learning
answer count: 1
tagged with: neural-network
score: 0

http://stackoverflow.com/a/52313398
score: 1
accepted answer of: http://stackoverflow.com/q/52313090
upvote count: 1
has comment: http://stackoverflow.com/comment/91611761
has comment: http://stackoverflow.com/comment/91607789
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91583075
has body: The file is in YAML format. Normally you would specify this with .yml extension rather than .txt but it doesn't affect the file contents. Rather than parse with something like regex, you can instead read in the YAML format and write back out in your desired output. See the documentation for PyYAML for more details. import yaml with open('test.txt') as infile: data = yaml.load(infile) with open('test_out.txt', 'w') as outfile: for neighbor in data['neighbors']: outfile.write('neighbor {} remote-as {}\n'.format(neighbor['neighbor'], neighbor['remote-as'])) Note that dictionaries only started becoming ordered in python 3.6, and only guaranteed to be ordered in 3.7+, so for earlier versions of Python, it cannot be guaranteed that you will get the exact desired output. You could mitigate this by specifying the sub-dictionary keys in the string you're writing out.
answers question: http://stackoverflow.com/q/52313090
type: Answer
has comment: http://stackoverflow.com/comment/91584483

size
type: Tag
tags question: http://stackoverflow.com/q/52288635
tag name: size

http://stackoverflow.com/a/52413234
type: Answer
answers question: http://stackoverflow.com/q/52412717
has comment: http://stackoverflow.com/comment/91770311
has comment: http://stackoverflow.com/comment/91770352
has comment: http://stackoverflow.com/comment/91770783
has comment: http://stackoverflow.com/comment/91770984
has body: Okay after looking at your code for a long time, there are two main problems. &lt;li&gt;{{ theURL.theURLs }}&lt;/li&gt; should just be &lt;li&gt;{{ theURL }}&lt;/li&gt; Your for loop is seriously messed up. In its current form, you only take the last URL that you iterate over. Fix it in this way: def getTheA(request): theURLs = [] for yadayadayada: theURLs.append(x['url']) theNames = json.dumps(x['tags']['tag']['name']) theVars = json.dumps(x['tags']['variables']) context = { 'theURLs' : theURLs } return render(request, 'templates/a.html', context=context)
has comment: http://stackoverflow.com/comment/91770692
score: 0

http://stackoverflow.com/comment/91680269
type: AnswerComment
comment on: http://stackoverflow.com/a/52367848
type: Comment
score: 2
has text: [here](https://en.wikipedia.org/wiki/Comparison_of_file_systems) you can check which filesystem has `/` in the 'allowable characters for directory entries'.

http://stackoverflow.com/comment/91847658
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52420187
type: Comment
has text: If you are always using a 3-element second vector for convolution, you might just take array[2: end-1] to drop first and last elements.

http://stackoverflow.com/comment/91763552
type: Comment
score: 2
comment on: http://stackoverflow.com/a/52409738
type: AnswerComment
has text: @Sid You should start by learning the basics of TCP. A google search should point you to the technical documentation. Then read the API docuentation at https://www.sharekhan.com/Upload/General/TradeTigerAPIForClient.pdf and find a TCP library for python to implement the requests.

http://stackoverflow.com/comment/91597388
comment on: http://stackoverflow.com/a/52324987
has text: all of the data is this W596304 ( it stats with a W and has 6 numbers after) that I am looking up. Essentially I am trying to circumvent doing a vlookup./group the vlookup matches and delete all the rows that had a match in the vlookup
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91856878
score: 0
comment on: http://stackoverflow.com/a/52417802
type: Comment
has text: Please accpet an answer if any of them worked for you
type: AnswerComment

http://stackoverflow.com/comment/91637651
type: QuestionComment
has text: Please, provide [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).
comment on: http://stackoverflow.com/q/52345987
type: Comment
score: 0

http://stackoverflow.com/q/52367388
favorite count: 0
has title: apply(set) to two columns in a pandas dataframe
tagged with: python
type: AnsweredQuestion
score: 3
tagged with: list
upvote count: 3
tagged with: set
tagged with: apply
has answer: http://stackoverflow.com/a/52367448
type: Question
has body: I have three columns in a dataframe. I would like to make the second and third column have sets as opposed to lists. Using df['column_name_2 and column_name_3'].apply(set) results in an error because, as I understand it, this function will only take 1 argument. However splitting them into two separate functions, completely eliminates column three. This is what I have: column_1 column_2 column_3 1 [lk, 18m] [kjaf] This is what I want: column_1 column_2 column_3 1 {lk, 18m} {kjaf}
downvote count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52367448
answer count: 1

http://stackoverflow.com/q/52373862
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91697205
linked to: http://stackoverflow.com/q/7305742
has body: a. Have a scenario where in have some environment variables and other alias set. b. But I wanted to store that info in a different string and whenever the user calls the particular alias, it needs to print all the string store in that variable, like HELP function. c. I was trying like, printinfo_var = " This is line 1. This is line 2. This is line 3. " alias printinfo 'echo $printinfo_var' Query: 1. But I am unable to proceed with the same when I tried in CSHELL Script. 2. Which is the best scripting methodology that I can use to set and print environment variables?? Share in your comments !
has comment: http://stackoverflow.com/comment/91698162
duplicate of: http://stackoverflow.com/q/7305742
type: Question
tagged with: csh
has title: How To Store Multiple Lines in a String And Echo That String To Print The Output in CSHELL Script?
score: 0
tagged with: tcsh
has comment: http://stackoverflow.com/comment/91697488
tagged with: python
tagged with: shell
answer count: 0

http://stackoverflow.com/a/52296887
has body: Numpy, cumsum with alternating sign i = np.arange(len(df)) j = np.arange(2) a = np.where( (i[:, None] + j) % 2 == 0, 1, -1 ) * df.VALUE.values[:, None] b = a.cumsum(0)[i, i % 2] df.assign(VALUE=b) ID VALUE 0 0 1 1 1 9 2 2 21 3 3 24 4 4 54 Explanation First thing is to notice that X0 -&gt; X0 X1 -&gt; X1 - X0 X2 -&gt; X2 - X1 + X0 X3 -&gt; X3 - X2 + X1 - X0 X4 -&gt; X4 - X3 + X2 - X1 + X0 So I wanted to multiply every other row by negative one... but I needed to do this twice for the other choice of alternating rows. I needed to generate a mask that swaps between + and - 1 for both options i = np.arange(len(df)) j = np.arange(2) m = np.where( (i[:, None] + j) % 2 == 0, 1, -1 ) m array([[ 1, -1], [-1, 1], [ 1, -1], [-1, 1], [ 1, -1]]) Now I need to broadcast multiply this across my df.VALUE a = m * df.VALUE.values[:, None] a array([[ 1, -1], [-10, 10], [ 30, -30], [-45, 45], [ 78, -78]]) Notice the pattern. Now I cumsum a.cumsum(0) array([[ 1, -1], [ -9, 9], [ 21, -21], [-24, 24], [ 54, -54]]) But I need the positive ones... more specifically, I need the alternating ones. So I slice with a modded arange b = a.cumsum(0)[i, i % 2] b array([ 1, 9, 21, 24, 54]) This is what I ended up assigning to the existing column df.assign(VALUE=b) ID VALUE 0 0 1 1 1 9 2 2 21 3 3 24 4 4 54 This produces a copy of df and overwrites the VALUE column with b. To persist this answer, make sure to reassign to a new name or df if you want. df_new = df.assign(VALUE=b)
score: 9
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91542162
accepted answer of: http://stackoverflow.com/q/52296536
has comment: http://stackoverflow.com/comment/91542184
answers question: http://stackoverflow.com/q/52296536
upvote count: 9
has comment: http://stackoverflow.com/comment/91541835

http://stackoverflow.com/comment/91708821
has text: @Mavrick - You can add `matched_categories = [x for x in matched_categories if x != 'not matched']` to the end.
type: AnswerComment
comment on: http://stackoverflow.com/a/52288250
type: Comment
score: 1

http://stackoverflow.com/q/52413215
has title: python3 use logging to log all elements in a container(list, or tuple)
favorite count: 0
has comment: http://stackoverflow.com/comment/91770231
has comment: http://stackoverflow.com/comment/91770283
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91770170
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52413348
has body: In Python3, if we want to print all elements in a list, we can simply do lst = ['a','b', 'c'] print(lst) In this way, we can print out all elements in a list. Suppose now I use logging to log everything, instead of print it out to the screen, for a debug purpose, how to log all elements in a container ( i.e list, or tuple) ? I can think of something like : for it in lst: log.info("element is {i}".format(i = it)) but this is too ugly. Any suggestion? I also refer Howto , but did not get much input.
downvote count: 1
tagged with: logging
type: Question
score: -1
has comment: http://stackoverflow.com/comment/91770374
upvote count: 0
answer count: 1

getgauge
tags question: http://stackoverflow.com/q/52370910
tag name: getgauge
type: Tag

http://stackoverflow.com/q/52358291
has comment: http://stackoverflow.com/comment/91661478
tagged with: jupyter-notebook
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/91700428
type: Question
has body: I'm using movielens database and I need to create a dataframe about movies X genres in python. In other words, I need to transform the dataframe in a new binary dataframe. How can I do this in a optimized way?
linked to: http://stackoverflow.com/q/18889588
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91661142
has comment: http://stackoverflow.com/comment/91697250
duplicate of: http://stackoverflow.com/q/18889588
tagged with: pandas
linked to: http://stackoverflow.com/q/29034928
type: UnansweredQuestion
has title: How can I create a dataframe of movies X genres using the original dataframe?
tagged with: python

http://stackoverflow.com/q/52297758
upvote count: 1
tagged with: python
type: AnsweredQuestion
has body: I just started programming in python yesterday. Ultimately I want to open a comma deliminated file and read its contents. I searched for related topics and tried using some of the code and am running into some errors. Code: def ReadTxtFile(): fname="c:\vba\lapseC2.csv" #with open(fname) as f: with open("c:\vba\lapseC2.csv", "r") as f: content = f.readlines you may also want to remove whitespace characters like \n at the end of each line content = [x.strip() for x in content] ReadTxtFile() Error: OSError: [Errno 22] Invalid argument: 'c:\x0bba\lapseC2.csv'
score: 1
linked to: http://stackoverflow.com/q/2953834
type: Question
has title: Python, Open file, error OSError: [Errno 22] Invalid argument
accepted answer: http://stackoverflow.com/a/52297955
duplicate of: http://stackoverflow.com/q/2953834
downvote count: 0
has comment: http://stackoverflow.com/comment/91543934
answer count: 1
has comment: http://stackoverflow.com/comment/91543450
favorite count: 0
has answer: http://stackoverflow.com/a/52297955

http://stackoverflow.com/comment/91759074
score: 2
comment on: http://stackoverflow.com/q/52407669
type: Comment
type: QuestionComment
has text: Possible duplicate of [FileNotFoundError: \[Errno 2\] No such file or directory](https://stackoverflow.com/questions/22282760/filenotfounderror-errno-2-no-such-file-or-directory)

http://stackoverflow.com/q/52406323
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52407792
has comment: http://stackoverflow.com/comment/91756403
score: 0
has answer: http://stackoverflow.com/a/52407792
tagged with: django
has comment: http://stackoverflow.com/comment/91757951
has comment: http://stackoverflow.com/comment/91756968
has body: I think the answer is simple but I can't figure it out. So I have three models: host, project and a model that relates those two. In my template I have two 'select' inputs, one for the host and one for the project. What I want to do is show only the projects that are related to the host that is currently selected(the relations are described in the third model). Perhaps there is a better way to do this in the views.py file than in the html page. Code: class Projetos(models.Model): nomeAlias = models.CharField("Nome do Projeto",max_length=50, default='Personalizado') nome = models.CharField("Nome do Projeto(Artifactory)",max_length=50, primary_key=True) repositorio = models.CharField("Repositório do Projeto", max_length=150) remote_war = models.CharField("Nome do WAR do projeto",max_length=150) class Maquina(models.Model): nome = models.CharField("Nome da Máquina",max_length=20) endereco = models.CharField("Endereço da Máquina",max_length=300, primary_key=True) class RelMaquinaProjeto(models.Model): maquina = models.ForeignKey(Maquina, on_delete=models.CASCADE,related_name='relacoes',verbose_name="Nome da Máquina") projeto = models.ForeignKey(Projetos, on_delete=models.CASCADE,related_name='projetos_em',verbose_name="Nome do Projeto") contexto = models.CharField("Contexto",max_length=20)
type: Question
has comment: http://stackoverflow.com/comment/91756875
has title: Django: Filter database query in template
answer count: 2
has answer: http://stackoverflow.com/a/52407529
has comment: http://stackoverflow.com/comment/91757006
has comment: http://stackoverflow.com/comment/91756899
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52407529
has comment: http://stackoverflow.com/comment/91756745
tagged with: python

http://stackoverflow.com/comment/91806255
has text: The first case is entirely sufficient. I actually ended up simply doing `type(name, bases, {}).__mro__[1:]`
type: Comment
comment on: http://stackoverflow.com/a/52427184
score: 0
type: AnswerComment

task
type: Tag
tag name: task
tags question: http://stackoverflow.com/q/52358358

http://stackoverflow.com/comment/91502010
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52272325
has text: @MisterMiyagi I'm looking for the simplest multiprocessing with error handling - I'd like to avoid adding wrapper class or equivalent to handle it though.
score: 0

http://stackoverflow.com/q/52426694
has answer: http://stackoverflow.com/a/52426881
has body: I would like to get a arg.pics which returns something like ['pic1.png', 'pic2.png', 'pic3.png'] (to arbitrarily parse all files of .png format) after running the following (test.py): import argparse import os def parser_arg(): par = argparse.ArgumentParser() parser = par.add_argument_group('pictures') parser.add_argument("-p", "--pics", nargs="+", help="picture files", required=True) arguments = par.parse_args() return arguments args = parser_arg() And upon running the script via command line, and inputting python test.py -p ../User/Desktop/Data/*.png then args.pics returns ['../User/Desktop/Data/*.png'] instead.. Am I using the right approach? I heard using *.png will be expanded into the .png files once inputted but it doesn't seem to be the case on my end. Edits: I'm using Anaconda Prompt on Windows 10 if it helps.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52427434
type: Question
has comment: http://stackoverflow.com/comment/91796874
has title: parse_args all .png files from a parser argument
has answer: http://stackoverflow.com/a/52427434
has comment: http://stackoverflow.com/comment/91797348
possible better answer: http://stackoverflow.com/a/52426881
score: 0
has comment: http://stackoverflow.com/comment/91797041
answer count: 2
has comment: http://stackoverflow.com/comment/91796916
has comment: http://stackoverflow.com/comment/91797030
tagged with: python-3.x
tagged with: argparse
tagged with: glob
tagged with: windows
has comment: http://stackoverflow.com/comment/91796953
tagged with: python

http://stackoverflow.com/q/52303403
tagged with: tensorflow
type: Question
score: 1
accepted answer: http://stackoverflow.com/a/52309009
has comment: http://stackoverflow.com/comment/91554898
has title: Getting batch predictions for TFrecords via CloudML
has comment: http://stackoverflow.com/comment/91556157
answer count: 1
downvote count: 0
tagged with: tfrecord
has answer: http://stackoverflow.com/a/52309009
favorite count: 0
tagged with: google-cloud-ml
tagged with: python
type: AnsweredQuestion
tagged with: machine-learning
has body: I followed this great tutorial and successfully trained a model (on CloudML). My code also makes predictions offline, but now I am trying to use Cloud ML to make predictions and have some problems. To deploy my model I followed this tutorial. Now I have a code that generates TFRecords via apache_beam.io.WriteToTFRecord and I want to make predictions for those TFRecords. To do so I am following this article, my command looks like this: gcloud ml-engine jobs submit prediction $JOB_ID --model $MODEL --input-paths gs://"$FILE_INPUT".gz --output-path gs://"$OUTPUT"/predictions --region us-west1 --data-format TF_RECORD_GZIP But I get only errors: 'Exception during running the graph: Expected serialized to be a scalar, got shape: [64] It seems like it expect data in a different format. I found the format specs for JSON here, but couldn't find how to do it with TFrecords. UPDATE: here is the output of saved_model_cli show --all --dir MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs: signature_def['prediction']: The given SavedModel SignatureDef contains the following input(s): inputs['example_proto'] tensor_info: dtype: DT_STRING shape: unknown_rank name: input:0 The given SavedModel SignatureDef contains the following output(s): outputs['probability'] tensor_info: dtype: DT_FLOAT shape: (1, 1) name: probability:0 Method name is: tensorflow/serving/predict signature_def['serving_default']: The given SavedModel SignatureDef contains the following input(s): inputs['example_proto'] tensor_info: dtype: DT_STRING shape: unknown_rank name: input:0 The given SavedModel SignatureDef contains the following output(s): outputs['probability'] tensor_info: dtype: DT_FLOAT shape: (1, 1) name: probability:0 Method name is: tensorflow/serving/predict
upvote count: 1

http://stackoverflow.com/a/52381770
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52381723
answers question: http://stackoverflow.com/q/52381723
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: This line here right at the top: bgp_result_file = open(r'E:\\Python-Scripts\\bgp-result.txt','w') That line is executed at the start of your script and basically wipes out the file. From the documentation: https://docs.python.org/2/library/functions.html#open The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). [...] truncating the file if it already exists.
has comment: http://stackoverflow.com/comment/91753026

http://stackoverflow.com/a/52336343
has body: There is currently no GUI capable of reading the contents of .npy as plain text. However, if you think that such a program would be beneficial to the community, then you can easily create such a tool. Let's look at a couple ways in which the aforementioned tool could work: Simply output the results of np.load to a file using the console command: $ python your_program.py &gt; file.txt This redirects the console output from your_program.py to file.txt. Use the contextlib.redirect_stdout() function to output only a the relevant data from stdout into file.txt. Like so: from contextlib import redirect_stdout with open("help.txt", "w") as f: with redirect_stdout(f): print('it now prints to 'help.text')
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52335967

http://stackoverflow.com/q/52293990
type: Question
accepted answer: http://stackoverflow.com/a/52294352
tagged with: dataset
has body: I have a list of dictionaries in python with values both floats and np arrays. I want to save it in a pandas dataframe so that I can plot the xarr, yarr for a given set of parameters. dic1 = {'p1':1, 'p2': 34, 'xarr' : np.array([1,2,3]) , 'yarr': np.array([4,4,6])} dic2 = {'p1':2, 'p2': 45 ,'xarr' : np.array([1,2,3]) , 'yarr': np.array([6,6,4])} listdic = [dic1, dic2] df = pd.DataFrame(listdic) dfplot= df[df['p1'] &gt; 1] x, y = dfplot['xarr'], dfplot['yarr'] plt.plot(x, y) But I get this error ValueError: setting an array element with a sequence. Because I am also getting the index of the pandas df. Is there an efficient way of doing this?
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52294352
answer count: 1
has title: How to create a panda/pickle dataset wtih np arrays entries in columns so that I can plot them efficiently?
tagged with: python
tagged with: plot
type: AnsweredQuestion

http://stackoverflow.com/a/52405770
has body: I'm going to take a wild guess and say that it should look like this: action.Id = action_id Note that all other fields are camel case. It looks like IAction has a put_Id method, and I assume the Python wrapper preserves the case of the fields it exposes as attributes.
has comment: http://stackoverflow.com/comment/91755674
score: 0
has comment: http://stackoverflow.com/comment/91755282
type: Answer
answers question: http://stackoverflow.com/q/52405712
has comment: http://stackoverflow.com/comment/91755415

http://stackoverflow.com/a/52429847
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/91806902
downvote count: 0
has body: Frankly, all this zip stuff, list comprehension etc might look like a clever thing, but why don't you use Multinomial sampling? One liner, really, and sum is automatically, by definition, equal to N import numpy as np t = np.random.multinomial(200, [1/288.]*288, size=1) # sample 288 numbers summed to 200 print(t) print(sum(t[0])) t = np.random.multinomial(1000, [1/288.]*288, size=1) # sample 288 numbers summed to 1000 print(t) print(sum(t[0]))
type: Answer
answers question: http://stackoverflow.com/q/52426195

http://stackoverflow.com/comment/91596277
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52324568
has text: Why not simply change the filename? The ambiguity just seems to be asking for confusion.
type: Comment

http://stackoverflow.com/q/52330532
has answer: http://stackoverflow.com/a/52330710
tagged with: python
type: AnsweredQuestion
has body: I have trained a neural network using TensorFlow 1.8.0 and eager execution. After training I saved it and there were no problems with loading and predicting. Then I made a python server (using flask) which loads the trained model to receive POST requests with data in format json, which is later standardized and proceeded to the model. But now every time I restart the server the neural network gives different answers with different probabilities. I have checked that: the data received by the server a really the same. when manually restoring the network without a server and manually giving the data to it - all the answers are the same with the same probabilities. This is how the code looks like: imports tf.enable_eager_execution() model = tf.keras.Sequential([ ... ]) optimizer root = tfe.Checkpoint(optimizer=optimizer, model=model, optimizer_step=tf.train.get_or_create_global_step()) root.restore(tf.train.latest_checkpoint(checkpoint_directory)) @app.route('/calc', methods=['POST']) def predict_data(): read and parse json class_ids = ["false", "true"] predict_data = tf.convert_to_tensor([data_to_predict]) predictions = model(predict_data) for i, logits in enumerate(predictions): class_idx = tf.argmax(logits).numpy() p = tf.nn.softmax(logits)[class_idx] name = class_ids[class_idx] return("{\"Result\":"+ name+",\"Probability\":"+str(float(p))+"}") if __name__ == '__main__': app.run(debug, port) Seems like some weights are randomly initialized somehow but the problem is that when I'm not using a server, everythig acts as it has to.
accepted answer: http://stackoverflow.com/a/52480704
tagged with: tensorflow
has title: Tensorflow neural network predicts different answers for the same data after creating a server
type: Question
tagged with: server
score: 0
answer count: 2
tagged with: neural-network
has comment: http://stackoverflow.com/comment/91608185
has answer: http://stackoverflow.com/a/52480704
possible better answer: http://stackoverflow.com/a/52330710

http://stackoverflow.com/comment/91762665
type: AnswerComment
comment on: http://stackoverflow.com/a/52403401
type: Comment
score: 0
has text: I agree. Thank you for your time

http://stackoverflow.com/q/52376482
has comment: http://stackoverflow.com/comment/91697738
type: Question
has title: Django - Boolean updated on web view but not when exported
has body: Depending on certain conditions on the models.py, I would like to have the ABC BooleanField to be ticked (green check) or unticked (red cross). This, I have done it without any problems; however, when I am trying to export (as a CSV or XLSX) that same dataset with the ABC BooleanField, the BooleanField is not updated according to the web view nor the models.py I have set. Could you please give me some guidance? The following are parts of the code: class something(models.Model) book = models.BooleanField(default=False) ... some code ... def bookcheck(self): if self.writingDate is not None: if self.publishDate is not None: self.book = True return True else: return False else: return False bookcheck.boolean = True
answer count: 1
downvote count: 0
tagged with: django-import-export
tagged with: python
has answer: http://stackoverflow.com/a/52377584
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: django
score: 1

pyqt5
tags question: http://stackoverflow.com/q/52304519
tags question: http://stackoverflow.com/q/52414654
tags question: http://stackoverflow.com/q/52410731
type: Tag
tags question: http://stackoverflow.com/q/52360073
tags question: http://stackoverflow.com/q/52307237
tags question: http://stackoverflow.com/q/52313073
tags question: http://stackoverflow.com/q/52288632
tags question: http://stackoverflow.com/q/52338500
tags question: http://stackoverflow.com/q/52358258
tags question: http://stackoverflow.com/q/52291734
tags question: http://stackoverflow.com/q/52359924
tags question: http://stackoverflow.com/q/52376313
tags question: http://stackoverflow.com/q/52391813
tags question: http://stackoverflow.com/q/52321938
tags question: http://stackoverflow.com/q/52409119
tags question: http://stackoverflow.com/q/52377946
tags question: http://stackoverflow.com/q/52314931
tags question: http://stackoverflow.com/q/52401233
tags question: http://stackoverflow.com/q/52376364
tags question: http://stackoverflow.com/q/52377073
tags question: http://stackoverflow.com/q/52384362
tags question: http://stackoverflow.com/q/52379948
tags question: http://stackoverflow.com/q/52391008
tags question: http://stackoverflow.com/q/52423429
tags question: http://stackoverflow.com/q/52315520
tags question: http://stackoverflow.com/q/52368510
tags question: http://stackoverflow.com/q/52286009
tags question: http://stackoverflow.com/q/52427383
tags question: http://stackoverflow.com/q/52359042
tags question: http://stackoverflow.com/q/52282780
tags question: http://stackoverflow.com/q/52300267
tags question: http://stackoverflow.com/q/52343873
tags question: http://stackoverflow.com/q/52389811
tags question: http://stackoverflow.com/q/52338366
tag name: pyqt5
tags question: http://stackoverflow.com/q/52372134
tags question: http://stackoverflow.com/q/52332534
tags question: http://stackoverflow.com/q/52404221
tags question: http://stackoverflow.com/q/52339932

http://stackoverflow.com/comment/91838405
score: 0
has text: @OllieMcFly dictionary are my fav! :) best of luck!
comment on: http://stackoverflow.com/a/52356055
type: Comment
type: AnswerComment

http://stackoverflow.com/q/52377370
upvote count: 1
linked to: http://stackoverflow.com/q/1041542
has comment: http://stackoverflow.com/comment/91699414
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: python-requests
has comment: http://stackoverflow.com/comment/91700245
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91722330
has title: Sending directory to client from server flask
tagged with: flask-restful
has comment: http://stackoverflow.com/comment/91723368
type: Question
has comment: http://stackoverflow.com/comment/91736834
has comment: http://stackoverflow.com/comment/91702152
has body: I am trying to return a directory of images from the server to the client. I'm having a hard time understanding how to format my response so that the client is able to distinguish between the files. What is the best practice way to accomplish what I am doing? my photos are kept in a tmp folder within the application. Here is my utils.py: def get_multipart_fields(): final = {} for file in os.listdir(os.path.dirname(os.path.realpath(__file__)) + '/tmp'): try: with open(os.path.dirname(os.path.abspath(__file__)) + '/tmp/' + os.path.join(file), "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) final[os.path.join(file)] = { 'filename': encoded_string } except Exception as e: print e return final.to_string() and my views.py: @app.route('/download-files', methods=['GET']) def gallery(): client = get_client() resource = get_resource() download_dir(client, resource, 'test-bucket') file_names = get_multipart_fields() m = MultipartEncoder( fields=file_names ) return Response(json.dumps(m), mimetype=m.content_type) Where am I going wrong with this logic ? Any help would be greatly appreciated.
tagged with: flask

http://stackoverflow.com/comment/91502587
comment on: http://stackoverflow.com/q/52276566
score: 0
has text: @vash_the_stampede No, that doesn't seem to do the trick.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52291998
type: AnsweredQuestion
tagged with: scrapy
type: Question
score: 4
has answer: http://stackoverflow.com/a/65821580
upvote count: 4
has answer: http://stackoverflow.com/a/53372477
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/65821580
tagged with: amazon-web-services
linked to: http://stackoverflow.com/q/54409036
tagged with: aws-lambda
favorite count: 0
tagged with: python-3.x
has body: I built a crawler using the python scrapy library. It works perfectly and reliably when running locally. I have attempted to port it over to the AWS lambda (I have packaged it appropriately). However when I run it the process isn't blocked whilst the crawl runs and instead completes before the crawlers can return giving no results. These are the last lines I get out of logs before it exits: 2018-09-12 18:58:07 [scrapy.middleware] INFO: Enabled item pipelines: [] 2018-09-12 18:58:07 [scrapy.core.engine] INFO: Spider opened Whereas normally I would get a whole of information about the pages being crawled. I've tried sleeping after starting the crawl, installing crochet and adding its declarators and installing and using this specific framework that sounds like it addresses this problem but it also doesn't work. I'm sure this is an issue with Lambda not respecting scrapys blocking, but I have no idea on how to address it.
has comment: http://stackoverflow.com/comment/91556092
has title: Unable to get results from Scrapy on AWS Lambda
linked to: http://stackoverflow.com/q/44058239
tagged with: python
accepted answer: http://stackoverflow.com/a/53372477

http://stackoverflow.com/q/52429613
has answer: http://stackoverflow.com/a/52429716
upvote count: 0
has body: Consider the following code (I received a name error when running this) item = input("What food???") def itemcheck(): if item == "chex": cereal = "Yummy" else: cereal = "Yuck!" itemcheck() print(cereal) the error was name 'cereal' is not defined. What error am I making/how do I fix it? What is the correct way to define a variable in your own function?
has answer: http://stackoverflow.com/a/52429814
has comment: http://stackoverflow.com/comment/91802904
has title: Error when defining variables within a defined function (Python)
type: Question
has answer: http://stackoverflow.com/a/52429643
linked to: http://stackoverflow.com/q/35920320
downvote count: 3
duplicate of: http://stackoverflow.com/q/35920320
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52429664
score: -3
tagged with: python
answer count: 4

http://stackoverflow.com/a/52347063
answers question: http://stackoverflow.com/q/52346412
accepted answer of: http://stackoverflow.com/q/52346412
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You can use datetime.strptime and datetime.strftime for that like so: from datetime import datetime def convert1(string): conversion = '%d' + string[2:4] + ' %b %Y' dt = datetime.strptime(string, conversion) return dt.strftime('%Y-%m-%d %H:%M:%S') def convert2(string): conversion = '%a %d' + string[6:8] + ' %b %Y' dt = datetime.strptime(string, conversion) return dt.strftime('%Y-%m-%d %H:%M:%S') print(convert1('30th Sep 2018')) print(convert2('Mon 30th Sep 2018')) print(convert1('01st Sep 2018')) print(convert2('Sun 02nd Sep 2018')) This is the output: 2018-09-30 00:00:00 2018-09-30 00:00:00 2018-09-01 00:00:00 2018-09-02 00:00:00 I used the patterns as described in the documentation for datetime. I used sclicing to extract the th part of the date-string. In doing so I ensure that the functions also work for nd and st.
score: 1
upvote count: 1

http://stackoverflow.com/q/52326123
score: 0
has answer: http://stackoverflow.com/a/52326795
tagged with: python
type: UnansweredQuestion
tagged with: tensorflow
type: Question
answer count: 2
has body: Hi~I'm new to python's tensorflow. I would like my training model to identify easy Captcha images. I use a .net application to create 0 to 9 Captcha images. And using keras tensorflow to train my model. if I created 0 to 9 and every number 1000 images, val_loss and val_acc would not improved. And it always mistake 8 to 3 and 9 to 0. [https://i.sstatic.net/akZMG.jpg][https://i.sstatic.net/fsKPp.jpg][https://i.sstatic.net/SiH7B.jpg] But add 2000 number 9 images ,it works. I don't know why. [https://i.sstatic.net/v6czM.jpg][https://i.sstatic.net/lIRUP.jpg][https://i.sstatic.net/MLyT7.jpg]
has title: Using python tensorflow model identificate Captcha image , but some problem happen
has answer: http://stackoverflow.com/a/52326291

http://stackoverflow.com/comment/91745002
score: 0
type: QuestionComment
has text: @Nils Werner: kriging interpolation method is not available with NumPy
type: Comment
comment on: http://stackoverflow.com/q/52399781

http://stackoverflow.com/a/74420837
type: Answer
has body: X_train, y_train, train_labels =load_data(TRAIN_DIR, IMG_SIZE)
score: 0
answers question: http://stackoverflow.com/q/52417927

http://stackoverflow.com/a/52313780
accepted answer of: http://stackoverflow.com/q/52313457
has body: You can groupby by multiply columns and aggregate sum: x['quantity'] = pd.to_numeric(x['quantity'], errors='coerce') df = x.groupby(['dates','user','location'], as_index=False)['quantity'].sum() print (df) dates user location quantity 0 2018-09-03 user_01 GR 23.0 1 2018-09-03 user_02 SW 3.0 2 2018-09-03 user_03 POR 0.0 3 2018-09-03 user_04 PAN 222.0 EDIT: You can use Grouper by MS start of months - check offset aliases: x['dates'] = pd.to_datetime(x['dates']) x['quantity'] = pd.to_numeric(x['quantity'], errors='coerce') df = (x.groupby([pd.Grouper(key='dates', freq='MS'),'user','location'])['quantity'] .sum() .reset_index()) print (df) dates user location quantity 0 2018-09-01 user_01 GR 23.0 1 2018-09-01 user_02 SW 3.0 2 2018-09-01 user_03 POR 0.0 3 2018-09-01 user_04 PAN 222.0 Or use month or day or year: df = x.groupby([x['dates'].dt.month,'user','location'])['quantity'].sum().reset_index() print (df) dates user location quantity 0 9 user_01 GR 23.0 1 9 user_02 SW 3.0 2 9 user_03 POR 0.0 3 9 user_04 PAN 222.0
has comment: http://stackoverflow.com/comment/91575208
answers question: http://stackoverflow.com/q/52313457
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91575256
has comment: http://stackoverflow.com/comment/91575518
type: Answer
has comment: http://stackoverflow.com/comment/91574776
downvote count: 0
score: 1

http://stackoverflow.com/a/52273561
has body: You could try this: def PrintXY(x=None, y=None): print(''.join(['{:&lt;10,.3g}'.format(n) if n is not None else '' for n in [x, y]])) This you could easily expand to use x, y and z.
downvote count: 0
answers question: http://stackoverflow.com/q/52273431
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/q/52384190
accepted answer: http://stackoverflow.com/a/52384259
favorite count: 0
possible better answer: http://stackoverflow.com/a/52384489
has answer: http://stackoverflow.com/a/52384489
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: how to replace +xx in pandas str replace
has comment: http://stackoverflow.com/comment/91712416
has answer: http://stackoverflow.com/a/52384259
type: Question
answer count: 2
downvote count: 0
score: 1
has body: I'm using Python 2.7.12 and pandas 0.20.3, I have a data frame like below, I want to replace column called number, this column dtype is object, when I try to replace +91 in that column I'm getting error like below, number 0 +9185600XXXXX 1 +9199651XXXXX 2 99211XXXXX 3 99341XXXXX 4 +9199651XXXXX sre_constants.error: nothing to repeat full trace, Traceback (most recent call last): File "encoder.py", line 21, in df['number']=df['number'].str.replace('+91','') File "/home/hduser/.local/lib/python2.7/site-packages/pandas/core/strings.py", line 1574, in replace flags=flags) File "/home/hduser/.local/lib/python2.7/site-packages/pandas/core/strings.py", line 424, in str_replace regex = re.compile(pat, flags=flags) File "/usr/lib/python2.7/re.py", line 194, in compile return _compile(pattern, flags) File "/usr/lib/python2.7/re.py", line 251, in _compile raise error, v # invalid expression sre_constants.error: nothing to repeat But when I replace 91 it works as I expected, It's not working when I put + in prefix, Please help me to solve this problem. Error Occurs at, df['number']=df['number'].str.replace('+91','')
tagged with: pandas

swagger-ui
tag name: swagger-ui
tags question: http://stackoverflow.com/q/52414476
type: Tag

http://stackoverflow.com/a/52302095
accepted answer of: http://stackoverflow.com/q/52302060
type: Answer
has comment: http://stackoverflow.com/comment/91552233
downvote count: 0
has comment: http://stackoverflow.com/comment/91552250
has body: Simple df.replace('[^\d\.eE+-]', '', regex=True).astype(float) 0 1 2 3 0 10.0 41.00 -0.01 2.000 1 10.5 54.00 34.20 -0.076 2 65.0 -32.01 344.32 0.010 3 32.0 0.00 5.00 43.000 A little more robust df.replace('[^\d\.eE+-]', '', regex=True).apply(pd.to_numeric, errors='coerce') 0 1 2 3 0 10.0 41.00 -0.01 2.000 1 10.5 54.00 34.20 -0.076 2 65.0 -32.01 344.32 0.010 3 32.0 0.00 5.00 43.000
score: 5
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52302060
upvote count: 5

macos
tags question: http://stackoverflow.com/q/52406665
tags question: http://stackoverflow.com/q/52372490
tags question: http://stackoverflow.com/q/52408517
tags question: http://stackoverflow.com/q/52393611
tags question: http://stackoverflow.com/q/52365838
tags question: http://stackoverflow.com/q/52398022
tags question: http://stackoverflow.com/q/52426245
tags question: http://stackoverflow.com/q/52329776
tags question: http://stackoverflow.com/q/52278521
tags question: http://stackoverflow.com/q/52372992
tags question: http://stackoverflow.com/q/52281840
tags question: http://stackoverflow.com/q/52387297
tags question: http://stackoverflow.com/q/52347778
tags question: http://stackoverflow.com/q/52359157
tags question: http://stackoverflow.com/q/52378890
type: Tag
tags question: http://stackoverflow.com/q/52361275
tags question: http://stackoverflow.com/q/52361885
tags question: http://stackoverflow.com/q/52300930
tag name: macos

http://stackoverflow.com/q/52413533
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52413553
linked to: http://stackoverflow.com/q/3121979
favorite count: 0
has comment: http://stackoverflow.com/comment/91770924
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91770886
tagged with: python
has comment: http://stackoverflow.com/comment/91771245
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91770870
accepted answer: http://stackoverflow.com/a/52413553
downvote count: 1
type: Question
has title: How to sort list of lists by first value in inner list
score: -1
has body: So I have a list of lists [ ["c",2,5], ["bb",6,2], ["a",7,11], ... ] I want it sorted like the following : [ ["a",7,11], ["bb",6,2], ["c",2,5], ... ] Sorting by each lists first value. How would this be done? (So it was sorted by a &lt; bb &lt; c)

http://stackoverflow.com/a/52351425
has comment: http://stackoverflow.com/comment/91655811
type: Answer
score: 13
answers question: http://stackoverflow.com/q/52351312
has comment: http://stackoverflow.com/comment/91648162
downvote count: 0
has comment: http://stackoverflow.com/comment/91647958
has comment: http://stackoverflow.com/comment/91648047
upvote count: 13
has comment: http://stackoverflow.com/comment/91648212
has body: The first thing to keep in mind is Python is not Java. It's not as restrictive as other languages. As Guido says, "we're all adults here". Nothing really prevents you from doing most things in Python. The solution is "don't do that". However, there are several ways to do singletons. Another way, one that looks more "natural" to a user, is to use a factory function that looks like a class instantiation. Here's an example. class _Singleton: _instance = None def hello(self): print("Hello!") def Singleton(): if _Singleton._instance is None: _Singleton._instance = _Singleton() return _Singleton._instance s1 = Singleton() s2 = Singleton() assert s1 is s2
has comment: http://stackoverflow.com/comment/91647986
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52351312

http://stackoverflow.com/q/52409712
has body: I have a dataframe that contains hourly data: area date hour output H1 2018-07-01 07:00:00 150 H1 2018-07-01 08:00:00 150 H1 2018-07-01 09:00:00 100 H1 2018-07-01 11:00:00 150 H2 2018-07-01 09:00:00 100 H2 2018-07-01 10:00:00 50 H2 2018-07-01 11:00:00 50 H2 2018-07-01 12:00:00 150 but the data only contains row for the hours when there was output, how can I fill in the missing hours for each area with output 0? For example add two rows for H1: area date hour output H1 2018-07-01 10:00:00 0 H1 2018-07-01 12:00:00 0 I can assume that the min and max hour for all areas are the beginning and end of the sample period (in this case 7:00:00 and 12:00:00) Right now, I'm creating a dataframe containing all the hours from 7:00 to 12:00 for each area and then doing a merge of my data with that dataframe, and then filling the NaN with 0s. This is very slow as my data set can have millions of rows. Is there any better way of doing this?
score: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52432223
downvote count: 1
type: Question
upvote count: 5
has title: Fill in missing hours in a pandas dataframe
has answer: http://stackoverflow.com/a/52409895
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/91763286
favorite count: 0
possible better answer: http://stackoverflow.com/a/52409956
has answer: http://stackoverflow.com/a/52409956
tagged with: python
accepted answer: http://stackoverflow.com/a/52409895

http://stackoverflow.com/comment/91518863
has text: @KoYan Can you Please show me the whole data containing the end time column and please explain what you want, anyway, happy that i helped,
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52272490

http://stackoverflow.com/comment/91808878
has text: It worked for me now. When I gave the Xpath with ('//*[@id="LocationNotes_0__Note"]')- It did not work but it worked when I went thru all elements from Root(Absolute Path). I am not sure what is wrong with the 1st one.
comment on: http://stackoverflow.com/q/52429283
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/60532965
type: Answer
has body: I have stumbled upon this solution while having a similar issue as the OP, but with the AWS Glue Python Shell Job. Swati's answer above helped. If someone is trying to pass parameters to AWS Glue Python Shell Job, below is a template that worked for me: key = --JOB_NAME value= my_job key = --input value= 'xyz' AWS Glue Python Shell Job script: import sys from awsglue.utils import getResolvedOptions args = getResolvedOptions(sys.argv, ['JOB_NAME','input']) print("Job name is:{}, and input: {}".format(args["JOB_NAME"],args["input"]))
answers question: http://stackoverflow.com/q/52322381
score: 0
has comment: http://stackoverflow.com/comment/124836408

http://stackoverflow.com/a/63306634
has body: Adding to Divakar's answer above - if the original array A has a wider range than B, that will give you an 'index out of bounds' error. See: A = np.array([1,1,2,3,3,3,4,5,6,7,8,8,10,12,14]) B = np.array([1,2,8]) A[B[np.searchsorted(B,A)] != A] &gt;&gt; IndexError: index 3 is out of bounds for axis 0 with size 3 This will happen because np.searchsorted will assign index 3 (one-past-the-last in B) as the appropriate position for inserting in B the elements 10, 12 and 14 from A, in this example. Thus you get an IndexError in B[np.searchsorted(B,A)]. To circumvent that, a possible approach is: def subset_sorted_array(A,B): Aa = A[np.where(A &lt;= np.max(B))] Bb = (B[np.searchsorted(B,Aa)] != Aa) Bb = np.pad(Bb,(0,A.shape[0]-Aa.shape[0]), method='constant', constant_values=True) return A[Bb] Which works as follows: # Take only the elements in A that would be inserted in B Aa = A[np.where(A &lt;= np.max(B))] # Pad the resulting filter with 'Trues' - I split this in two operations for # easier reading Bb = (B[np.searchsorted(B,Aa)] != Aa) Bb = np.pad(Bb,(0,A.shape[0]-Aa.shape[0]), method='constant', constant_values=True) # Then you can filter A by Bb A[Bb] # For the input arrays above: &gt;&gt; array([ 3, 3, 3, 4, 5, 6, 7, 10, 12, 14]) Notice this will also work between arrays of strings and other types (for all types for which the comparison &lt;= operator is defined).
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52417929
downvote count: 0

http://stackoverflow.com/q/52395075
answer count: 1
has comment: http://stackoverflow.com/comment/91735609
has comment: http://stackoverflow.com/comment/91735427
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/91735447
has answer: http://stackoverflow.com/a/52395994
has body: so I have this exercise to do where it is asking me to get the age of someone, in terms of days, based off an input of their birthdate and current date. For instance, (2012,1,1,2012,2,28) should return 58 (Also I am not allowed to use any built in time functions). Here is my code so far: def leapyear(year): return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) def daysBetweenDates(year1, month1, day1, year2, month2, day2): age = 0 months31 = [1,3,5,7,8,10,12] months30 = [4,6,9,11] while year1 != year2 and month1 != month2 and day1 != day2: age += day2 day2 = 0 if day2 == 0: month2-=1 if month2 in months31: day2 += 31 month2 -= 1 if month2 in months30: day2 += 30 month2 -= 1 if month2 == 2: if leapyear(year2): day2 += 29 month2 -= 1 else: day2 += 28 month2 -= 1 else: year2 -= 1 month2 = 12 return age Anyways my problem is that whenever I try this function it keeps returning with 0, any help to fix this is appreciated. EDIT: Hey guys, so based off of your feedback I understood why my code was taking forever to run so I changed it up so it looks like this now: def leapyear(year): return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) def daysBetweenDates(year1, month1, day1, year2, month2, day2): # Your code here. age = 0 months31 = [1,3,5,7,8,10,12] months30 = [4,6,9,11] if day1 != day2: age = abs(day2-day1) day2 = day1 if month1 &gt; month2: while month1 != month2: if month2 in months31: age += 31 month2 += 1 if month2 in months30: age += 30 month2 += 1 if month2 == 2: if leapyear(year2): age += 29 month2 += 1 else: age += 28 month2 += 1 else: while month1 != month2: if month2 in months31: age += 31 month2 -= 1 if month2 in months30: age += 30 month2 -= 1 if month2 == 2: if leapyear(year2): age += 29 month2 -= 1 else: age += 28 month2 -= 1 while year1 != year2: if leapyear(year2): age += 365 year2 -= 1 else: age += 365 year2 -= 1 return age But the only problem is that for certain examples it's working while for others I am getting close to the answer …
type: Question
has title: Getting the age of someone based off input of birthdate and current date
accepted answer: http://stackoverflow.com/a/52395994
has comment: http://stackoverflow.com/comment/91735720
has comment: http://stackoverflow.com/comment/91735352

http://stackoverflow.com/a/52395705
has comment: http://stackoverflow.com/comment/91736602
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52395689
answers question: http://stackoverflow.com/q/52395689
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91736837
type: Answer
has comment: http://stackoverflow.com/comment/91736538
score: 1
upvote count: 1
has body: Use: data["observation"] = pd.np.where(data["Result1"] &gt; data["Result2"], "Class 1", "Class 2") That works if you imported pandas as pd (using import pandas as pd), otherwise, if you just used import pandas, then use pandas.np.where(...) Alternatively, to use the list comprehension syntax, which is what I think you were trying to do, use: data["observation"]=["Class 1" if i["Result1"] &gt;i["Result2"] else "Class 2" for _, i in data.iterrows()] However, this could be very inneficient for a large dataframe.

http://stackoverflow.com/q/52382999
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/52403071
tagged with: python-3.6
has title: how to implement a websocket aware reverse-proxy with aiohttp (python 3.6)
answer count: 1
has body: I am trying to implement an application specific reverse-proxy for jupyter notebooks using aiohttp. It works fine for http requests, but the websocket forwarding does not work. Requests from the browser arrive and get forwarded, but there are no responses from jupyter forthcoming. I assume my websocket client code somehow does not react to incoming messages from jupyter. The only indication on the jupyter side that something is amiss are messages like this: WebSocket ping timeout after 90009 ms. so here is my attempt at writing the proxy from aiohttp import web from aiohttp import client import aiohttp import logging import pprint logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) baseUrl = 'http://0.0.0.0:8888' mountPoint = '/fakeUuid' async def handler(req): proxyPath = req.match_info.get('proxyPath','no proxyPath placeholder defined') reqH = req.headers.copy() if reqH['connection'] == 'Upgrade' and reqH['upgrade'] == 'websocket' and req.method == 'GET': ws_server = web.WebSocketResponse() await ws_server.prepare(req) logger.info('##### WS_SERVER %s' % pprint.pformat(ws_server)) client_session = aiohttp.ClientSession() async with client_session.ws_connect(baseUrl+req.path_qs, headers = { 'cookie': reqH['cookie'] }, ) as ws_client: logger.info('##### WS_CLIENT %s' % pprint.pformat(ws_client)) async for server_msg in ws_server: logger.info('&gt;&gt;&gt; msg from browser: %s',pprint.pformat(server_msg)) if server_msg.type == aiohttp.WSMsgType.TEXT: await ws_client.send_str(server_msg.data) else: await ws_client.send_bytes(server_msg.data) async for client_msg in ws_client: logger.info('&gt;&gt;&gt; msg from jupyter: %s',pprint.pformat(client_msg)) if client_msg.tp == aiohttp.WSMsgType.TEXT: await ws_server.send_str(client_msg.data) else: await ws_server.send_bytes(client_msg.data) return ws_server else: async with client.request( req.method,baseUrl+mountPoint+proxyPath, headers = reqH, allow_redirects=False, data = await req.read() ) as res:…
favorite count: 0
tagged with: jupyter-notebook
tagged with: reverse-proxy
upvote count: 2
accepted answer: http://stackoverflow.com/a/52403071
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: aiohttp

http://stackoverflow.com/a/52396777
has body: Hey welcome to stackoverflow! I got your solution, however it's not very good and not a lot of effort, but I will tell you the algorithm so hopefuly you can make a better one than me. Basically all you have to say is if the ball's rectanglar area, is at an intersection with any of the paddles, bounce it (to bounce in this case just reverse the x velocity). To see if it is in intersection is the same way you checked if the ball was inside the screen, you just match the x and y values of the balls and paddles. I made the paddle's thin so that they basically only bounce on the actual paddle(tell me if you want this changed, and I will happily do it!). Heres the code, It was bad indentation but I fixed that, I do recommend you make you while loop mainly functions for readability as it is a bit long. #import and start up pygame import pygame import math import time pygame.init() #define colors BLACK = ( 0, 0, 0) WHITE = ( 255, 255, 255) GREEN = ( 0, 255, 0) RED = ( 255, 0, 0) BLUE = ( 0, 0, 255) PURPLE = (255, 0, 255) YELLOW = (255, 255, 0) TEAL = ( 0, 255, 255) BROWN = ( 70, 50, 30) #create window size = (800, 500) screen = pygame.display.set_mode(size) pygame.display.set_caption("Pong") done = False #manage time clock = pygame.time.Clock() #ball movement rect_x = 375 rect_y = 250 rect_change_x = 3 rect_change_y = 3 #paddle movement y_speed_1 = 0 y_speed_2 = 0 #paddle coords so we can track them in real time x_coord_1 = 70 x_coord_2 = 700 y_coord_1 = 200 y_coord_2 = 200 #score score_player_1 = 0 score_player_2 = 0 time.sleep(1) def display_score(): font = pygame.font.SysFont('System Bold', 35, True, False) text1 = font.render(str(score_player_1), True, WHITE) text2 = font.render(str(score_player_2), True, WHITE) screen.blit(text1, [375, 10]) screen.blit(text2, [425, 10]) def player_win(): font = pygame.font.SysFont('System Bold', 40, True, False) player_1_win = font.render("Player 1 Wins!", True, WHITE) player_2_win = font.render("Player 2 Wins!", True, WHITE) if score_…
has comment: http://stackoverflow.com/comment/91739634
downvote count: 0
has comment: http://stackoverflow.com/comment/91739439
has comment: http://stackoverflow.com/comment/91739565
answers question: http://stackoverflow.com/q/52396469
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/91738422

http://stackoverflow.com/comment/91625913
type: QuestionComment
score: 1
has text: @DanMašek I looked at my code some more and indeed no image is being passed into `detectAndCompute`. The code I use to crop an image before running `detectAndCompute` seems to be going out of bounds so no image is produced thus why it appears as none when `detectAndCompute` is run. Thanks for all your help.
comment on: http://stackoverflow.com/q/52321305
type: Comment

http://stackoverflow.com/comment/91655231
type: Comment
type: QuestionComment
has text: @oren_isp yeah... that doesn't seem quite consistent with the logic based on your input and my original question... you probably want to detail out the rules for grouping in your question as well...
comment on: http://stackoverflow.com/q/52355260
score: 0

http://stackoverflow.com/comment/91533468
type: AnswerComment
has text: Thanks for that! Indeed, this works nicely. The thing is that I would like to add 5% of a value from another row, where Version = S1 and the Channel is Phone instead of e.g. SMS. df.loc[[((df['Version'] == 'S1') & (df['Weeknum'] == '2019-13') & (df['Channel']=='Phone'), 'contacts'] = df['contacts'] + df['contacts'](<- This value from the row where Version =S1, Week = 2019-13 but channel = "SMS") * 0.05
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52292724

http://stackoverflow.com/q/52351261
has answer: http://stackoverflow.com/a/52361034
type: AnsweredQuestion
has body: I have the code that prints all image_url that i want to download Next I want to save them in a local folder with folder_name=scrap_images with desired image_name=uni_name that is also in the output can you help me out. response = requests.get('https://www.eduvision.edu.pk/admissions.php? discipline_type=Social-Sciences&amp;sub_level=7&amp;city=&amp;pageNo=2',headers=header) soup = BeautifulSoup(response.content, 'html.parser') data=soup.findAll('div',attrs={'class':'col-lg-12 col-xs-12'})[:-1] for d in data: uni_name,comma,city = (d.findAll('a')[1].text).partition(',') print(uni_name) admis_img = d.img['src'] if(d.img['src']=="images_post/nust.jpg"): admis_img= "https://www.eduvision.edu.pk/"+d.img['src'] print(admis_img) else: print(admis_img)
tagged with: screen-scraping
has title: bs4 scraping: download images and save them in local folder with desired name
tagged with: image
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/52361034
favorite count: 0
tagged with: beautifulsoup
score: 0
linked to: http://stackoverflow.com/q/51170871
tagged with: python
tagged with: download
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/91676311
comment on: http://stackoverflow.com/q/52365838
type: Comment
type: QuestionComment
has text: Possible duplicate of [sasl/saslwrapper.h:22:23: fatal error: sasl/sasl.h: No such file or directory](https://stackoverflow.com/questions/48562383/sasl-saslwrapper-h2223-fatal-error-sasl-sasl-h-no-such-file-or-directory)
score: 1

pyside2
tags question: http://stackoverflow.com/q/52370288
tags question: http://stackoverflow.com/q/52342123
tags question: http://stackoverflow.com/q/52412102
tags question: http://stackoverflow.com/q/52429399
type: Tag
tags question: http://stackoverflow.com/q/52426437
tags question: http://stackoverflow.com/q/52364789
tag name: pyside2
tags question: http://stackoverflow.com/q/52391008
tags question: http://stackoverflow.com/q/52337856
tags question: http://stackoverflow.com/q/52291585
tags question: http://stackoverflow.com/q/52283469
tags question: http://stackoverflow.com/q/52311576
tags question: http://stackoverflow.com/q/52343873

http://stackoverflow.com/comment/91582362
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52317485
type: Comment
has text: Are you not using `matplotlib` are you interested in plotting within `seaborn`?

http://stackoverflow.com/comment/91752238
type: Comment
type: QuestionComment
has text: Sounds like you first want to resample your groups such that a value is available for each timestamp for each group (e.g. forward fill the values). Then you should be able to easily calculate the cumulative sums you are after.
score: 0
comment on: http://stackoverflow.com/q/52382503

http://stackoverflow.com/q/52291007
has comment: http://stackoverflow.com/comment/91544296
tagged with: performance
answer count: 0
tagged with: rsa
has title: inneficiency creating public and private keys
upvote count: 1
has comment: http://stackoverflow.com/comment/91538509
type: Question
has comment: http://stackoverflow.com/comment/91544175
downvote count: 0
tagged with: runtime
has comment: http://stackoverflow.com/comment/91544854
has body: this code is simply to create a public and private key pair (and use it on a single character) but if i use prime numbers greater than about 1500 then it takes far to long, to create these keys and encrypt/decrypt a single character. my code is: from math import gcd import random prime_numbers=[1223, 1033] def phi_function(x): x=(p-1)*(q-1) return(x) def is_coprime(x, y): z=gcd(x, y) if z==1: return True if z!=1: return False def encryption_key_generator(x, y): list_p=[] for i in range(1, x): i2 = i+1 if is_coprime(i2, y)==True: if is_coprime(i2, phi)==True: list_p.append(i+1) z=(list_p[len(list_p)-(random.randint(1, len(list_p)))], y) return z def decryption_key_generator(x, y, z): list_p=[] for i in range(z): i2=i+1 if (x*i2)%y == 1: list_p.append(i2) q=(list_p[len(list_p)-1], z) return (q) p=prime_numbers[0] q=prime_numbers[1] n=p*q phi=phi_function(n) encryption_key=encryption_key_generator(phi, n) decryption_key=decryption_key_generator(encryption_key[0], phi, n) #print('encryption_key = '+str(encryption_key)) #print('decryption_key = '+str(decryption_key)) x=input('text: ') x1=ord(x) y=(x1**(encryption_key[0]))%(encryption_key[1]) y=chr(y) y1=ord(y) z=(y1**(decryption_key[0]))%(decryption_key[1]) print(chr(z)) my question is, are there any methods or built in functions i can use here to make it run faster. (if it makes any difference to the solution, its going to be used for a secure messaging app i'm in the process of building)
tagged with: public-key-encryption
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91572747
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/52318674
has comment: http://stackoverflow.com/comment/91585399
upvote count: 2
has comment: http://stackoverflow.com/comment/91585118
has comment: http://stackoverflow.com/comment/91584811
has body: Broadcast the second array, making use of vectorized operations. Setup a = np.array([[5, 3, 2, 1, 4, 2], [7, 0, 3, 5, 7, 9], [9, 8, 0, 2, 4, 8], [3, 5, 2, 0, 1, 9], [7, 7, 4, 1, 7, 6], [5, 9, 8, 9, 6, 1]]) d = (a - a[:, None])**2 np.sqrt(d.sum(-1)).round(2) array([[ 0. , 9.38, 9.06, 8.19, 7. , 11.87], [ 9.38, 0. , 9.8 , 10.15, 8.66, 13.82], [ 9.06, 9.8 , 0. , 7.94, 5.92, 13.53], [ 8.19, 10.15, 7.94, 0. , 8.37, 15.03], [ 7. , 8.66, 5.92, 8.37, 0. , 10.68], [11.87, 13.82, 13.53, 15.03, 10.68, 0. ]]) Performance a = np.random.rand(100, 100) %%timeit d = (a - a[:, None])**2 np.sqrt(d.sum(-1)).round(2) 7.68 ms ± 75.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) %%timeit distance = np.zeros((100, 100)) for i, el1 in enumerate(a): for j, el2 in enumerate(a): distance[i][j] = np.sqrt(np.sum(np.square(np.subtract(el1, el2)))) 51.1 ms ± 1.97 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
has comment: http://stackoverflow.com/comment/91586893
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52318603
has comment: http://stackoverflow.com/comment/91585171
has comment: http://stackoverflow.com/comment/91585367
has comment: http://stackoverflow.com/comment/91584790
answers question: http://stackoverflow.com/q/52318603
type: Answer
score: 2

http://stackoverflow.com/comment/91574066
score: 1
comment on: http://stackoverflow.com/a/52312381
type: AnswerComment
has text: Nice move but if `input size = (300, 226)` rate will be `0.3840476863212842` and output is `(115, 87)` resolution is (115x87) = 10005
type: Comment

http://stackoverflow.com/a/52370423
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52369174
has body: TensorFlow variables are 32 bit floats by default, and they do not have enough precision to track the difference dt, which is too small in relation to the rest of values. Use dtype=tf.float64 to increase the precision and you will see the correct results: import numpy as np import tensorflow as tf import matplotlib.pyplot as plt with tf.Graph().as_default(): a = tf.Variable(1, name="Var_a", dtype=tf.float64) dx = tf.Variable(1.33333, name='dx', dtype=tf.float64) dt = tf.Variable(5e-10, name='dt', dtype=tf.float64) dz = tf.Variable(1.0, name='dz', dtype=tf.float64) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) a = dt+dx a = a-dz print dx.eval() print dt.eval() print (dt+dx).eval() print (dx+dt).eval() print a.eval() writer = tf.summary.FileWriter("/tmp/tensorlog") writer.add_graph(sess.graph) Output: 1.33333 5e-10 1.3333300005 1.3333300005 0.33333000049999995 Note however that using tf.float64 instead of tf.float32 values comes at a cost in terms of memory and time, so use tf.float64 only when you really require high precision. In general, 32-bit float values are precise to about 7 decimal places while 64-bit float values are precise to about 15 decimal places.
downvote count: 0

http://stackoverflow.com/comment/91599180
type: Comment
has text: Nope. `file` is (I believe) a file name. You can open the file, alter it, delete it, or anything. The `file` variable will still contain the file name. Editing the `files` array is a completely different story, and this should not be necessary.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52326066

http://stackoverflow.com/comment/91867911
has text: Sorry @Able Archer, I have almost zero knowledge on dataframe so I can't help you there.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52427897
type: Comment

http://stackoverflow.com/q/52374197
upvote count: 7
has body: I trying to get text from captcha image using opencv. Problem is text are masked with noise and it is complex to process with those horizontal line/noise. Original image My processed image : not sure how to remove those horizontal lines and get text Code : import numpy as np import cv2 # Load an color image in grayscale img = cv2.imread('captcha.jpg',0) #display image in window #cv2.imshow('image',img) #@param - windowname, image to be displayed horizontal_inv = cv2.bitwise_not(img) #perform bitwise_and to mask the lines with provided mask masked_img = cv2.bitwise_and(img, img, mask=horizontal_inv) #reverse the image back to normal masked_img_inv = cv2.bitwise_not(masked_img) cv2.imshow("masked img", masked_img_inv) cv2.imwrite("result2.jpg", masked_img_inv) cv2.waitKey(0) # time for window to show image in milliseconds - 0 is infinite wait cv2.destroyAllWindows() Edit : how to handle if text are in light color
tagged with: python
tagged with: ocr
has answer: http://stackoverflow.com/a/52377897
accepted answer: http://stackoverflow.com/a/52377897
downvote count: 0
tagged with: opencv
type: AnsweredQuestion
tagged with: captcha
score: 7
tagged with: image-processing
type: Question
answer count: 1
has title: Remove unwanted lines in captcha text - opencv - python
favorite count: 0
has comment: http://stackoverflow.com/comment/91694858

http://stackoverflow.com/a/52387260
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52387191
type: Answer
answers question: http://stackoverflow.com/q/52387191
has body: For large files, pandas can read them in chunks. chunksize = 10 ** 6 for chunk in pd.read_csv(filename, chunksize=chunksize): process(chunk)
score: 5
upvote count: 5
downvote count: 0

http://stackoverflow.com/a/52333650
type: Answer
has body: Assuming you have this data in the clipboard Day Date Data Mo 2018-08-06 blah Mo 2018-08-06 blah Mo 2018-08-06 blah Tu 2018-08-07 blah Try import pandas as pd df = pd.read_clipboard().set_index(['Day', 'Date']) to get a multiindexed example Then change the Date to Datetime df2 = df.reset_index() df2.Date = pd.to_datetime(df2.Date, yearfirst=True) Afterwards you can set the multiindex again, if you want. Note, check out the documentation on to_datetime if your datetime string is formatted differently. It assumes month first, unless you set dayfirst or yearfirst to True.
answers question: http://stackoverflow.com/q/52332822
score: 0

http://stackoverflow.com/a/70464979
type: Answer
has body: One thing that seems to work well that isn't mentioned.. Ajax Call Success: success: function (response) { if("redirect" in response){ window.location.href = response["redirect"]; } } Instead of using HttpResponseRedirect you use this in your view return JsonResponse({"redirect":'/customer/buyer'}, status=200)
score: 0
answers question: http://stackoverflow.com/q/52318358

http://stackoverflow.com/q/52365943
has comment: http://stackoverflow.com/comment/91677423
has comment: http://stackoverflow.com/comment/91676176
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91677382
has comment: http://stackoverflow.com/comment/91676312
type: Question
has comment: http://stackoverflow.com/comment/91676184
has answer: http://stackoverflow.com/a/52366346
has comment: http://stackoverflow.com/comment/91679549
score: 0
answer count: 2
has body: here, i need to get two values from user and save that output in a spread sheet format. the mcve of my code is : while True: a=input('enter the string') print(a) b=input('enter the number') print(b) the sample output is: enter the stringa a enter the number2 2 enter the stringb b enter the number4 4 enter the string I need to assign each integer value to the respective string in an spreadsheet
has comment: http://stackoverflow.com/comment/91676139
has answer: http://stackoverflow.com/a/52367824
has title: converting python output in spread sheet format
tagged with: python

http://stackoverflow.com/a/52312353
answers question: http://stackoverflow.com/q/52303696
upvote count: 2
score: 2
downvote count: 0
has body: You can use a generator expression with next and enumerate: s = pd.Series([False, False, True, True, False, False]) res = len(s) - next(idx for idx, val in enumerate(s[::-1], 1) if val) # 3 This will be more efficient for large series with a True value towards the end.
type: Answer

http://stackoverflow.com/comment/91731094
type: AnswerComment
type: Comment
has text: @Borodin In Python 3, many functions that previously returned lists in early versions now return iterators. And for this task, I think an iterator is appropriate, since it doesn't take many key letters in the input string for the output to become quite large. FWIW, I'm not desperate for points, and I left school decades ago. I was just trying to help the OP.
score: 3
comment on: http://stackoverflow.com/a/52383460

http://stackoverflow.com/comment/91494388
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52273378
has text: you can simply subtract like this, `print df1-df2`. Note df2 assigns df1's data

http://stackoverflow.com/comment/91641885
type: QuestionComment
comment on: http://stackoverflow.com/q/52348199
score: 0
has text: Thanks a lot, I have never felt so stupid. It worked!
type: Comment

http://stackoverflow.com/comment/91665466
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52353581
has text: No variations in results? Can you post some examples of the result you have created and the code implementations?

http://stackoverflow.com/q/52425077
has title: Uploading large file to S3/D42 as parallel multipart with python boto
upvote count: 1
type: Question
tagged with: boto
tagged with: amazon-s3
tagged with: multipart
has body: I am trying to upload a 400 GB .ibd file of MySql DB machine into D42/S3. I am using set_contents_from_file function of Python boto. But it is taking a lot of time and I cannot see the progress (about how much uploaded/left). Does anyone have any python script to use thread or parallel multipart upload? It's a very simple use case for end-user, but boto's documentation doesn't have any function like this.
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52448304
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 1

http://stackoverflow.com/comment/91713205
has text: Oh, I forgot about it. This work pretty well. I just realized that I put `out.release()` in the loop, that's why it read only the first frame. Thank you so much for helping me out.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52373874
type: Comment

http://stackoverflow.com/comment/91500290
score: 0
type: AnswerComment
has text: So you need to preprocess your dataset. Maybe you can solve it by doing `w_alarms[w_alarms.site_id.astype(int) > 3].groupby('site_id')['issue'].count()` but you should really construct a proper dataset first and not on the fly.
comment on: http://stackoverflow.com/a/52275644
type: Comment

http://stackoverflow.com/comment/91620833
type: QuestionComment
type: Comment
has text: Thanks @Pekka but I took a look in that link before and none. Can't find a variable with that information.
comment on: http://stackoverflow.com/q/52329164
score: 0

django-1.11
tags question: http://stackoverflow.com/q/52278610
tag name: django-1.11
type: Tag

http://stackoverflow.com/a/52424323
has comment: http://stackoverflow.com/comment/91858998
downvote count: 0
has body: You can set different log levels for different loggers using setLevel. You could set the loggers you are not interested in to CRITICAL and the ones you are to something lower such as DEBUG: import logging logger_A = logging.getLogger("A") logger_B = logging.getLogger("B") logger_A.setLevel(logging.DEBUG) logger_B.setLevel(logging.CRITICAL) logger_A.error("this is A error") logger_B.error("this is B error")
answers question: http://stackoverflow.com/q/52424001
has comment: http://stackoverflow.com/comment/91837261
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/52366314
has comment: http://stackoverflow.com/comment/91677122
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91677855
has comment: http://stackoverflow.com/comment/91676984
has comment: http://stackoverflow.com/comment/91685020
score: 0
has title: Flask installed in server, but still receiving "no module named flask" error
accepted answer: http://stackoverflow.com/a/52380161
has comment: http://stackoverflow.com/comment/91677569
has body: I'm trying to deploy a small test app to a server, but even though Flask is installed on the server, I'm still getting a "no module named flask" error every time I try to run the app on the server. This is the error message I get, and the server telling me that Flask is already installed . I have looked at some of the other solutions on this site, but I have to admit I am a complete noob and can't even understand what some of those solutions mean. There are some mentions of the path files being wrong, but I'm not sure what that means or how to fix it on the server. Can anyone explain what might have gone wrong and how to fix it?
type: Question
has comment: http://stackoverflow.com/comment/91677071
tagged with: flask
linked to: http://stackoverflow.com/q/24661649
linked to: http://stackoverflow.com/q/41415629
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91677978
has comment: http://stackoverflow.com/comment/91678207
linked to: http://stackoverflow.com/q/17309288
has comment: http://stackoverflow.com/comment/91676887
has comment: http://stackoverflow.com/comment/91678246
answer count: 1
has answer: http://stackoverflow.com/a/52380161
has comment: http://stackoverflow.com/comment/91677478
has comment: http://stackoverflow.com/comment/91683404

http://stackoverflow.com/q/52337608
tagged with: django
downvote count: 1
has answer: http://stackoverflow.com/a/52350715
has body: I'm making a Django app and I have a view that display both sides of an object_set (a reverse many to many). Because of this, I want to query all of the objects on both sides at the same time. Specifically speaking, I want to have all of the Signup objects that are associated with each Event. (The view page format should look like this.) Event (0) -- Signup (0.0) -- Signup (0.1) -- Signup (0.2) -- Signup (0.3) Event (1) -- Signup (1.0) -- Signup (1.1) Event (3) -- Signup (3.0) -- Signup (3.1) -- Signup (3.2) -- Signup (3.3) ... The code is as follows: class TournamentDetailView(DetailView): model = Tournament def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) tournament_id = self.get_object().pk events = Event.objects.annotate( cached_signups=( Signup.objects .filter(event_id=OuterRef('pk'), tournament_id=tournament_id, dropped=False) .order_by('created') .defer('tournament') ) ).all() context['events'] = events return context Here's the traceback: Traceback: File "C:\Users\werdn\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\werdn\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\werdn\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\werdn\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in view 69. return self.dispatch(request, *args, **kwargs) File "C:\Users\werdn\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in dispatch 89. return handler(request, *args, **kwargs) File "C:\Users\werdn\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\ge…
has answer: http://stackoverflow.com/a/52346551
accepted answer: http://stackoverflow.com/a/52350715
has comment: http://stackoverflow.com/comment/91638459
possible better answer: http://stackoverflow.com/a/52346551
score: 2
type: AnsweredQuestion
has title: AttributeError: 'Query' object has no attribute 'contains_aggregate'
has answer: http://stackoverflow.com/a/68619312
favorite count: 0
type: Question
tagged with: python
upvote count: 3
answer count: 3

http://stackoverflow.com/comment/92860818
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52413102
type: Comment
has text: @OnurOzbek Thanks. And sure – I have already done so. You had a downvote before that. So right now this equals to null...

http://stackoverflow.com/comment/91660710
type: Comment
type: QuestionComment
has text: @today: Only 2 epochs, but I would expect some significant changes in loss at the beginning of training. No I have not tried other optimizer, as this was the one given by the keras example, and I did not think the issue would be with the optimizer type or its settings, but with the layers (see my updated, more specific questions).
comment on: http://stackoverflow.com/q/52357812
score: 0

http://stackoverflow.com/comment/91616959
type: QuestionComment
comment on: http://stackoverflow.com/q/52334909
has text: You're setting all nan values to a single value?
score: 0
type: Comment

http://stackoverflow.com/a/52399700
has comment: http://stackoverflow.com/comment/91779502
answers question: http://stackoverflow.com/q/52398924
upvote count: 1
has comment: http://stackoverflow.com/comment/91779117
has body: You can use diff from pandas to get the difference between two rows Here is a sample code. In [1]: import pandas as pd In [2]: from io import StringIO In [3]: data = StringIO('''Order,States,modified_at ...: 1,Resolved,2018-06-18T15:05:52.2460000 ...: 1,Edited,2018-05-24T21:44:07.9030000 ...: 1,Pending PO Creation,2018-06-06T19:52:51.5990000 ...: ''') In [4]: df = pd.read_csv(data, sep=',') In [5]: df['modified_at'] = pd.to_datetime(df['modified_at']) #convert the type to datetime In [6]: df Out[6]: Order States modified_at 0 1 Resolved 2018-06-18 15:05:52.246 1 1 Edited 2018-05-24 21:44:07.903 2 1 Pending PO Creation 2018-06-06 19:52:51.599 In [7]: df['diff'] = df['modified_at'].diff() #get the diff and add to a new column In [8]: df Out[8]: Order States modified_at diff 0 1 Resolved 2018-06-18 15:05:52.246 NaT 1 1 Edited 2018-05-24 21:44:07.903 -25 days +06:38:15.657000 2 1 Pending PO Creation 2018-06-06 19:52:51.599 12 days 22:08:43.696000
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/comment/91552986
comment on: http://stackoverflow.com/a/52301367
type: AnswerComment
has text: thank you very much for the help it works wonderfully. Saludos desde Ecuador
score: 0
type: Comment

http://stackoverflow.com/q/52339864
has comment: http://stackoverflow.com/comment/91626980
answer count: 2
upvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52339889
has answer: http://stackoverflow.com/a/52340106
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
has title: How to make a list from 2 arrays in python?
has comment: http://stackoverflow.com/comment/91626984
downvote count: 1
type: Question
has body: I have two arrays, I want to make a list with its first element as [first element of array one, 'first element of array 2'] and so on. Basically each elements of a list will be a list. lista = [1, 2, 3, 4] listb = [a, b, c, d] Desired Output: listc = [1a, 2b, 3c, 4d]
score: -1

http://stackoverflow.com/a/52329204
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91605929
type: Answer
has comment: http://stackoverflow.com/comment/91605565
has body: From the docs: Direct Connection The slot is invoked immediately, when the signal is emitted. The slot is executed in the emitter's thread, which is not necessarily the receiver's thread. By specifying Qt.DirectConnection when connecting your signal you're causing the connected method to be called by your CaptureScreen thread, meaning that you're creating a QPixmap outside of your GUI thread. Does changing the connection type to Qt.QueuedConnection fix things?
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52328859
answers question: http://stackoverflow.com/q/52328859

http://stackoverflow.com/comment/91556202
has text: Thank you anky! Still, it doesn't work for me. Could you please take a look to the below and advise on what I'm doing wrong? file_list = [os.path.join(r,file) for r,d,f in os.walk('C:/Users/JG/work/files_cargo.xlsx') for file in f] for file in list(file_list): f = pd.read_excel(file) sheet_names = f.sheet_names for i in list(sheet_names): dataframe = pd.read_excel(f,i) type(dataframe) NameError: name 'dataframe' is not defined
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52287447

http://stackoverflow.com/comment/91587316
has text: could you please explain me a little bit the structure of the first cumprod approach? it looks interesting
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52319816
score: 0

http://stackoverflow.com/comment/91667655
type: Comment
comment on: http://stackoverflow.com/a/52361628
type: AnswerComment
has text: @jaykodeveloper - just change solution for get original ordering
score: 0

http://stackoverflow.com/q/52322221
accepted answer: http://stackoverflow.com/a/52323247
type: Question
answer count: 1
score: 0
has body: I'm new to Python, and trying to scrape a dynamically generated table. I've got far enough to open the page, input a search, and have the results table show off. I'm having trouble scraping the results, and I noticed the specific text of the results isn't part of the HTML. Here's my code so far, thanks for any and all help. ## module importation import os, requests, bs4, openpyxl, webbrowser, lxml, html5lib, re from selenium import webdriver from selenium.webdriver.common.keys import Keys print('Type in the FIRST NAME of the individual.') #I've been using [Mike] here. firstName = input() print('Thanks. Now type in the individual\'s LAST NAME.') #I've been using [Jones] here. lastName = input() browser = webdriver.Firefox(executable_path='/usr/local/bin/geckodriver') #BoP inmate locator #Goes to BoP website browser.get('https://www.bop.gov/inmateloc/') res = requests.get('https://www.bop.gov/inmateloc/') #Clicks Search by name option (just in case) searchByNameButton = browser.find_element_by_css_selector("#ui-id-1") searchByNameButton.click() # clicks the Search by Name Button #enters first name bopSearchFirstNameElem = browser.find_element_by_css_selector('#inmNameFirst') bopSearchFirstNameElem.send_keys(firstName) #enters last name bopSearchLastNameElem = browser.find_element_by_css_selector('#inmNameLast') bopSearchLastNameElem.send_keys(lastName) # Clicks search searchSubmitButton = browser.find_element_by_css_selector('#searchNameButton') searchSubmitButton.click() # clicks the Search Button on the BoP page # Scrape table results bopResultsPage = bs4.BeautifulSoup(res.text, 'html.parser')
tagged with: python
has answer: http://stackoverflow.com/a/52323247
has title: Using python 3 and Selenium to scrape a dynamicaly generated table
tagged with: selenium
tagged with: web-scraping
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91592182

http://stackoverflow.com/comment/91604614
type: Comment
comment on: http://stackoverflow.com/a/52328230
score: 0
type: AnswerComment
has text: Then please answer my question in the comments. What does len(request.form[img]) and nparr.shape return? Before that, did you check img variable is correct at client side?

http://stackoverflow.com/comment/91751353
score: 1
type: QuestionComment
type: Comment
has text: As mentioned above - no there isn't. That's just not how HTTP works - Django or no Django.
comment on: http://stackoverflow.com/q/52403371

http://stackoverflow.com/a/52326606
answers question: http://stackoverflow.com/q/52326434
has comment: http://stackoverflow.com/comment/131788754
type: Answer
score: 2
downvote count: 0
has body: I imagine that something like this would do: import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText def send_email(temperature): fromaddr = "sender@gmail.com" toaddr = "recipient@gmail.com" msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "Alert: Server Room " body = "Server room current temprature is : " + temperature msg.attach(MIMEText(body, 'plain')) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(fromaddr, "password") text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit() f = open("temp_log.txt", "r") content = f.read() temp = content.split(' ')[1] if float(temp) &gt; 35: send_email(temp)
upvote count: 2

http://stackoverflow.com/comment/125806680
comment on: http://stackoverflow.com/a/57731053
score: 1
type: AnswerComment
has text: Doesn't work for MacOs
type: Comment

http://stackoverflow.com/comment/91743067
type: Comment
comment on: http://stackoverflow.com/q/52399520
has text: Check the type of just `Graph.node` (without `()`)
score: 0
type: QuestionComment

http://stackoverflow.com/q/52295279
score: 1
upvote count: 1
type: Question
duplicate of: http://stackoverflow.com/q/27975069
duplicate of: http://stackoverflow.com/q/19913659
has answer: http://stackoverflow.com/a/52295311
has title: python dataframe column apply a function
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/52295311
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/19913659
tagged with: python
type: AnsweredQuestion
has body: I have a dataframe import pandas as pd data = {'A': ['SA01', '0007', 'SA06', '0198', 'SA06'], 'B': [2012, 2012, 2013, 2014, 2014], } df = pd.DataFrame(data) df = A B SA01 2012 0007 2012 SA06 2013 0198 2014 SA06 2014 I want to use df.apply or other functions of pandas to add a df['C'] as follows: df = A B C SA01 2012 M 0007 2012 F SA06 2013 M 0198 2014 F SA06 2014 M If df['A'] contains substring 'SA' then df['C'] is 'M' else 'F'. How to solve?

http://stackoverflow.com/a/52359429
score: 0
has comment: http://stackoverflow.com/comment/91663579
type: Answer
answers question: http://stackoverflow.com/q/52357358
has comment: http://stackoverflow.com/comment/91714892
has body: Store the id of the message in the data attribute (see here: https://www.w3schools.com/tags/att_global_data.asp) Than you can use jquery to get the data, for example id $(this).data("id") Than you can call the server to retrieve the message using ajax and populate the right part of page.

http://stackoverflow.com/q/52355110
favorite count: 0
tagged with: multidimensional-array
has comment: http://stackoverflow.com/comment/91656650
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52355328
downvote count: 1
has body: I currently have a 2d array like this array = [ [a1, a2, a3, a4], [b1, b2, b3, b4], [c1, c2, c3, c4], [d1, d2, d3, d4], ] want I want to do is change the array to this: array = [ [b1, b2, b3, b4], [c1, c2, c3, c4], [d1, d2, d3, d4], [a1, a2, a3, a4], ] I would preferably like a method where I can save the 'a' row to a variable and remove it from the 2d array, and then add it back to the end later. thanks for any help.
tagged with: 2d
score: -1
has answer: http://stackoverflow.com/a/52355176
type: Question
has title: moving rows in 2D arrays
has comment: http://stackoverflow.com/comment/91654843
answer count: 2
upvote count: 0
tagged with: arrays

http://stackoverflow.com/comment/91712530
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52384149
has text: Given that `C` is overwritten at any iteration, the fastest equivalent of the code you posted so far is: `C = np.isin(A[N - 1, :], B[N - 1, :]`. But I guess that this is not what you want, and you should be more precise in your question.
score: 0

http://stackoverflow.com/comment/91653923
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52354596
has text: Yes there is typo in my example, I fixed that. Your second assumption is correct, I want to combine consecutive ones. But my final list for a given day should be like [0, 4.00, 6:59, 13:00, 14:59, 21:00, 22:59]

http://stackoverflow.com/a/52418317
has comment: http://stackoverflow.com/comment/92128026
has body: I believe need check if format of datetimes is correct - maybe necessary parameter dayfirst=True: M = pd.read_csv('file.csv', sep='\s+', parse_dates=True, index_col= 'Date', dayfirst=True) print(M.head()) Temp Date 1895-01-01 7.72 1895-01-02 5.50 1895-01-03 13.56 1895-01-04 17.83 1895-01-05 20.39 Then if necessary count mean per year and month: MTT = M['Temp'] - M.groupby(M.index.strftime("%Y%m"))['Temp'].transform('mean') print (MTT.head(10)) Date 1895-01-01 -8.8775 1895-01-02 -11.0975 1895-01-03 -3.0375 1895-01-04 1.2325 1895-01-05 3.7925 1895-01-06 8.9025 1895-01-07 9.2925 1895-01-08 8.5125 1895-01-09 6.0725 1895-01-10 -0.7675 Name: Temp, dtype: float64 Or per months only: MTT = M['Temp'] - M.groupby(M.index.month)['Temp'].transform('mean') print (MTT.head(10)) Date 1895-01-01 -9.342167 1895-01-02 -11.562167 1895-01-03 -3.502167 1895-01-04 0.767833 1895-01-05 3.327833 1895-01-06 8.437833 1895-01-07 8.827833 1895-01-08 8.047833 1895-01-09 5.607833 1895-01-10 -1.232167 Name: Temp, dtype: float64
has comment: http://stackoverflow.com/comment/91816916
has comment: http://stackoverflow.com/comment/91817290
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52417478
has comment: http://stackoverflow.com/comment/92128164
has comment: http://stackoverflow.com/comment/91817241
downvote count: 0

http://stackoverflow.com/comment/91560368
type: AnswerComment
score: 0
type: Comment
has text: I notice when I try to use the toggled signal with a partial function, passing an extra variable, I get an error that the slotted method is throwing an error: getting TypeError: light_label_event() takes exactly 2 arguments (3 given). What are the 3 arguments being passed? button.connect(partial(event,variable)). Thank you.
comment on: http://stackoverflow.com/a/52306342

http://stackoverflow.com/q/52347369
has comment: http://stackoverflow.com/comment/91640153
has comment: http://stackoverflow.com/comment/91640199
tagged with: date
has answer: http://stackoverflow.com/a/52347414
type: Question
has comment: http://stackoverflow.com/comment/91640178
has comment: http://stackoverflow.com/comment/91640293
has answer: http://stackoverflow.com/a/52347496
has body: If I input "1995y 05m 05d", then I want to make a program that prints "950505". More example: "1949y 05m 23d" --> "490523". import re Birthday = str(input("insert your birth&lt;(ex) xxxxy **m 00d&gt; : ")) p= re.sub('[ymd ]','',Birthday) print(p) #result is "xxxx**00" here is my code. How do I fix it? any solutions?
has answer: http://stackoverflow.com/a/52347387
tagged with: regex
score: 1
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/52347464
answer count: 5
type: UnansweredQuestion
tagged with: python
has title: python: how can I make this code with regular expression?
downvote count: 1
has answer: http://stackoverflow.com/a/52347442
has comment: http://stackoverflow.com/comment/91640229
has comment: http://stackoverflow.com/comment/91640273
has comment: http://stackoverflow.com/comment/91640252

http://stackoverflow.com/a/52396411
accepted answer of: http://stackoverflow.com/q/52396291
type: AcceptedAnswer
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52396291
has body: You should use the endswith function to check whether the last "n" characters in the cube are equal to the string representation of the number you are passed. You could thus do: print(str(num_cube).endswith(num)) The way you have currently implemented it, you are "hard coding" the expected length of the number read from the stdin and are thus assuming it to always be of length 1. To correct your code, you would do the following: &gt;&gt;&gt; num = "24" &gt;&gt;&gt; num_cube = str(pow(int(num), 3)) &gt;&gt;&gt; num_cube[len(num_cube) - len(num):] == num True &gt;&gt;&gt; num_cube[-len(num):] == num # negative indexing True

http://stackoverflow.com/comment/91526002
comment on: http://stackoverflow.com/q/52287641
has text: I would like to add that i could have more than one tickers on a given date and so using date as a pure index may not help?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52287359
score: 1
upvote count: 1
type: Question
tagged with: opencv
tagged with: opencv3.0
has title: opencv python camera permission issue on Windows 10
has comment: http://stackoverflow.com/comment/91545509
has answer: http://stackoverflow.com/a/54698784
has comment: http://stackoverflow.com/comment/96188861
answer count: 3
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/60135070
has comment: http://stackoverflow.com/comment/91532769
has answer: http://stackoverflow.com/a/62933893
has body: While running a simple opencv video capture script, i am getting False as the result. I suspect it is due to some security setting in Windows 10 which is not allowing camera access. I checked Privacy > Camera settings, but there was no option to allow a script to access the camera. I can see that the camera is not turned on when running the following opencv based test script. import cv2 cap = cv2.VideoCapture(0) while(True): ret, frame = cap.read() print(ret)

http://stackoverflow.com/comment/91778685
type: QuestionComment
has text: I looked at the link but the encode("utf-8") doesn't help me because if i encode 'filename' then i'm NOT able to download it. Please show me in code what do you suggest please.
comment on: http://stackoverflow.com/q/52417697
score: 0
type: Comment

http://stackoverflow.com/comment/91697095
type: Comment
type: QuestionComment
score: 2
has text: I have the impression that you do too much work here yourself. If you use a `ModelForm`, you can avoid constructing an `Info` yourself: https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#modelform
comment on: http://stackoverflow.com/q/52376115

http://stackoverflow.com/a/52389263
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52387208
type: Answer
upvote count: 2
score: 2
has body: Well, for those who eventually met this problem in the futur, I've solved it by removing the unecessary single quotes and by sending some empty file from my custom filter when the condition is not verified... (my mistake) Here is my custom filter : @environmentfilter def include_text(ctx, key): res_dict = { 'key_value_1' : 'file_name_1', 'key_value_2' : 'file_name_2' } try: return "texts/" + res_dict[key] + ".html" except KeyError: return "texts/empty.html" Now, the first solution I was trying works fine.
answers question: http://stackoverflow.com/q/52387208
type: AcceptedAnswer

http://stackoverflow.com/comment/91749560
comment on: http://stackoverflow.com/q/52402184
score: 0
type: Comment
type: QuestionComment
has text: @dydek i use mysql in the past, it worked all fine.

http://stackoverflow.com/a/52386157
has comment: http://stackoverflow.com/comment/91745567
score: 2
has comment: http://stackoverflow.com/comment/91746590
has comment: http://stackoverflow.com/comment/91745443
has comment: http://stackoverflow.com/comment/91745168
has comment: http://stackoverflow.com/comment/91746859
downvote count: 0
has comment: http://stackoverflow.com/comment/91745133
has comment: http://stackoverflow.com/comment/91746826
has comment: http://stackoverflow.com/comment/91746807
answers question: http://stackoverflow.com/q/52364406
has body: As a "proof of concept" for two temperature sensors (neither putting noise nor thinking about realistic parameters here): import matplotlib.pyplot as plt import numpy as np from scipy.optimize import leastsq def strain( t, a, b, c, d ): return a * t**3 + b * t**2 + c * t + d def residuals( params, x1Data, x2Data, yData ): s1, s2, a, b, c, d = params cxData = [ (s1**2 * x1 + s2**2 * x2) /( s1**2 + s2**2 ) for x1, x2 in zip( x1Data, x2Data) ] diff = [ strain( x, a, b, c, d ) -y for x, y in zip( cxData, yData ) ] return diff timeList = np.linspace( 0, 25, 55 ) t1List = np.fromiter( ( 5 + 25. * (1 - np.exp( -t / 9. ) )for t in timeList ), np.float ) t2List = np.fromiter( (30. * (1 - np.exp( -t / 7. ) ) * ( 1 - np.exp( -t / 3. ) ) for t in timeList ), np.float ) combinedList = np.fromiter( ( (.7 * a + .2 * b)/.9 for a, b in zip( t1List, t2List ) ), np.float ) strainList = np.fromiter( ( strain( t, .01, -.1, .88, .2 ) for t in combinedList ), np.float ) fit, ier = leastsq( residuals, [.71,.22, 0,0, .1, .1 ], args=( t1List, t2List, strainList ), maxfev=5000 ) print fit fittedT = [ (fit[0]**2 * x1 + fit[1]**2 *x2 ) /( fit[0]**2 + fit[1]**2 ) for x1, x2 in zip( t1List, t2List) ] fittedS = [ strain( t, *(fit[2:]) ) for t in fittedT ] fig = plt.figure() ax = fig.add_subplot( 3, 1, 1 ) bx = fig.add_subplot( 3, 1, 2 ) cx = fig.add_subplot( 3, 1, 3 ) ax.plot( timeList, t1List ) ax.plot( timeList, t2List ) ax.plot( timeList, combinedList ) bx.plot( combinedList, strainList, linestyle='', marker='x' ) bx.plot( fittedT, fittedS ) cx.plot( timeList, fittedT ,'--') cx.plot( timeList, combinedList,':' ) plt.show() Giving [ 4.21350842e+03 2.25221499e+03 1.00000000e-02 -1.00000000e-01 8.80000000e-01 2.00000000e-01] and showing: Top: temperature 1 (blue) and 2 (orange) as well as linear combination (green) Centre: "simulated data" (blue) and fit (orange) Bottom: fitted temperature (blue), true temperature (orange) Depending on the real data, some fiddling might be required.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91745903
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52364406
has comment: http://stackoverflow.com/comment/91746712
type: Answer
has comment: http://stackoverflow.com/comment/91745572

http://stackoverflow.com/a/52359430
type: AcceptedAnswer
has body: Using df.reset_index().melt('Country')
accepted answer of: http://stackoverflow.com/q/52359420
answers question: http://stackoverflow.com/q/52359420
type: Answer
upvote count: 4
downvote count: 0
score: 4

http://stackoverflow.com/q/52317752
downvote count: 0
has title: Connecting Django to Postgres: django.db.utils.OperationalError: FATAL: database "DATABASENAME" does not exist
upvote count: 3
tagged with: postgresql
has body: I have just started learning Django after I took some tutorials for Python. I am trying to connect my POSTGRES database to the Django project I have just created. However, I am experiencing this problem: django.db.utils.OperationalError: FATAL: database "producthuntdb" does not exist I followed these steps: 1) Opened postgress by clicking its icon 2) Clicked on the database "postgress". The terminal opened and I wrote: CREATE DATABASE producthuntdb; The database has been created because I see it if I open postgress via its icon. 3) Went to my Django project in "settings" and change the SQLITE database to the following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'producthuntdb', 'USER': 'mymac2017', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '5432', } } 4) Run the code python3 manage.py migrate However, I am getting the error: django.db.utils.OperationalError: FATAL: database "producthuntdb" does not exist So I did the following: Cliking on postgress icon and opening the the database producthuntdb Once the terminal is open, I wrote: \du There are two users with the attributes: 1) mymac2017 | Superuser, Create role, Create DB | {} 2) postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {} What am I doing wrong? I tried to look other answers to this problem and most of the issues are from misspelling the database name OR not creating it. However, the name of my database is correct and I can see the database producthuntdb if I open postgres. Many thanks for your help.
answer count: 1
accepted answer: http://stackoverflow.com/a/52318588
has comment: http://stackoverflow.com/comment/91583698
favorite count: 0
has comment: http://stackoverflow.com/comment/91583308
has comment: http://stackoverflow.com/comment/91583434
has answer: http://stackoverflow.com/a/52318588
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91583609
has comment: http://stackoverflow.com/comment/91583335
type: AnsweredQuestion
score: 3
type: Question

http://stackoverflow.com/a/52396301
score: 1
answers question: http://stackoverflow.com/q/52395626
has body: You shouldn't include the modules in requirements.txt -- that's only for dependencies to be installed from PyPI. An import statement like: from competitor_scrape.headless import headless_browser means that you should have a directory structure something like this: . ├── competitor_scrape │ ├── __init__.py │ └── headless │ └── __init__.py ├── main.py └── requirements.txt And in the competitor_scrape/headless/__init__.py file, you should have a variable called headless_browser.
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/52402302
type: Answer
answers question: http://stackoverflow.com/q/52397120
has body: I was able to fix it using string concatenation to add the variables together into one string child.sendline ('show ap auto-rf '+radio+' '+apname)
accepted answer of: http://stackoverflow.com/q/52397120
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/91497276
type: Comment
type: QuestionComment
has text: Yes, it does,i just edited that part out, its a valid file
comment on: http://stackoverflow.com/q/52274857
score: 0

http://stackoverflow.com/comment/91636639
comment on: http://stackoverflow.com/a/52345073
type: AnswerComment
score: 0
type: Comment
has text: OK it was because hostname of my computer was in Korean. So I got that UnicodeError. Thx guys for trying to help me

http://stackoverflow.com/q/52309975
has body: I am having a tough time understanding how time complexity is calculated for a python code. Why is the time complexity of the below code O(N**2) ? from itertools import permutations indices = list(permutations(range(len(A)),2)) indices = list(filter(lambda x: x[0] &lt; x[1], indices)) Y = [(A[i], A[j]) for i,j in indices] count = sum(x&gt;y for x,y in Y) if count &gt;= 1000000000: count = -1 return count
downvote count: 4
has comment: http://stackoverflow.com/comment/91567146
tagged with: time-complexity
answer count: 1
has comment: http://stackoverflow.com/comment/91567325
has answer: http://stackoverflow.com/a/52310455
tagged with: big-o
favorite count: 0
has title: Why the Time Complexity of my python code O(N**2)
score: -4
tagged with: python
has comment: http://stackoverflow.com/comment/91567027
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52310455
has comment: http://stackoverflow.com/comment/91567393
has comment: http://stackoverflow.com/comment/91567339
has comment: http://stackoverflow.com/comment/91567287
type: Question
has comment: http://stackoverflow.com/comment/91567100
has comment: http://stackoverflow.com/comment/91567196
has comment: http://stackoverflow.com/comment/91567384
upvote count: 0

http://stackoverflow.com/comment/91522057
type: AnswerComment
comment on: http://stackoverflow.com/a/52286535
score: 0
type: Comment
has text: how can i pass parameter at self.timeline.frameChanged.connect(onframeChanged) ??

http://stackoverflow.com/q/52289736
upvote count: 2
has title: How to implement pre-training in Tensorflow? How to partially use saved weights from checkpoint file?
tagged with: python
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/52290468
tagged with: tensorflow
type: Question
downvote count: 0
has body: For the convenience of discussion, the following models have been simplified. Let's say there are around 40,000 512x512 images in my training set. I am trying to implement pre-training, and my plan is the following: 1.Train a neural network (lets call it net_1) that takes in 256x256 images, and save the trained model in tensorflow checkpoint file format. net_1: input -&gt; 3 conv2d -&gt; maxpool2d -&gt; 2 conv2d -&gt; rmspool -&gt; flatten -&gt; dense let's call this structure net_1_kernel: net_1_kernel: 3 conv2d -&gt; maxpool2d -&gt; 3 conv2d and call the remaining part other_layers: other_layers: rmspool -&gt; flatten -&gt; dense Thus we can represent net_1 in the following form: net_1: input -&gt; net_1_kernel -&gt; other_layers 2.Insert several layers to the structure of net_1, and now call it net_2. It should look like this: net_2: input -&gt; net_1_kernel -&gt; maxpool2d -&gt; 3 conv2d -&gt; other_layers net_2 will take 512x512 images as input. When I train net_2, I would like to use the saved weights and biases in the checkpoint file of net_1 to initialize the net_1_kernel part in net_2. How can I do this? I know that I can load checkpoints to make predictions of test data. But in that case it will load everything (net_1_kernel and other_layers). What I want is to load net_1_kernel only and use it for the weight/bias initialization in net_2. I also know that I can print contents in checkpoint files to txt, and copy &amp; paste to manually initialize the weights and biases. However, there are so many numbers in those weights and biases, and this would be my last choice.
accepted answer: http://stackoverflow.com/a/52290468
answer count: 1
tagged with: transfer-learning
favorite count: 0

http://stackoverflow.com/q/52385079
has comment: http://stackoverflow.com/comment/91738092
has body: I'm trying to use reply_message function to send back multi-messages to user, but I got some trouble in there. In the official SDK document we know how to using the reply_message function example is: line_bot_api.reply_message(event.reply_token, TextSendMessage(text = "123")) And then the Line bot will show the message "123" if user send something messages. But in the official github it said that "reply_message" function can send 5 messages at same time. official github Screenshot official github link Also, the document said that the request body should send back two parameters: replyToken and messages (please see the screenshot) offical reply_message SDK document link It said put the array of message object into message parameter. And the array of message object is look like: the SDK document of message object example link Another way I found that someone using PHP to implement by using this function. PHP implement method example But I still can't find the solution how to send multi messages in the reply_message function by using Python.. I tried to code in Python is: line_bot_api.reply_message({'reply_token' : event.reply_token, 'messages' : [{'type' : 'text', 'text' : '123'}]}) The error message is: TypeError: reply_message() missing 1 required positional argument: 'messages' error message log I tried another way to put parameters, but still can't work line_bot_api.reply_message(reply_token = event.reply_token, messages = [{'type' : 'text', 'text' : '123'}]) the error message is: AttributeError: 'dict' object has no attribute 'as_json_dict' How can this be done in Python?
has comment: http://stackoverflow.com/comment/91714908
type: Question
tagged with: chatbot
upvote count: 3
answer count: 1
has title: How using LINE chat bot "reply_message function" to reply multi-messages to user
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52400313
score: 3
downvote count: 0

http://stackoverflow.com/q/52296134
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python-multithreading
tagged with: multithreading
tagged with: python
has title: How to make a loop add a function to a pool of multiprocessing tasks in PYTHON?
downvote count: 0
score: 1
has body: I need some help with multiprocessing in Python. I want my code to extract a link from each line of a CSV file and then feed each into an instance of function. I need these functions to be running at the same time. Currently my code pulls the link from the CSV and feeds it to the function one by one - meaning no more link functions can be started until the one before it has finished. I think threading or multiprocessing may be needed however I haven't managed to implement it properly using a loop. Any help would be greatly appreciated! Thanks links = csv.reader(open('links.csv','r')) row = list(csv.reader(open('links.csv','r'))) row_count = sum(1 for row in links) for i in range(0,row_count): link = ((str(row[i])).replace("'","")).replace("[","").replace("]","") print(link) LINKFUNCTIONPROCESS(link)
type: Question
tagged with: multiprocessing
linked to: http://stackoverflow.com/q/23794207
has comment: http://stackoverflow.com/comment/91540999
has answer: http://stackoverflow.com/a/52296443
upvote count: 1

http://stackoverflow.com/comment/91732868
type: Comment
has text: For #1 you can use `[ "$n3" -eq 4 ] && [ "$n2" -eq 0 ]` instead of `$$`, but what do you mean by problem 2? What does it output, and what did you expect? (By the way, SO works better with one problem per post. See [One post with multiple questions or multiple posts?](https://meta.stackexchange.com/questions/39223/one-post-with-multiple-questions-or-multiple-posts))
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52393770

http://stackoverflow.com/q/52294650
has title: Using JavaScript Onclick Event to pass Data to views.py in Django?
accepted answer: http://stackoverflow.com/a/52295009
type: Question
tagged with: javascript
has answer: http://stackoverflow.com/a/52295009
upvote count: 2
answer count: 1
tagged with: dom-events
has comment: http://stackoverflow.com/comment/91536956
favorite count: 0
tagged with: ajax
tagged with: django
tagged with: python
has body: I Have a bit of idea about this to use ajax with the JavaScript to send data to views.py but I am not able to do that. So what I am trying to do is I have put onclick event on the image so by clicking on that image I should be able to send some value to views.py. This is Hello.html file: JavaScript function: function change(){ // Do something here to send data to views.py } Now in views.py def SomeFunction(): //To get data here
has comment: http://stackoverflow.com/comment/91538825
has comment: http://stackoverflow.com/comment/91536977
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/52406902
has comment: http://stackoverflow.com/comment/91762018
favorite count: 0
has comment: http://stackoverflow.com/comment/91772820
has answer: http://stackoverflow.com/a/53739572
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91758618
has comment: http://stackoverflow.com/comment/91761206
tagged with: c++
has body: I have to transform the radial symmetry transform algorithm from C++ to Python. I'm very new to python and have never used C++. void RadSymTransform(InputArray gradx,InputArray grady,OutputArray result,int ray,double minval=0,double maxval=255) { Mat gxMat=gradx.getMat(); Mat gyMat=grady.getMat(); result.create(gradx.size(), CV_16UC1); Mat resMat=result.getMat(); resMat=Mat::zeros(resMat.size(), resMat.type()); int x,y,i,H,W; double tx,ty,gx,gy,ampl,max; H=gxMat.rows;W=gxMat.cols; for(y=0;y&lt;H;y++) for (x = 0; x &lt; W; x++) { gx=gxMat.at&lt;double&gt;(y,x); gy=gyMat.at&lt;double&gt;(y,x); ampl=sqrt(gx*gx+gy*gy); if((ampl&gt;minval)&amp;&amp;(ampl&lt;maxval)){ max=(abs(gx)&gt;abs(gy)?abs(gx):abs(gy)); gx/=max;gy/=max; tx=x-ray*gx;ty=y-ray*gy; if(tx&lt;0||tx&gt;W||ty&lt;0||ty&gt;H)continue; tx=x;ty=y; for (i = 0; i &lt; ray; ++i) { tx-=gx;ty-=gy; resMat.at&lt;ushort&gt;((int)ty,(int)tx)++; } } } } It takes the x and y gradients and the detection radius (ray). minval and maxval are low and high thresholds for the gradient. The algorithm should transform the coin image down below to the radial symmetry transform. This is my python version, but unfortunately I get an error: Traceback (most recent call last): File "C:/Users/Christian/PycharmProjects/symmetry_transform4/RadSymTransform.py", line 74, in &lt;module&gt; print(radSymTransform(gray, 60, 0, 255)) File "C:/Users/Christian/PycharmProjects/symmetry_transform4/RadSymTransform.py", line 64, in radSymTransform result[ty, tx] = result[ty, tx] + 1 IndexError: index 1024 is out of bounds for axis 1 with size 1024 code: import cv2 import cv2 import numpy as np import math # x gradient def gradx(img): img = img.astype('int') rows, cols = img.shape # Use hstack to add back in the columns that were dropped as zeros return np.hstack((np.zeros((rows, 1)), (img[:, 2:] - img[:, :-2]) / 2.0, np.zeros((rows, 1)))) # y gradient def grady(img): img = img.astype('int') rows, cols = img.shape # Use vstack to add back the rows that …
has comment: http://stackoverflow.com/comment/91758266
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91757854
has comment: http://stackoverflow.com/comment/91758968
has comment: http://stackoverflow.com/comment/91759582
tagged with: algorithm
has comment: http://stackoverflow.com/comment/91768241
score: 0
has title: Algorithm from C++ to Python (radial symmetry transform)
answer count: 1
has comment: http://stackoverflow.com/comment/91757815
has comment: http://stackoverflow.com/comment/91768534

http://stackoverflow.com/q/52366742
tagged with: if-statement
has answer: http://stackoverflow.com/a/52366885
has body: import time def temp(): print(script) print(a,sce1) print(b,sce2) print(c,sce3) print(d,sce4) choice = str(input()) return choice if choice =="i": print(inventory) if choice =="p": print(storyline_varable) script = "" a = "" b = "" c = "" d = "" sce1 = "" sce2 = "" sce3 = "" sce4 = "" choice = "" inventory = list(("")) storyline_variable = list(("")) print("Welcome to choice dungeon! Go through this dangerous place by typing the letter of the choice you'd like to make (also type 'i' to see your inventory and 'p' to see important choices made), good luck!") time.sleep(4) #start script = "You lay shackled to a wall in a room with damp walls made of rough stone, you are cold and wet, what do you do?" sce1 = "Pull the shackles" sce2 = "Shout for help" sce3 = "Sit in the cold dark room for a while" sce4 = "Start nawing your hand off" a = "a-" b = "b-" c = "c-" d = "d-" if temp() == "a" or temp() == "ba" or temp() == "ca": #a&amp;ba&amp;ca script = "Your shackles break free, there is a dimmly lit room with a skeleton, a torch and a closed door" sce1 = "Grab the torch" sce2 = "Search the skeleton" sce3 = "Go through the door" a = "aa-" b = "ab-" c = "ac-" d = "ad-" if temp() == "b": #b&amp;cb&amp;db storyline_variable.append("Someone has been woken up") script = "You call for hours to no avail, until you hear a faint shout from a distance: 'Shut up'. Try another option" sce1 = "Pull the shackles" sce2 = "Shout for help...again" sce3 = "Sit in the cold dark room for a while" sce4 = "Start nawing your hand off" a = "ba-" b = "bb-" c = "bc-" d = "bd-" if temp() == "c" or temp() == "bc" or temp() == "cc": #c&amp;cc script = "You just sit there, it's a bit uncomfortable and a tad boring but it isn't that bad. Try another option" sce1 = "Pull the shackles" sce2 = "Shout for help" sce3 = "Sit there more" sce4 = "Start nawing your hand off" a = "ca-" b = "cb-" c = "cc-" d = "cd-" if temp() == "d" or temp() == "bd" or temp() == "cd": print("Was it worth it? You bled out... ouch") e…
has answer: http://stackoverflow.com/a/52366866
type: Question
has comment: http://stackoverflow.com/comment/91677823
answer count: 2
has comment: http://stackoverflow.com/comment/91677808
upvote count: 0
tagged with: function
score: -2
tagged with: python
has comment: http://stackoverflow.com/comment/91677732
favorite count: 0
has title: My functions and if statements don't seem to be working
has comment: http://stackoverflow.com/comment/91677687
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/91677789
has comment: http://stackoverflow.com/comment/91677793

http://stackoverflow.com/comment/102633292
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52391775
has text: No, it doesn't, sorry.
score: 0

http://stackoverflow.com/q/52335553
has comment: http://stackoverflow.com/comment/91622255
upvote count: 1
type: Question
tagged with: opencv
downvote count: 0
has comment: http://stackoverflow.com/comment/91626241
has comment: http://stackoverflow.com/comment/91625883
has answer: http://stackoverflow.com/a/52349342
answer count: 1
has comment: http://stackoverflow.com/comment/91643795
favorite count: 0
linked to: http://stackoverflow.com/q/48251448
has title: Fit internal rectangles to joints
has comment: http://stackoverflow.com/comment/91624401
has body: Using a joints array, like the following: How can I fit the internal rectangles, so that no rectangles overlap and all points are used? Basically fitting table cells to the points. I've tried grabbing the contours, works fine: With 22 points found. How can I fit these points to internal polygons? E.g. find the 21 rectangles in this image.
tagged with: python
accepted answer: http://stackoverflow.com/a/52349342
type: AnsweredQuestion
tagged with: opencv3.0
score: 1

http://stackoverflow.com/comment/91681776
comment on: http://stackoverflow.com/a/52368126
has text: Ah, I searched for the issue in here a bit and found that adding `newline=''` after `'w'` solves it. Thanks! weiß-rote Grüße aus Stuttgart.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/52359903
type: UnansweredQuestion
tagged with: python
has body: I wrote a Python 3 script to measure the running time of a process, since it keeps dying and I'm interested in how long it will keep actively running. But it's running on my laptop, and I realized the statistics will be skewed by periods when I've put it to sleep. It's on Linux, so I'm sure there's a log file I could parse (it used to be pm-suspend.log before systemd), but I'm wondering if there's a more general/direct way. Can a process ask to be notified of suspend events? I should note that I'm interested in the wallclock time the process was running, not the actual CPU execution time. So time.process_time() won't work.
type: Question
has title: How to measure process awake time (system not asleep)
has answer: http://stackoverflow.com/a/52360261
score: 0
answer count: 1
tagged with: python-3.x

http://stackoverflow.com/q/52399505
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91750590
tagged with: python
has title: Is there a way to name a tensorflow variable based on the value of another tensor-variable
answer count: 0
tagged with: machine-learning
tagged with: tensorflow
type: Question
has body: I want to be able to do the following n = str(tf.constant(2)) v = tf.get_variable(name=n, shape=(256,256), initializer=tf.contrib.layers.xavier_initializer()) but doing this is converts n to a string representation of tensorflow variable i.e "&lt;tf.Tensor 'Const_4:0' shape=() dtype=int32&gt;"
score: 0
has comment: http://stackoverflow.com/comment/91743364

http://stackoverflow.com/q/52357834
has answer: http://stackoverflow.com/a/52357887
has body: I'm learning python and with it pandas and some tools about Data Science. Doing the exercises of a book I wrote the above code on IPython but I receive an error message when the block is executed: for i in range(len(df1)): if (df1['Temperature'][i]-df1['Temperature'][i-1]) &gt; 0.1: print (df1['Temperature'][i]) Traceback (most recent call last): File "&lt;ipython-input-140-9f31dd23b324&gt;", line 2, in &lt;module&gt; if (df1['Temperature'][i]-df1['Temperature'][i-1]) &gt; 0.1: File "D:\Programas\Anaconda\lib\site-packages\pandas\core\series.py", line 766, in __getitem__ result = self.index.get_value(self, key) File "D:\Programas\Anaconda\lib\site-packages\pandas\core\indexes\base.py", line 3103, in get_value tz=getattr(series.dtype, 'tz', None)) File "pandas\_libs\index.pyx", line 106, in pandas._libs.index.IndexEngine.get_value File "pandas\_libs\index.pyx", line 114, in pandas._libs.index.IndexEngine.get_value File "pandas\_libs\index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc File "pandas\_libs\hashtable_class_helper.pxi", line 958, in pandas._libs.hashtable.Int64HashTable.get_item File "pandas\_libs\hashtable_class_helper.pxi", line 964, in pandas._libs.hashtable.Int64HashTable.get_item KeyError: -1 Where df1['Temperature'] is a Data Frame such that Temperature is one of its columns. The code intending to compare two consecutive values of that column and verify the numeric difference between them and print the temperature given a statement. What am I doing wrong?
tagged with: pandas
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/7837722
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/52357859
answer count: 2
has title: Looping structure and Pandas
tagged with: python
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/91660277
downvote count: 1
has comment: http://stackoverflow.com/comment/91660308
has answer: http://stackoverflow.com/a/52357859
possible better answer: http://stackoverflow.com/a/52357887
has comment: http://stackoverflow.com/comment/91660174

http://stackoverflow.com/comment/92282184
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52394697
has text: As written in the [documentation for Popen](https://docs.python.org/3/library/subprocess.html#subprocess.Popen): "`bufsize` will be supplied as the corresponding argument to the `open()` function when creating the `stdin`/`stdout`/`stderr` pipe file objects". The buffer defaults to the system buffering settings. [Furthermore](https://docs.python.org/3/library/subprocess.html#subprocess.Popen.stderr): "Warning: Use `communicate()` rather than `.stdin.write`, `.stdout.read` or `.stderr.read` to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process."
type: QuestionComment

http://stackoverflow.com/a/52332216
accepted answer of: http://stackoverflow.com/q/52331845
has body: You can use loop by each file, each line and append filtered rows to list, last use DataFrame contructor: data = [] for file in glob.glob('logs/*.json'): with open(file) as f: for line in f: if json.loads(line)['Name'] == '1': data.append(json.loads(line)) df = pd.DataFrame(data)
has comment: http://stackoverflow.com/comment/91611221
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/91611304
has comment: http://stackoverflow.com/comment/91649881
score: 1
has comment: http://stackoverflow.com/comment/91611192
answers question: http://stackoverflow.com/q/52331845
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52337439
has comment: http://stackoverflow.com/comment/91622241
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/91622270
has answer: http://stackoverflow.com/a/52337530
has body: I'm running Mac OS X Yosemite - 10.10.5, I am trying to run tensorflow in Python 2.7.10. When I try to import tensorflow I get this error, I believe it is caused because Numpy is not updated: $ python Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import tensorflow as tf RuntimeError: module compiled against API version 0xa but this version of numpy is 0x9 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/krishnachatpar/Library/Python/2.7/lib/python/site-packages/tensorflow/__init__.py", line 24, in &lt;module&gt; from tensorflow.python import * File "/Users/krishnachatpar/Library/Python/2.7/lib/python/site-packages/tensorflow/python/__init__.py", line 51, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "/Users/krishnachatpar/Library/Python/2.7/lib/python/site-packages/tensorflow/python/pywrap_tensorflow.py", line 52, in &lt;module&gt; raise ImportError(msg) ImportError: Traceback (most recent call last): File "/Users/krishnachatpar/Library/Python/2.7/lib/python/site-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "/Users/krishnachatpar/Library/Python/2.7/lib/python/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in &lt;module&gt; _pywrap_tensorflow_internal = swig_import_helper() File "/Users/krishnachatpar/Library/Python/2.7/lib/python/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) ImportError: numpy.core.multiarray failed to import Update: When I try to update numpy: $ pip install numpy --upgrade Collecting numpy Using cachedhttp://files.pythonhosted.org/packages/e7/c1/d5c47de35e366b1c2f60da88a24b25d3037b89…
tagged with: numpy
answer count: 2
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/52338003
has title: Can't use tensorflow because of Numpy Error
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/20518632

http://stackoverflow.com/comment/91619283
comment on: http://stackoverflow.com/q/52335418
type: Comment
score: 1
type: QuestionComment
has text: Welcome to StackOverflow. 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), [how to ask](http://stackoverflow.com/help/how-to-ask), and [... the perfect question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) apply here. StackOverflow is not a design, coding, research, or tutorial resource.

http://stackoverflow.com/q/52363846
type: Question
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91771514
has body: I have working pipeline and want to implement in C++. How can I link two elements in one element? Pipeline example: autoaudiosrc ! ...... ! rtpmp4apay ! udpsink host="" port=1234 udpsrc port=4321 ! ..... ! autoaudiosink Here I need to combine udpsink and udpsrc to one element. Do I need to use udpsink as g_object_set to udpsrc?
has comment: http://stackoverflow.com/comment/91687617
has comment: http://stackoverflow.com/comment/91685566
has title: Gstreamer link udpsink and udpsrc in one element (C++)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91683769
has answer: http://stackoverflow.com/a/52382055
has comment: http://stackoverflow.com/comment/91680322
tagged with: python
tagged with: c++
tagged with: gstreamer
has comment: http://stackoverflow.com/comment/91683910

http://stackoverflow.com/a/52389219
score: 0
type: AcceptedAnswer
has body: You may use the following pattern: (.*\bposition\b:50\.00%.*\bline\b:10\.00%)\s*(.*) Replacing with: \1\n{\\an8}\2 Regex demo here. In Python: import re mystring = '''00:05:31.957 --&gt; 00:05:34.835 position:50.00%,start align:start size:25.24% line:10.00% Not yet.''' print(re.sub(r'(.*\bposition\b:50\.00%.*\bline\b:10\.00%)\s*(.*)',r'\1\n{\\an8}\2',mystring)) Prints: 00:05:31.957 --&gt; 00:05:34.835 position:50.00%,start align:start size:25.24% line:10.00% {\an8}Not yet.
type: Answer
answers question: http://stackoverflow.com/q/52389087
accepted answer of: http://stackoverflow.com/q/52389087

http://stackoverflow.com/q/52359905
has comment: http://stackoverflow.com/comment/91677621
type: Question
has body: This is a simple example that reproduces my issue in a network I am trying to deploy. I have an image input layer (which I need to maintain), then a Dense layer, Conv2D layer and a dense layer. The idea is that the inputs are 10x10 images and the labels are 10x10 images. Inspired by my code and this example. import numpy as np from keras.models import Model from keras.layers import Input, Conv2D #Building model size=10 a = Input(shape=(size,size,1)) hidden = Dense(size)(a) hidden = Conv2D(kernel_size = (3,3), filters = size*size, activation='relu', padding='same')(hidden) outputs = Dense(size, activation='sigmoid')(hidden) model = Model(inputs=a, outputs=outputs) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) #Create random data and accounting for 1 channel of data n_images=55 data = np.random.randint(0,2,(n_images,size,size,1)) labels = np.random.randint(0,2,(n_images,size,size,1)) #Fit model model.fit(data, labels, verbose=1, batch_size=10, epochs=20) print(model.summary()) I get the following error: ValueError: Error when checking target: expected dense_92 to have shape (10, 10, 10) but got array with shape (10, 10, 1) I don't get an error if I change: outputs = Dense(size, activation='sigmoid')(hidden) with: outputs = Dense(1, activation='sigmoid')(hidden) No idea how Dense(1) is even valid and how it allows 10x10 output signal as model.summary() indicates: _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_26 (InputLayer) (None, 10, 10, 1) 0 _________________________________________________________________ dense_93 (Dense) (None, 10, 10, 10) 20 _________________________________________________________________ conv2d_9 (Conv2D) (None, 10, 10, 100) 9100 _________________________________________________________________ dense_94 (Dense) (None, 10, 10, 1) 101 ======================================================…
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/91678223
has comment: http://stackoverflow.com/comment/91677431
has comment: http://stackoverflow.com/comment/91677761
tagged with: python
has comment: http://stackoverflow.com/comment/91671627
tagged with: conv-neural-network
accepted answer: http://stackoverflow.com/a/52367868
upvote count: 1
linked to: http://stackoverflow.com/q/52089601
tagged with: tensorflow
has title: How to Build a Two-Branch Keras Model with Dense and Conv2D Layers?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/43895750
score: 1
has answer: http://stackoverflow.com/a/52367868

http://stackoverflow.com/comment/91934621
has text: No I didn't test - just a guess based on the intuitive nature of DRF
comment on: http://stackoverflow.com/a/52365514
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91656371
comment on: http://stackoverflow.com/q/52351608
type: Comment
has text: Sorry. No idea. :(
score: 0
type: QuestionComment

http://stackoverflow.com/a/52280458
has body: try below example: files = ["Hello%","&amp;*hhf","ddh","GTD@JJ"] #input data in list # going through each element of list # apllying a filter on each character of string for alphabet or numeric other then special symbol # joining the charactors back again and putting them in list result = ["".join(list(filter(str.isalnum, line))) for line in files] print(result) #print the result Output: ['Hello', 'hhf', 'ddh', 'GTDJJ']
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52280027

http://stackoverflow.com/comment/91732312
score: 1
comment on: http://stackoverflow.com/a/52393521
type: AnswerComment
type: Comment
has text: Thank you very much for the detailed explanation. I've got some ideas thanks to your reply. There is long way to go to get used to the selenium though. Thanks alot!

http://stackoverflow.com/comment/91760778
comment on: http://stackoverflow.com/q/52408505
score: 0
type: Comment
type: QuestionComment
has text: why dont you traverse the list...convert the whole thing into a df if you want...just take the first element of the list as the header for your df and all the rest as the data

http://stackoverflow.com/q/52313100
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52313126
has body: i have string date = "2018-09-12" i want to get output like 2018-September-12 and i try like this from datetime import datetime date3 = datetime.strptime(date, '%Y-%m%B-%d') or date3 = datetime.strptime(date, '%Y-%B-%d') but always get time data '2018-09-12' does not match format '%Y-%m%B-%d'
linked to: http://stackoverflow.com/q/2265357
answer count: 1
has comment: http://stackoverflow.com/comment/91573212
has comment: http://stackoverflow.com/comment/91573258
duplicate of: http://stackoverflow.com/q/2265357
favorite count: 0
accepted answer: http://stackoverflow.com/a/52313126
tagged with: python
has comment: http://stackoverflow.com/comment/91573239
type: AnsweredQuestion
has title: Converting month in number to word
score: 0

http://stackoverflow.com/q/52272285
tagged with: encode
tagged with: python
type: AnsweredQuestion
has body: when importing ethjsonrpc It throws an error as below: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.6/site-packages/ethjsonrpc/__init__.py", line 1, in &lt;module&gt; from ethjsonrpc.client import (EthJsonRpc, ParityEthJsonRpc, File "/usr/local/lib/python3.6/site-packages/ethjsonrpc/client.py", line 7, in &lt;module&gt; from ethereum import utils File "/usr/local/lib/python3.6/site-packages/ethereum/utils.py", line 103, in &lt;module&gt; assert sha3('').encode('hex') == 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' AttributeError: 'bytes' object has no attribute 'encode'
has title: can't import ethjsonrpc in python3.6 , ubuntu
type: Question
tagged with: ubuntu
has answer: http://stackoverflow.com/a/52272371
accepted answer: http://stackoverflow.com/a/52272371
score: 0
tagged with: ethereum
answer count: 1

http://stackoverflow.com/a/52420583
has comment: http://stackoverflow.com/comment/91784391
score: 6
has body: You can use getattr(..) [Python-doc] and add a default value for that, for example: from django.conf import settings def mixpanel_id(self): if getattr(settings, 'CROSS_SUBDOMAIN_COOKIE', False): cross_subdomain_cookie = True else: cross_subdomain_cookie = False So here as default we set False. In case the CROSS_SUBDOMAIN_COOKIE is missing, we will obtain False, otherwise getattr(..) will return the value of the attribute. Note that an if-else that returns True/False can be simplified to: def mixpanel_id(self): cross_subdomain_cookie = bool(getattr(settings, 'CROSS_SUBDOMAIN_COOKIE', False)) and in case the attribute is always a boolean, we can even write: def mixpanel_id(self): cross_subdomain_cookie = getattr(settings, 'CROSS_SUBDOMAIN_COOKIE', False) In case the default is True, or another value, you thus can replace the False by that value.
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52420526
upvote count: 6
accepted answer of: http://stackoverflow.com/q/52420526

http://stackoverflow.com/q/52274257
has answer: http://stackoverflow.com/a/52534797
favorite count: 0
has answer: http://stackoverflow.com/a/52274572
has title: Finding the source of Django login page message
linked to: http://stackoverflow.com/q/6583877
tagged with: python
type: UnansweredQuestion
tagged with: django
upvote count: 1
score: 1
type: Question
has answer: http://stackoverflow.com/a/52274483
answer count: 3
tagged with: django-admin
downvote count: 0
has body: I have created a working Django application. I am using django-allauth for implementing social-account authentication. Now, suppose I am logged-in inside my application using an e-mail id whose user does not have a staff access and, if I open admin login page directly, the admin login page is displayed as follows: My question is: how can I stop Django from displaying the message "Successfully signed in as ... "? Where is the source of this message present?

http://stackoverflow.com/q/52417440
has comment: http://stackoverflow.com/comment/91778084
has comment: http://stackoverflow.com/comment/91778107
has title: How do I add a counter to track the months and years in one while loop?
score: 1
has answer: http://stackoverflow.com/a/52417548
type: Question
answer count: 2
downvote count: 0
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/91778139
has body: so I am trying to create a program and I have the program complete for the most part but I am having some trouble with counters. -I need to add a counter for months and years that track how long it will take to become a millionaire. -I have the months counter correct, but I am having trouble trying to figure out the years counter. Here is my code so far: balance = float(input("Enter initial amount: ")) monthlyContribution = float(input("Enter monthly contribution: ")) interestRate = float(input("Enter annual interest rate: ")) month = 0 year = 0 while balance &lt; 1000000 : month = month + 1 year = year + 1 interest = interestRate/100 balance = balance + monthlyContribution + (balance + monthlyContribution) * interest/12 print(f'Current Balance: ${balance:,.2f}', (f'after {month} months'), (f' or {year} years')) print(f'Congratulations, you will be a millionaire in {month} months: ${balance:,.2f}')
tagged with: python
has answer: http://stackoverflow.com/a/52417495
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91778256
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/comment/91544407
type: Comment
has text: Thanks - yes, I also identified the problem. The solution is what bugs me ;-). This sound like a solution, but seems not ideal yet. How about a Dense layer that has the right number of output neurons? Maybe in the middle, after the encoding?
comment on: http://stackoverflow.com/a/52297694
type: AnswerComment
score: 0

http://stackoverflow.com/q/52408268
accepted answer: http://stackoverflow.com/a/52408398
has comment: http://stackoverflow.com/comment/91761049
has answer: http://stackoverflow.com/a/52408407
type: Question
linked to: http://stackoverflow.com/q/10484261
has comment: http://stackoverflow.com/comment/91760395
has answer: http://stackoverflow.com/a/52408398
has answer: http://stackoverflow.com/a/52408458
has comment: http://stackoverflow.com/comment/91760404
has comment: http://stackoverflow.com/comment/91760319
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/91760957
downvote count: 1
has body: I have 2 dictionaries that (simplified) look like this: dict1 = {'X(0,0)': 1, 'X(0,1)': 3, 'X(1,0)':4, 'X(1,1)':2} dict2 = {'X(0)': 'area1', 'X(1)': 'area2'} I want to create a third dictionary with the keys of the first one and the values of the second one, if the dict2 key 'X(i)' is part of the dict1 key 'X(i,j)'. So the end result should be like this: dict3 = {'X(0,0)': 'area1', 'X(0,1)': 'area1', 'X(1,0)':'area2', 'X(1,1)':'area2'} I have tried following what was suggested here but it is not exactly what I want and cannot make it work.
possible better answer: http://stackoverflow.com/a/52408407
favorite count: 0
tagged with: python-3.x
answer count: 3
tagged with: python
tagged with: dictionary
has title: Create new dictionary based on keys from other dictionaries
has comment: http://stackoverflow.com/comment/91760561
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91760377

http://stackoverflow.com/comment/91691283
score: 1
has text: Afaik xlsxwriter cannot use xlsb
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52372951

http://stackoverflow.com/comment/91880412
comment on: http://stackoverflow.com/a/52309698
score: 0
has text: When the booking instance was created i validated fields a,b&c using serializer 1. Now when i’m updating it, i’m validating fields d,e&f using serialiser 2. edit: hmm...now that you’ve mentioned it i think Step5 is redundant because i’m already serialising it once in step2.
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52394908
answer count: 2
has body: EDIT: As indicated by @Carlos Cordoba, this problem is a known bug with ipykernel, and will be fixed in the coming weeks. For anyone experiencing the same problem, see this thread, and use the following command after installing spyder to your environment: conda install -n env_name ipykernel=4.8.2 ORIGINAL: I'm creating a Python 3.6 environment using Anaconda, and receive the following error in the prompt after installing and running Spyder: js: Not allowed to load local resource: file:///C:/Users/User/Anaconda3/envs/my_env/lib/site-packages/spyder/utils/help/static/css/default.css This error continues to print every 15 seconds or so. Steps I've used for creating my environment within Anaconda Prompt: 1. conda create -n my_env python 2. conda install -n my_env spyder 3. conda activate my_env 4. spyder What could be causing this, and why am I getting a javascript error when using Python?
has title: Conda/Spyder environment error - js not allowed to load local resource
downvote count: 0
has comment: http://stackoverflow.com/comment/91735227
favorite count: 0
tagged with: spyder
tagged with: python
has comment: http://stackoverflow.com/comment/91736006
has answer: http://stackoverflow.com/a/52396162
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/52696541
upvote count: 2
has comment: http://stackoverflow.com/comment/91736219
has comment: http://stackoverflow.com/comment/91735846
type: Question
possible better answer: http://stackoverflow.com/a/52696541
accepted answer: http://stackoverflow.com/a/52396162
tagged with: conda

http://stackoverflow.com/comment/91554657
comment on: http://stackoverflow.com/q/52303314
type: Comment
type: QuestionComment
score: 0
has text: You're also missing one line of code at the very beginning, with the function's definition.

http://stackoverflow.com/q/52401802
downvote count: 4
has comment: http://stackoverflow.com/comment/91747510
has comment: http://stackoverflow.com/comment/91747500
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91747590
has comment: http://stackoverflow.com/comment/91747520
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91747488
tagged with: python
has comment: http://stackoverflow.com/comment/91747575
has title: Why doesn't this return s?
has comment: http://stackoverflow.com/comment/91747572
has comment: http://stackoverflow.com/comment/91747682
has comment: http://stackoverflow.com/comment/91747447
type: Question
has body: Trying to make a function to use the SUVAT equations to calculate each variable, and the functions aren't returning the values that should have been calculated. def float_input(text: str) -&gt; float: while True: try: num = float(input(text)) except ValueError: num = '' break else: return num print ('Enter the values of the following variables if they have been given') s = float_input('Displacement') u = float_input('Initial Velocity') v = float_input('Final Velocity') a = float_input('Acceleration') t = float_input('Time') def find_s (s, u, v, a, t): if s == '': if '' not in (v, u, a): es = 's = (v^2-u^2)/(2a)' s = ((v**2)-(u**2))/(2*a) elif '' not in (u, t, a): es = 's = ut + 1/2at^2' s = (u*t) + (0.5*a*t**2) elif '' not in (v, a, t): es = 's = vt - 1/2at^2' s = (v*t)-(0.5*a*t**2) elif '' not in (v, u, t): es = 's = t(v+u)/2' s = (0.5*(v+u))*t return (s, es) else: es = '' return (s, es) s, es = find_s (s, u, v, a, t) print (s) I've input values for u, v, and a, which should mean s is calculated, but this prints 'None' instead of the value of s based on the calculations, why, and how would I fix it?
upvote count: 0
has comment: http://stackoverflow.com/comment/91748692
score: -4
has answer: http://stackoverflow.com/a/52401906

http://stackoverflow.com/a/53067592
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52401288
has body: The signal should be similar in shape but with shift in the time scale.

http://stackoverflow.com/q/52418721
has comment: http://stackoverflow.com/comment/91784943
tagged with: eve
tagged with: python
has body: Suppose I have multiple mongodbs like mongodb_1, mongodb_2, mongodb_3 with same kind of data like employee details of different organizations. When user triggers GET request to get employee details from all the above 3 mongodbs whose designation is "TechnicalLead". then first we need to connect to mongodb_1 and search and then disconnect with mongodb_1 and connect to mongodb_2 and search and repeat the same for all dbs. Can any one suggest how can we achieve above using python EVE Rest api framework. Best Regards, Narendra
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91784012
has comment: http://stackoverflow.com/comment/91785210
has answer: http://stackoverflow.com/a/52872010
type: Question
tagged with: mongodb
score: 0
answer count: 1
has title: How to search for all existing mongodbs for single GET request

http://stackoverflow.com/q/52332897
has comment: http://stackoverflow.com/comment/91613219
accepted answer: http://stackoverflow.com/a/52333182
tagged with: python
has comment: http://stackoverflow.com/comment/91612886
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52333440
has comment: http://stackoverflow.com/comment/91612644
upvote count: 3
has comment: http://stackoverflow.com/comment/91613153
has body: I have a .gz file, inside which there is another file. I need to extract the file inside the zipped file. f = gzip.open(dest, 'rb') This only opens the file but I need to download that particular file which is inside gz instead of just opening the gz file. This question has been marked as duplicate which I accept, but I haven't found a solution where we can actually download the file and not just read its content. Same is the case with the link mentioned.
type: Question
possible better answer: http://stackoverflow.com/a/52333440
has title: How to extract a gz file in python
linked to: http://stackoverflow.com/q/31028815
tagged with: gzip
has answer: http://stackoverflow.com/a/52333182
answer count: 2
has comment: http://stackoverflow.com/comment/91612494
score: 3
has comment: http://stackoverflow.com/comment/91612540
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/52328984
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/52331202
type: AnsweredQuestion
has title: Difference between object.method() and method(object) in Python?
tagged with: methods
type: Question
has answer: http://stackoverflow.com/a/52331202
tagged with: object
score: 0
has body: I have a very basic question; if this is a duplicate please link me to it as I wasn’t sure what to search! I’d like the ask what the difference between object.method() and method(object) is. For instance, when I was defining a stack class, I noticed that peek(stack) returned name error while stack.peek() worked fine. Why is this so? Please forgive me is this is a duplicate, will remove this question if so!
answer count: 1

http://stackoverflow.com/a/52352803
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52352766
has comment: http://stackoverflow.com/comment/91656765
answers question: http://stackoverflow.com/q/52352766
type: Answer
has body: According to the docs manage.py shell opens a Python interpreter to do stuff with your code interactively. If you have an enhanced interpreter like IPython or bpython it will tend to use that by default. What you posted is just the standard IPython prompt, which is more powerful that the default interactive prompt you get when you run just python. For example, you can run normal shell commands at the IPython prompt, such as ls and cd.
upvote count: 1
has comment: http://stackoverflow.com/comment/91656915

http://stackoverflow.com/q/52375258
tagged with: nltk
downvote count: 0
accepted answer: http://stackoverflow.com/a/52375330
tagged with: pandas
has comment: http://stackoverflow.com/comment/91695417
tagged with: nlp
has title: Find number of keyword matches in pandas column that is in a list
favorite count: 0
tagged with: python-3.x
has body: I have a pandas dataframe that looks like the following: Type Keywords ---- -------- Animal [Pigeon, Bird, Raccoon, Dog, Cat] Pet [Dog, Cat, Hamster] Pest [Rat, Mouse, Raccoon, Pigeon] Farm [Chicken, Horse, Cow, Sheep] Predator [Wolf, Fox, Raccoon] Let's say that I have the following string: input = "There is a dead rat and raccoon in my pool" Given that I tokenize the string and remove stop-words so that it becomes input = [Dead, Rat, Raccoon, Pool] I need to go through each row and find the rows that have the highest number of keyword matches. With the given example, the results would look like the following: Type Keywords Matches ---- -------- ------- Animal [Pigeon, Bird, Raccoon, Dog, Cat] 1 Pet [Dog, Cat, Hamster] 0 Pest [Rat, Mouse, Raccoon, Pigeon] 2 Farm [Chicken, Horse, Cow, Sheep] 0 Predator [Wolf, Fox, Raccoon] 1 The output would be the top three Type names that have the highest number of matches. In the above case, since the "Pest" category has the highest number of matches, it would be selected as the highest match. Additionally both the Animal and Predator categories would be selected. The output in order would thus be: output = [Pest, Animal, Predator] Doing this task with nested for loops is easy, but since I have thousands of these kinds of rows, I'm looking for a better solution. (Additionally for some reason I have encountered a lot of bugs when using non in-built functions with pandas, perhaps it's because of vectorization?) I looked at the groupby and isin functions that are inbuilt in pandas, but as far as I could tell they would not be able to get me to the output that I want (I would not be surprised at all if I am incorrect in this assumption). I next investigated the usage of sets and hashmaps with pandas, but unfortunately my coding knowledge and current ability is not yet proficient enough to craft a solid solution. This StackOverflow link in particular got me much closer to what I wanted, though it didn't find the top three match row na…
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/52375330
possible better answer: http://stackoverflow.com/a/52375328
has answer: http://stackoverflow.com/a/52375328
type: Question
linked to: http://stackoverflow.com/q/51574485
answer count: 2

http://stackoverflow.com/comment/91785419
has text: Looks like you forgot the `.html` suffix.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52421172

http://stackoverflow.com/comment/91747271
type: Comment
comment on: http://stackoverflow.com/a/52304429
has text: I edited my post and added a picture which might help understanding what I mean with invisible points. I want that only visible points are calculated, which would reduce the amount of samples or maybe just a display filter that does that automatically. I don't know. I am pretty much a noob and might have a wrong way of thinking here.
type: AnswerComment
score: 0

http://stackoverflow.com/a/52289194
type: AcceptedAnswer
downvote count: 0
has body: I was wondering how should one code the self.prediction object, so that it emits a vector of predictions for individual instances? In general tf.nn.softmax returns a vector of probabilities. You just can't see them because your are using tf.argmax, which returns the index of the largest value. Therefore you will just get one number. Just remove tf.argmax and you should be fine.
type: Answer
answers question: http://stackoverflow.com/q/52288300
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52288300
has comment: http://stackoverflow.com/comment/91526275
has comment: http://stackoverflow.com/comment/91526232

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/52316930
type: Tag

http://stackoverflow.com/comment/91504878
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52278364
has text: https://docs.python.org/3/library/functions.html#id

http://stackoverflow.com/q/52319804
answer count: 3
downvote count: 0
favorite count: 0
has title: Compare any number of dates in list inside a dictionary
has answer: http://stackoverflow.com/a/52319848
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52319995
tagged with: list
score: 1
upvote count: 1
tagged with: date
has answer: http://stackoverflow.com/a/52320077
accepted answer: http://stackoverflow.com/a/52320077
type: Question
has body: I have a dictionary of dates like this (The keys here are relevant to some other work and need to be considered): {2: ['8-12-2012', '9-12-2012', '7-12-2012], 5: ['10-12-2012', '11-12-2012'], 7: ['13-12-2012']} Now, I want to find the earliest date in each list. In the end, I need to find out which date out of all was the earliest, returning that date and the key. If I manually go through what I'm trying to do here: **key 2**, `7-12-2012` is the earliest. **key 5**, `10-12-2012` is the earliest. **key 7**, `13-12-2012` is the earliest. 7-12-2012 is the earliest date, so I should return 2. Things to note here: The data in the dictionary are created dynamically during runtime. the lists inside the dictionary is not fixed length. This is what I tried but only compares two dates: ... ... # this value would be dynamically set during runtime expiryDates[item] = {2: ['8-12-2012', '9-12-2012', '7-12-2012], 5: ['10-12-2012', '11-12-2012'], 7: ['13-12-2012']} datesInBox = [] dict_earliest_expiration = defaultdict(list) for n in expiryDates: datesInBox = expiryDates[n] # when n = 2; datesInBox = ['8-12-2012', '9-12-2012'] d1 = time.strptime(datesInBox[0], "%d-%m-%Y") d2 = time.strptime(datesInBox[1], "%d-%m-%Y") if d1 &lt; d2: dict_earliest_expiration[n] = d1 else: dict_earliest_expiration[n] = d2 Any help would be greatly appreciated.
possible better answer: http://stackoverflow.com/a/52319848

http://stackoverflow.com/q/52318990
tagged with: pandas
downvote count: 0
answer count: 1
tagged with: tableau-api
accepted answer: http://stackoverflow.com/a/52319679
favorite count: 0
tagged with: data-analysis
tagged with: data-visualization
has title: Is there a way to integrate Pandas into tableau?
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91585605
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52319679
has body: I've been using tableau for a few months now and it really is a great visualization tool. However, I feel limited because I am more familiar with the pandas library and I feel more powerful on pandas. Is there a way to integrate python into Tableau so I work on one environment, instead of constantly exporting data from Pandas and re-importing it into tableau? Thanks for the help!

http://stackoverflow.com/q/52321884
score: 0
tagged with: wavelet
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/56176269
tagged with: python
tagged with: matlab
has body: I'm trying to implement a Morlet wavelet transform as matlab does, but I couldn't find any equivalent function in python. I want to implement it like this: s0 = 6/fs; % smallest scale ds = 0.001; % spacing between scales NbSc = 3000; % number of scales SCA = {s0,ds,NbSc, 'lin'}; % specify scales cwtstruct = cwtft({data, 1/fs},'scales',SCA); and get the same outputs as Matlab's cwtstruct does. I've already seen PyWavelets but it doesn't let you specify the scales in that way nor gives the same outputs.
type: Question
has title: What is the equivalent of Matlab's cwtft() in Python? (continuous morlet wavelet transform)

http://stackoverflow.com/comment/91903126
type: Comment
has text: Dear all my bad, due to some critical delivery I lost this track. I have updated with error details. Kindly let me know if you need more information from myside.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52412070

http://stackoverflow.com/comment/91607930
has text: That's strange... first time I see this error (seems like somehow your install became corrupted). Can you check if that file is available there? i.e.: do you have the file interpreterInfo.py in the folder: eclipse/plugins/org.python.pydev.core_6.5.0.201809011628/pysrc?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52316930

http://stackoverflow.com/a/52425298
score: 0
has body: You should use python3 instead of python for running any commands you want to run then it will use the python3 version interpreter. Also if you are using pip then use pip3. Hope this helps.
type: Answer
answers question: http://stackoverflow.com/q/52425065

http://stackoverflow.com/comment/91618397
score: 1
comment on: http://stackoverflow.com/a/52335119
has text: Sure. Edited as suggested then.
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52412449
type: Question
tagged with: pandas
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91769797
has body: I have the following code from a machine learning book in python: copy_set.plot(kind = "scatter" , x = "longitude" , y = "latitude" , alpha = 0.4 , s = copy_set[ "population" ], label = "population" , figsize=(10,7), c = "median_house_value" , cmap = plt.get_cmap ( "jet" ) ) median_house_value and population are two columns in the copy_set dataframe. I don't understand why for argument s I have to use copy_set['population'] but for argument c it is possible to only use the column name median_house_value. When I try to only use the column name for parameter s, I get an an error message: TypeError: ufunc 'sqrt' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
favorite count: 0
has answer: http://stackoverflow.com/a/52413742
upvote count: 2
tagged with: python
answer count: 1
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/52413742
downvote count: 0
has title: pandas.plot argument c vs s

http://stackoverflow.com/q/52373722
type: UnansweredQuestion
has title: Executing Python with apache giving internal server error
tagged with: python
answer count: 0
score: 1
tagged with: cgi
upvote count: 1
type: Question
tagged with: apache2
has body: I'm trying to execute python using Apache2. My apache2.conf file looks like this: .... &lt;Directory /var/www/&gt; Options Indexes FollowSymLinks AllowOverride None Require all granted &lt;/Directory&gt; &lt;Directory /var/www/html&gt; AllowOverride All &lt;/Directory&gt; &lt;Directory /var/www/html/tcd/&gt; Options +ExecCGI AddHandler cgi-script .py &lt;/Directory&gt; .... The python file looks like this: import cgi cgi.test() When I go to the URL that is suppose to execute the script I get the following: I've followed multiple guides to try and get this to work but nothing seems to be working and it is not showing up in my log files. How can I get my apache server to execute Python efficiently?
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/91728146
has text: @MarcelHermus The reason I've gone with using `box_name` and just `name` is because `name` is an attribute of a `Box` object, so using `box_name` is redundant. But when `box_name` is just a variable it's good to be explicit that it's for a box.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52377174
type: Comment

shell
tags question: http://stackoverflow.com/q/52394269
tags question: http://stackoverflow.com/q/52297102
tags question: http://stackoverflow.com/q/52393770
tag name: shell
tags question: http://stackoverflow.com/q/52290482
tags question: http://stackoverflow.com/q/52373862
tags question: http://stackoverflow.com/q/52380342
type: Tag
tags question: http://stackoverflow.com/q/52400010
tags question: http://stackoverflow.com/q/52282175
tags question: http://stackoverflow.com/q/52387563
tags question: http://stackoverflow.com/q/52300323
tags question: http://stackoverflow.com/q/52373206

http://stackoverflow.com/comment/91740118
score: 0
type: QuestionComment
type: Comment
has text: How do I get an output in dollars and/or change like the example rather than just a number like 10.00
comment on: http://stackoverflow.com/q/52397832

http://stackoverflow.com/comment/91623437
type: Comment
has text: @hydra123 `np.zeros([57])[:,None].shape` this so called numpy broadcast
type: AnswerComment
comment on: http://stackoverflow.com/a/52337975
score: 0

http://stackoverflow.com/comment/91712678
has text: That's just a specific case, where he knows the ID of the row he wants to update. It could be a condition like all the rows for the same friend.
score: 0
comment on: http://stackoverflow.com/q/52384084
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52278702
accepted answer of: http://stackoverflow.com/q/52273090
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52273090
has body: The issue here is that you are using MultiLabelBinarizer to: onehot_enc.fit(reviews_tokens)` before splitting into train and test, and test data is leaked to the model and hence higher accuracy. On the other hand, when you use CountVectorizer is only seeing the trained data and then ignoring the words that dont appear in the trained data, which may be valuable to model for classification. So depending on the quantity of your data, this can make a huge difference. Anyways, your second technique (using CountVectorizer) is correct and should be used in case of text data. MultiLabelBinarizer and one-hot encoding in general should be used only for categorical data, not text data. Can you share your complete data?
type: Answer
has comment: http://stackoverflow.com/comment/91666395
score: 0

http://stackoverflow.com/q/52306525
has title: Assign running count to a new column in groups of 3 pandas
has comment: http://stackoverflow.com/comment/91561354
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52307124
tagged with: dataframe
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/91561307
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/52215236
has comment: http://stackoverflow.com/comment/91561218
accepted answer: http://stackoverflow.com/a/52307124
tagged with: pandas
has comment: http://stackoverflow.com/comment/91561121
has comment: http://stackoverflow.com/comment/91562826
has body: I am trying to assign a new column in a pandas df based off values in another 2. In the df below, for each individual value in Location (Home, Away etc) I want to assign an increasing integer for the first 3 corresponding unique values in Day. import pandas as pd import numpy as np d = ({ 'Time' : ['7:00:00','8:00:00','9:00:00','11:00:00','12:00:00','1:00:00','2:00:00','3:00:00'], 'Day' : ['Mon','Tues','Wed','Thurs','Fri','Thurs','Fri','Sat'], 'Location' : ['Home','Home','Home','Away','Away','Home','Home','Home'], }) df = pd.DataFrame(data=d) #Assign values from Home mask = df['Location'] == 'Home' df1 = df[mask].drop_duplicates('Day') d = dict(zip(df1['Day'], np.arange(len(df1)) // 3 + 1)) df.loc[mask, 'Assign'] = df.loc[mask, 'Day'].map(d) #Assign values from Away mask = df['Location'] == 'Away' df1 = df[mask].drop_duplicates('Day') d = dict(zip(df1['Day'], np.arange(len(df1)) // 3 + 1)) df.loc[mask, 'Assign'] = df.loc[mask, 'Day'].map(d) Out: Time Day Location Assign 0 7:00:00 Mon Home 1.0 1 8:00:00 Tues Home 1.0 2 9:00:00 Wed Home 1.0 3 11:00:00 Thurs Away 1.0 4 12:00:00 Fri Away 1.0 5 1:00:00 Thurs Home 2.0 6 2:00:00 Fri Home 2.0 7 3:00:00 Sat Home 2.0 Intended Output: Time Day Location Assign 0 7:00:00 Mon Home 1.0 1 8:00:00 Tues Home 1.0 2 9:00:00 Wed Home 1.0 3 11:00:00 Thurs Away 2.0 4 12:00:00 Fri Away 2.0 5 1:00:00 Thurs Home 3.0 6 2:00:00 Fri Home 3.0 7 3:00:00 Sat Home 3.0
tagged with: assign
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/91589898
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52321077
has text: Can you show us the current code and what have you already tried?

http://stackoverflow.com/a/55151608
type: Answer
upvote count: 2
has body: The chances are you want to put the image in a footer (closer to axel_ande's answer). That way the image will go in the same place on every page, but only be defined once. If you want to put an image at the bottom of a page but not in the footer, you could try the TopPadder wrapper object: from reportlab.platypus.doctemplate import SimpleDocTemplate from reportlab.platypus.flowables import TopPadder from reportlab.platypus import Table, Paragraph from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors import numpy as np document = SimpleDocTemplate('padding_test.pdf') table = Table(np.random.rand(2,2).tolist(), style=[('GRID', (0, 0), (-1, -1), 0.5, colors.black)]) styles = getSampleStyleSheet() paragraph = Paragraph('Some paragraphs', style=styles['Normal']) document.build([ paragraph, TopPadder(table), ]) # This should generate a single pdf page with text at the top and a table at the bottom. I stumbled across this when looking through the code, the only documentation I could find on it was in the release notes. In my example I wrap a table simply so the example code is stand-alone. Hope this helps!
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52322039

http://stackoverflow.com/a/52317845
type: AcceptedAnswer
has body: You have a couple options here. You are starting the process in your ssh session, but then killing the ssh session, which then kills the process. One way to handle this, would be to have the VM run the script on startup. You could set the script as a service, so even if it goes down for some reason it will come back up. Read into init.rc for info on how launch a script at boot on linux. I'm not well-versed in Windows any more but I believe there is a way to do the same. Another option is to keep the session open by connecting to it with screen or tmux. This article explains the problem some and gives you a few different ways to work around the issue: https://www.tecmint.com/keep-remote-ssh-sessions-running-after-disconnection/
type: Answer
answers question: http://stackoverflow.com/q/52317405
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52317405
upvote count: 1

http://stackoverflow.com/a/52361152
answers question: http://stackoverflow.com/q/52360977
type: Answer
has body: ax is matplotlib object that do not have sns attribute, because of this you are getting error. sns is seaborn object. If you want to use ax object with seaborn plot for your case pass parameter ax=ax in seaborn object as follows: fig = plt.figure() fig.subplots_adjust(hspace=0.4, wspace=0.4) ax = fig.add_subplot(2, 2, 1) sns.distplot(df.Principal,ax=ax) ax = fig.add_subplot(2, 2, 2) sns.distplot(df.terms,ax=ax) ax = fig.add_subplot(2, 2, 3) sns.barplot(data = df'Less_than_College', 'college', 'Bachelor',ax=ax) ax.set_xticklabels(ax.get_xticklabels(), rotation=90) ax = fig.add_subplot(2, 2, 4) sns.boxplot(df['age'],ax=ax) plt.show() The plot looks like this.
has comment: http://stackoverflow.com/comment/123829541
upvote count: 12
score: 12
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52360977

http://stackoverflow.com/a/52400006
has comment: http://stackoverflow.com/comment/91953258
has comment: http://stackoverflow.com/comment/91745276
score: 0
answers question: http://stackoverflow.com/q/52399853
has body: roll_counts in show_roll_data(roll_counts) is the name of a parameter and is accessible throughout the scope of the show_roll_data function. Its value is passed in from roll_data in the call show_roll_data(roll_data), and has nothing to do with the local variable of the same name defined in simulate_dice_rolls. That's why you can rename roll_counts in show_roll_data to anything and it would still work.
has comment: http://stackoverflow.com/comment/91748970
has comment: http://stackoverflow.com/comment/91744257
type: Answer
has comment: http://stackoverflow.com/comment/91744550
has comment: http://stackoverflow.com/comment/91745151

tcp
type: Tag
tags question: http://stackoverflow.com/q/52400542
tag name: tcp

http://stackoverflow.com/a/52409895
type: Answer
has body: You may check resample with groupby df['Datetime']=pd.to_datetime(df.date+' '+df.hour)# combine hour and date to datetime df.drop(['date','hour'],inplace=True,axis = 1)# drop duplicate infomation df.groupby('area').\ apply(lambda x : x.set_index('Datetime').resample('H').mean().fillna(0)).\ reset_index() Out[662]: area Datetime output 0 H1 2018-07-01 07:00:00 150.0 1 H1 2018-07-01 08:00:00 150.0 2 H1 2018-07-01 09:00:00 100.0 3 H1 2018-07-01 10:00:00 0.0 4 H1 2018-07-01 11:00:00 150.0 5 H2 2018-07-01 09:00:00 100.0 6 H2 2018-07-01 10:00:00 50.0 7 H2 2018-07-01 11:00:00 50.0 8 H2 2018-07-01 12:00:00 150.0
answers question: http://stackoverflow.com/q/52409712
upvote count: 4
accepted answer of: http://stackoverflow.com/q/52409712
type: AcceptedAnswer
downvote count: 0
score: 4

http://stackoverflow.com/comment/91733951
has text: Where do you see O(1)?
comment on: http://stackoverflow.com/q/52394415
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52283949
has body: I am trying to understand the following code: ... parser=argparse.ArgumentParser parser.add_argument('--test_set', default='liberty', type=str) parser.add_argument('--test_matches', default='xxxxx.txt', type=str) ... def main(args): opt=parser.parse_args(args) ... def load_provider(): p=np.load(opt.test_set)[()] for i.t in enumerate(['matches', 'nonmatches']): p[t] =p['match_data'][opt.test_matches][i] return p ... if __name__=='__main__': main(sys.argv[1:]) So when I cloned the code and downloaded the dataset, liberty is a folder with bmp images and txt files, so when I ran the code I got the following error: IsADirectoryError: [Errno 21] Is a directory: 'liberty' I understand np.load should read a specific file instead of a directory, but I am trying to understand what np.load(opt.test_set)[()] means.
type: AnsweredQuestion
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52284024
answer count: 1
has title: what is np.load(opt.test_set)[()] mean?
has comment: http://stackoverflow.com/comment/91516136
has comment: http://stackoverflow.com/comment/91516496
accepted answer: http://stackoverflow.com/a/52284024
score: 0
has comment: http://stackoverflow.com/comment/91516474
tagged with: python
has comment: http://stackoverflow.com/comment/91516077

http://stackoverflow.com/a/52339003
has comment: http://stackoverflow.com/comment/114347710
has body: The error was fixed on my system, by simply updating one library. To find out where it is coming from, assuming Linux, try the following, LD_DEBUG=files python -c "import cv2" or, LD_DEBUG=files python -c "import cv2 ; img = cv2.imread('myimage.png',0) ; cv2.imshow('image',img) ; cv2.waitKey(0)" On my machine, it failed in one of the blas libraries. I updated that library and the code now runs without error. This is an old bug you can find it discussed in a number of online communities. My test code is as follows. Notably the error has not reoccurred, and apparently has nothing to do with Qt. import cv2 img = cv2.imread('sudoku.png',0) cv2.imshow('image',img) cv2.waitKey(0)
downvote count: 0
has comment: http://stackoverflow.com/comment/106185013
has comment: http://stackoverflow.com/comment/112481681
has comment: http://stackoverflow.com/comment/91625362
answers question: http://stackoverflow.com/q/52337870
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/comment/91702539
has text: try using profiler
comment on: http://stackoverflow.com/q/52374287
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91580109
type: Comment
has text: You're welcome. I'm still struggling with many things with dask and I personally find a little annoying the verbosity of `meta`. Then off course sin and cos are not linear but, I'm guessing, your final aim with x,y,z is 3D-plotting the position of bird on a given yearday and you have lat and lon as mean you should be fine. Finally might I ask if you set the `kubeCluster` by yourself or someone did for you? I'm looking for a tutorial to build my own on AWS.
comment on: http://stackoverflow.com/a/52303939
type: AnswerComment
score: 0

http://stackoverflow.com/a/54917998
score: 2
downvote count: 0
has body: You can save the obj file as an stl file using pymesh OR assimp Then you can load the stl file using numpy-stl
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52317268
type: Answer
answers question: http://stackoverflow.com/q/52317268

http://stackoverflow.com/a/52376110
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52372690
answers question: http://stackoverflow.com/q/52372690
has comment: http://stackoverflow.com/comment/91697321
type: Answer
has body: You want robust linear regression, ignoring the outliers. Such a thing is already implemented in sklearn module but since it's not among the tags, here is a plain SciPy solution. The idea is to minimize the sum of absolute values of deviations (L1 loss function) instead of the sum of squares. (Compare to: median vs mean.) import numpy as np from scipy.optimize import minimize import matplotlib.pyplot as plt x = np.linspace(0.7, 7, 10) y = 0.8*x + 1.2 y[5] = 2.5 # outlier l1_loss = lambda c: np.sum(np.abs(c[0]*x + c[1] - y)) c = minimize(l1_loss, (0, 0)).x plt.plot(x, y, 'b*') plt.plot(x, c[0]*x+c[1], 'r') plt.show() good = np.abs(c[0]*x + c[1] - y) &lt; 0.1 # arbitrary threshold to separate good from bad print('good data: x = {}, y = {}'.format(x[good], y[good])) Output: "good data: x = [0.7 1.4 2.1 2.8 3.5 4.9 5.6 6.3 7. ], y = [1.76 2.32 2.88 3.44 4. 5.12 5.68 6.24 6.8 ]". The line is not perturbed by the outlier at all. You may want to replace good = np.abs(c[0]*x + c[1] - y) &lt; 0.1 with an iterative approach, where the data point with the largest value of deviation, i.e., outlier_idx = np.argmax(np.abs(c[0]*x + c[1] - y)) is identified and removed from x and y arrays (np.delete), then the process repeated until the correlation is good.
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91770500
has comment: http://stackoverflow.com/comment/91867815

http://stackoverflow.com/q/52391315
score: 0
has comment: http://stackoverflow.com/comment/92097363
has body: I am trying to install a complete Python 3.7 environment with the full Anaconda distribution, using the following environment.yml file: name: py37 channels: - anaconda - conda-forge - default dependencies: - anaconda - python=3.7 using conda env create --file environment.yml. Upon completion only the following packages are installed: # # Name Version Build Channel anaconda custom py37_0 anaconda ca-certificates 2018.03.07 0 anaconda certifi 2018.8.24 py37_1 anaconda libcxx 4.0.1 h579ed51_0 anaconda libcxxabi 4.0.1 hebd6815_0 anaconda libedit 3.1.20170329 hb402a30_2 anaconda libffi 3.2.1 h475c297_4 anaconda ncurses 6.1 h0a44026_0 anaconda openssl 1.0.2p h1de35cc_0 anaconda pip 10.0.1 py37_0 anaconda python 3.7.0 hc167b69_0 anaconda readline 7.0 h1de35cc_5 anaconda setuptools 40.2.0 py37_0 anaconda sqlite 3.24.0 ha441bb4_0 anaconda tk 8.6.8 ha441bb4_0 anaconda wheel 0.31.1 py37_0 anaconda xz 5.2.4 h1de35cc_4 anaconda zlib 1.2.11 hf3cbc9b_2 anaconda I am expecting numpy, scipy, etc. What's happening?
tagged with: conda
has comment: http://stackoverflow.com/comment/91748259
has comment: http://stackoverflow.com/comment/91728415
has comment: http://stackoverflow.com/comment/91755059
has comment: http://stackoverflow.com/comment/91727779
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91756317
tagged with: python
has title: Conda fails to install the Anaconda distribution with Python 3.7
has comment: http://stackoverflow.com/comment/91762781
has comment: http://stackoverflow.com/comment/92101045
has comment: http://stackoverflow.com/comment/91728404
has comment: http://stackoverflow.com/comment/92097357
has comment: http://stackoverflow.com/comment/91761264
has comment: http://stackoverflow.com/comment/91727843
type: Question

http://stackoverflow.com/a/52348283
downvote count: 0
has comment: http://stackoverflow.com/comment/91642122
upvote count: 2
has comment: http://stackoverflow.com/comment/91642178
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/91646468
answers question: http://stackoverflow.com/q/52348225
has body: I am assuming new is the result of calling open(..), which should be a file handle that you are passing into the function. Calling readlines() is exhausting it, so trying to read from the file using the same handle won't work. Either open a new handle, or you can call new.seek(0) (better option than opening a completely new handle - although there are some cases where the same handle will be returned again, but lets not dive too deep into that here) to move the index to the beginning of the file.

http://stackoverflow.com/comment/91765464
type: Comment
has text: It is unusual for any program to have a legitimate reason to create more than one thread pool. Have you tried to see what would happen if you simply move the `thread_pool=ThreadPool(30)` to the line before `while True:`?
type: QuestionComment
comment on: http://stackoverflow.com/q/52405340
score: 0

http://stackoverflow.com/q/52368631
has comment: http://stackoverflow.com/comment/91689885
has body: I am trying to learn Scrapy and Python. I'm having an issue I don't understand. I'm running the same piece of code once through the Terminal and then again through a script and the results are different. The Terminal gives me all the titles (what I want) the script just gives me the first. for title in response.css('div.section-content ul'): item = { 'title' : title.css('li h3 a::text').extract_first(), } I'm trying to extract all the movie names on the iTunes movies page. Any help is appreciated. Thanks UPDATE import scrapy class ItunesSpider(scrapy.Spider): name = 'itunes' allowed_domains = ['apple.com'] start_urls = ['apple.com/itunes/charts/movies/'] def parse(self, response): self.log ('I just visited: ' + response.url) for title in response.css('div.section-content ul'): item = { 'title' : title.css('li h3 a::text').extract_first(), } yield item
type: Question
has comment: http://stackoverflow.com/comment/91690514
has comment: http://stackoverflow.com/comment/91689965
has comment: http://stackoverflow.com/comment/91681584
answer count: 1
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91681743
has title: Learning Python and Scrapy
has comment: http://stackoverflow.com/comment/91689647
has answer: http://stackoverflow.com/a/52415212
tagged with: python
has comment: http://stackoverflow.com/comment/91681575
has comment: http://stackoverflow.com/comment/91681619
type: UnansweredQuestion
upvote count: 1
tagged with: scrapy

http://stackoverflow.com/comment/91666656
type: QuestionComment
comment on: http://stackoverflow.com/q/52361110
has text: Just check this link, looks like you are having root permissions https://stackoverflow.com/questions/49181799/conda-update-conda-permission-error
score: 0
type: Comment

http://stackoverflow.com/a/52410274
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/52391422
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52391422
type: Answer
has body: If n = 500000 and m = 5000000, then that is 2.5e12 non-zeroes. For each of these you'd need roughly one double for the non-zero value and one CPXDIM for the index. That is 8+4=12 bytes per non-zero. This would give: &gt;&gt;&gt; print(2.5e12 * 12 / 1024. / 1024. / 1024.) 27939.6772385 Roughly, 28TB of memory! It's not clear exactly how many non-zeros you plan on having, but using this calculation you can easily find out whether it is even possible or not to do what you're asking. As mentioned in the comments, the CPLEX Python API does not accept scipy lil matrices. You could try docplex, which is numpy friendly, or you could even try generating an LP file directly. Using something like the following is probably your best bet in terms of reducing the conversion overhead (I think I made an off-by-one error in the comments section above): my_prob.objective.set_quadratic(list(zip(Q.rows, Q.data))) or my_prob.objective.set_quadratic([[row, data] for row, data in zip(Q.rows, Q.data)])) At any rate, you should play with these to see what gives the best performance (in terms of speed and memory).

http://stackoverflow.com/q/52422865
tagged with: taskkill
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91789099
has comment: http://stackoverflow.com/comment/91790325
possible better answer: http://stackoverflow.com/a/52423209
score: 1
tagged with: process
has answer: http://stackoverflow.com/a/52423209
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52423173
accepted answer: http://stackoverflow.com/a/52463677
has answer: http://stackoverflow.com/a/52422930
has comment: http://stackoverflow.com/comment/91788939
has comment: http://stackoverflow.com/comment/91869273
tagged with: os.system
downvote count: 0
favorite count: 0
has body: I have a command line program which I'd like to keep running until I open it again, so basically a program which first checks if there's currently any already running instance of itself and kill it. I tried os.system('TASKKILL /F /IM program.exe') but it turned out to be stupid because it also kills itself.
has title: How to make a program close it's currently running instance upon startup?
has comment: http://stackoverflow.com/comment/91789468
has answer: http://stackoverflow.com/a/52463677
tagged with: python

http://stackoverflow.com/a/52374623
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52373652
answers question: http://stackoverflow.com/q/52373652
type: AcceptedAnswer
downvote count: 0
has body: If your set of all object (active and inactive) never changes, and especially if transitions between active and inactive state are common, the total number of objects isn't outrageous or the set of inactive objects doesn't usually cover most of the total set, cycle would still work fairly well here, by keeping a set of inactive objects around and filtering out currently inactive objects "live": from itertools import cycle, filterfalse allobjects = [...] numuniqueobjects = len(set(allobjects)) inactiveobjects = set() # Each time we request an item, filterfalse pulls items from the cycle # until we find one that isn't in our inactive set for object in filterfalse(inactiveobjects.__contains__, cycle(allobjects)): # ... do actual stuff with object ... # Any objects that should go active again get removed from the set and will be # seen again the next time their turn comes up in the original order inactiveobjects -= objects_that_should_become_active() # Won't see this object again until it's removed from inactiveobjects if object.should_go_inactive(): inactiveobjects.add(object) if len(inactiveobjects) == numuniqueobjects: # Nothing is active, continuing loop would cause infinite loop break Advantages to this design are that: It makes it cheap to activate and deactivate objects It preserves original iteration order indefinitely (if an object was originally in position 4, when it goes inactive it is skipped, and when it goes active again, it reappears after position 3 and before position 5 the next time you cycle through) The main downside is that it adds a tiny bit more overhead to the "nothing is changing" case, especially if the set of inactiveobjects grows to an appreciable fraction of the total number of objects; you still have to cycle all objects even if filter out many of them. If that doesn't suit your use case, a custom version of cycle built on a deque as suggested by wim is probably the best general purpose solution: from collections import deque from collecti…
score: 1
type: Answer

http://stackoverflow.com/comment/91566008
type: Comment
type: QuestionComment
has text: @eyllanesc the problem seems in the setup of the welcome page here is a glance of the code
comment on: http://stackoverflow.com/q/52300267
score: 0

http://stackoverflow.com/q/52303660
favorite count: 0
has body: I'm trying to denote the predictions with a color and the correct labels as markers for the iris data set. Here is what I have so far: from sklearn.mixture import GMM import pandas as pd from sklearn import datasets import matplotlib.pyplot as plt import itertools iris = datasets.load_iris() x = iris.data y = iris.target gmm = GMM(n_components=3).fit(x) labels = gmm.predict(x) fig, axes = plt.subplots(4, 4) Superman = iris.feature_names markers = ["o" , "s" , "D"] Mi=[] for i in range(150): Mi.append(markers[y[i]]) for i in range(4): for j in range(4): if(i != j): axes[i, j].scatter(x[:, i], x[:, j], c=labels, marker = Mi, s=40, cmap='viridis') else: axes[i,j].text(0.15, 0.3, Superman[i], fontsize = 8) I'm not sure why Colors iterate and markers do not, but is there a way to assign each marker a certain value like color? It also fails when I just enter the numeric values from y. The code it returns is: Unrecognized marker style ['o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 's', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D']
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52304283
has answer: http://stackoverflow.com/a/52303895
tagged with: markers
downvote count: 1
type: Question
has title: iterating markers in plots
tagged with: matplotlib
score: 10
upvote count: 11
answer count: 2

heroku
tags question: http://stackoverflow.com/q/52355653
tags question: http://stackoverflow.com/q/52372170
tags question: http://stackoverflow.com/q/52356064
tags question: http://stackoverflow.com/q/52378074
tags question: http://stackoverflow.com/q/52311724
tags question: http://stackoverflow.com/q/52306938
tags question: http://stackoverflow.com/q/52372214
tags question: http://stackoverflow.com/q/52395651
tags question: http://stackoverflow.com/q/52400481
tags question: http://stackoverflow.com/q/52356362
tags question: http://stackoverflow.com/q/52357782
tags question: http://stackoverflow.com/q/52347984
tags question: http://stackoverflow.com/q/52423143
tags question: http://stackoverflow.com/q/52274578
type: Tag
tags question: http://stackoverflow.com/q/52323897
tags question: http://stackoverflow.com/q/52292555
tag name: heroku
tags question: http://stackoverflow.com/q/52358821

http://stackoverflow.com/q/52279702
has title: Pandas rearrange hour-date excel table into a datetime dataframe
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52279846
answer count: 1
has comment: http://stackoverflow.com/comment/91507746
accepted answer: http://stackoverflow.com/a/52279846
tagged with: python
has comment: http://stackoverflow.com/comment/91508773
type: AnsweredQuestion
tagged with: excel
type: Question
has body: I have an Excel data set that looks like this: 24 25 26 27 1 0,3818 0,0713 0,07222 0,3542 2 0,17802 0,04508 0,06877 0,17319 3 0,22356 0,07314 0,04991 0,22448 4 0,1771 0,07038 0,07406 0,19136 5 0,19389 0,06164 0,05497 0,18538 6 0,20401 0,07475 0,06417 0,21413 7 0,18354 0,07245 0,07337 0,17756 8 0,46184 0,04669 0,0506 0,28819 9 0,43838 0,0667 0,06785 0,4692 10 0,78292 0,07038 0,07291 0,66424 11 1,81792 0,06003 0,04508 1,17001 12 2,40833 0,05451 0,07245 1,08422 13 1,55746 0,07038 0,07314 0,61272 14 1,2075 0,06509 0,04485 0,40871 15 2,4196 0,05014 0,07291 0,27393 16 0,95979 0,07015 0,07291 0,2323 17 0,51681 0,06992 0,04554 0,2024 18 0,46529 0,04232 0,85192 0,35558 19 0,58328 0,06992 1,59321 0,60283 20 1,40185 0,07015 0,82869 1,23326 21 0,71484 0,04692 1,05041 1,01131 22 0,48576 0,07291 0,80707 1,4697 23 0,04278 0,07245 0,57523 1,72316 24 0,07291 0,04554 0,5175 0,61364 The first column represents the hours of the day, the first row the number of day of the year (24 corresponds to the 24th of January, the rows spans all the way through the year, ending on the day number 365) for the year 2013. What I want to obtain is a dataframe which as first column has the date, with year-month-day-hour and for which the respective hourly value is correctly associated. 'date' 'value' 2013-01-24 01:00 0.3818 2013-01-24 02:00 0.17802 2013-01-24 03:00 0.22356 ... The Excel data set Thank you for your help.

flask-restplus
tag name: flask-restplus
tags question: http://stackoverflow.com/q/52317458
tags question: http://stackoverflow.com/q/52280712
type: Tag
tags question: http://stackoverflow.com/q/52325100

http://stackoverflow.com/a/55393827
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/52392407
type: Answer
has body: Load your model with the graph that you created and use that in your session. graph = tf.Graph() with tf.Session(graph = graph) as session: embed = hub.Module("https://tfhub.dev/google/universal-sentence-encoder/2") And use the same graph object in initiate_connection function with session def initiate_connection(conn): data = conn.recv(1024) with tf.Session(graph = graph) as session: session.run([tf.global_variables_initializer(), tf.tables_initializer()]) conn.send(session.run(embed([data]))) conn.close()

http://stackoverflow.com/q/52389667
has comment: http://stackoverflow.com/comment/91741125
type: Question
has body: Given the following dataframe: import pandas as pd import numpy as np indices = [['A', 'B', 'C'], ['a', 'b', 'c', 'd'], ['1', '2', '3']] index = pd.MultiIndex.from_product(indices, names=['first', 'second', 'third']) df = pd.DataFrame(np.random.randint(10, size=(36, 4)), index=index, columns=['Val1','Val2',' Val3', 'Val4']) Which yields, for example: Val1 Val2 Val3 Val4 first second third A a 1 1 7 2 1 2 0 0 8 6 3 3 2 0 5 b 1 3 8 8 8 2 3 1 0 5 3 7 2 8 5 c 1 9 9 5 3 2 2 5 5 8 3 7 5 1 5 d 1 2 7 8 6 2 9 0 0 2 3 9 4 1 4 B a 1 1 2 3 3 2 3 2 3 1 3 1 3 2 2 b 1 4 4 3 1 2 9 4 8 2 3 6 7 8 8 c 1 6 6 3 2 2 2 6 5 6 3 6 4 2 7 d 1 1 1 1 5 2 6 4 8 1 3 3 4 3 1 C a 1 0 3 4 0 2 5 0 1 4 3 1 1 5 7 b 1 2 6 1 7 2 2 6 4 3 3 0 5 6 6 c 1 0 2 3 7 2 7 1 1 1 3 2 6 2 0 d 1 6 2 2 1 2 9 3 1 9 3 7 5 6 1 How would I go about filtering this dataframe by any index level and a specific column value? EDIT For example, if I want to keep all higher level indices (i.e. level=0 and level=1) if the corresponding third index (level=2) of 1 has a Val 2 column value greater than 5. Therefore, if index 1 in the third index does not have a Val2 value greater than 5, then the second level index corresponding to that index would be removed from the dataframe. My attempt at a solution, or to at least convey my intent (since this produces an error): df[df.loc[pd.IndexSlice[:, :, '1'], 'Val2'] &gt; 5] Which gives me the following error: pandas.core.indexing.IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match) In this example, my expected output would be as follows: Val1 Val2 Val3 Val4 first second third A a 1 1 7 2 1 2 0 0 8 6 3 3 2 0 5 b 1 3 8 8 8 2 3 1 0 5 3 7 2 8 5 c 1 9 9 5 3 2 2 5 5 8 3 7 5 1 5 d 1 2 7 8 6 2 9 0 0 2 3 9 4 1 4 B c 1 6 6 3 2 2 2 6 5 6 3 6 4 2 7 C b 1 2 6 1 7 2 2 6 4 3 3 0 5 6 6 Curious if this is achievable with df.filter() or if I am missing a simple way to perform this filtering on a MultiIndex? Thank you in advance.
has comment: http://stackoverflow.com/comment/91741534
has comment: http://stackoverflow.com/comment/91724353
linked to: http://stackoverflow.com/q/28140771
has title: Filtering pandas MultiIndex by specific index at given level and column value
has comment: http://stackoverflow.com/comment/91724213
has comment: http://stackoverflow.com/comment/91724302
score: 0
duplicate of: http://stackoverflow.com/q/28140771
tagged with: pandas
linked to: http://stackoverflow.com/q/49638955
has comment: http://stackoverflow.com/comment/91724504
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: multi-index

http://stackoverflow.com/comment/91611213
type: Comment
has text: Thankyou @ninad
score: 0
comment on: http://stackoverflow.com/q/52325534
type: QuestionComment

ipython
tags question: http://stackoverflow.com/q/52275874
tag name: ipython
type: Tag
tags question: http://stackoverflow.com/q/52297550
tags question: http://stackoverflow.com/q/52310689
tags question: http://stackoverflow.com/q/52311063
tags question: http://stackoverflow.com/q/52385634
tags question: http://stackoverflow.com/q/52348594
tags question: http://stackoverflow.com/q/52298957

http://stackoverflow.com/comment/91660445
type: QuestionComment
has text: @Chris I am using pynput
score: 0
comment on: http://stackoverflow.com/q/52357098
type: Comment

http://stackoverflow.com/comment/91634530
comment on: http://stackoverflow.com/q/52344254
has text: `from itertools import islice` and `for row in islice(readcsv, 5):` limits the loop to 5 iterations.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91522994
type: Comment
type: QuestionComment
has text: If no one answers, I recommend trying it out.
score: 0
comment on: http://stackoverflow.com/q/52286018

http://stackoverflow.com/a/52417631
type: Answer
has comment: http://stackoverflow.com/comment/91778367
has body: You should match the optional groups of digits preceded by a dot: if re.findall(r'(%s-\d+(?:\.\d+)*):'%project,line):
has comment: http://stackoverflow.com/comment/91778430
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91778537
has comment: http://stackoverflow.com/comment/91778798
has comment: http://stackoverflow.com/comment/91778595
answers question: http://stackoverflow.com/q/52417517
has comment: http://stackoverflow.com/comment/91778417
accepted answer of: http://stackoverflow.com/q/52417517
has comment: http://stackoverflow.com/comment/91779018
has comment: http://stackoverflow.com/comment/91778474
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91778398
has comment: http://stackoverflow.com/comment/91778521

http://stackoverflow.com/a/52301233
downvote count: 0
answers question: http://stackoverflow.com/q/52298922
has comment: http://stackoverflow.com/comment/91582462
has comment: http://stackoverflow.com/comment/91582919
has body: Your threads are queuing callbacks in their respective event loops, but they exit before actually running the event loop, so the callbacks never get executed. Also, you don't need call_soon_threadsafe, since you are invoking the callback from the same thread the event loop is (or, rather, will be) running on. This code prints the expected output: import asyncio from threading import Thread def hello(thread_name): print('hello from thread {}!'.format(thread_name)) event_loop_a = asyncio.new_event_loop() event_loop_b = asyncio.new_event_loop() def callback_a(): asyncio.set_event_loop(event_loop_a) asyncio.get_event_loop().call_soon(lambda: hello('a')) event_loop_a.run_forever() def callback_b(): asyncio.set_event_loop(event_loop_b) asyncio.get_event_loop().call_soon(lambda: hello('b')) event_loop_b.run_forever() thread_a = Thread(target=callback_a, daemon=True) thread_b = Thread(target=callback_b, daemon=True) thread_a.start() thread_b.start() A more typical use case for call_soon_threadsafe, and more in line with what you might have had in mind, is to submit a callback (or a coroutine using asyncio.run_coroutine_threadsafe) to an event loop running in another thread. Here is an example: import asyncio, threading def hello(thread_name): print('hello from thread {}!'.format(thread_name)) event_loop_a = asyncio.new_event_loop() event_loop_b = asyncio.new_event_loop() def run_loop(loop): asyncio.set_event_loop(loop) loop.run_forever() threading.Thread(target=lambda: run_loop(event_loop_a)).start() threading.Thread(target=lambda: run_loop(event_loop_b)).start() event_loop_a.call_soon_threadsafe(lambda: hello('a')) event_loop_b.call_soon_threadsafe(lambda: hello('b')) event_loop_a.call_soon_threadsafe(event_loop_a.stop) event_loop_b.call_soon_threadsafe(event_loop_b.stop) In that case it is rarely needed to have more than one event loop thread - you'd typically create only one, and allow that thread to service all your asyncio needs. After all, being able to host a large n…
type: Answer
upvote count: 29
has comment: http://stackoverflow.com/comment/91582607
score: 29
accepted answer of: http://stackoverflow.com/q/52298922
type: AcceptedAnswer

http://stackoverflow.com/a/52398538
downvote count: 0
has comment: http://stackoverflow.com/comment/91741424
answers question: http://stackoverflow.com/q/52398186
type: Answer
score: 1
has body: Reference Link: http://docs.python-requests.org/en/master/api/ You can use requests module of python like so import requests Req = requests.request( method = "GET", # or "POST", "PUT", "DELETE", "PATCH" etcetera url = "http(s)://*", params = {"key": "value"}, # IF GET Request (Optional) data = {"key": "value"}, # IF POST Request (Optional) headers = {"header_name": "header_value"} # (Optional) ) print Req.content You can surround the code with try::catch block like below to catch any exception thrown by requests module try: # requests.request(** Arguments) except requests.exceptions.RequestException as e: print e For full argument list, please check reference link.
upvote count: 1
has comment: http://stackoverflow.com/comment/91741326

http://stackoverflow.com/comment/91586183
type: Comment
type: QuestionComment
has text: I have a file in Notepad ++, and I would like to edit it with python following the pattern that add a new line with "M19" before each "M06".
comment on: http://stackoverflow.com/q/52319319
score: 0

http://stackoverflow.com/comment/133333690
has text: Have you tried setting the the number of workers and threads per workers as dask setting? Maybe you can try something like: `with dd.LocalCluster(n_workers=1, threads_per_worker=5, memory_limit='15GiB') as cluster, dd.Client(cluster, set_as_default=True) as client:` and adapt the values for your machine? ok, I just saw, that any comments are most likely too late :D
comment on: http://stackoverflow.com/q/52374936
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52340216
answers question: http://stackoverflow.com/q/52339411
score: 0
has body: I could not reproduce your error using the same code; assume because of discrepancy in browser, driver or Selenium versions. Also, keep in mind: different browsers can parse HTML/XML differently, so you might find discrepancies between browsers using xPath. CSS selectors are preferable and also less brittle insofar as easier to avoid deeply nested paths. environment os: macOS 10.10.5 Python: 3.6.1 Selenium: 3.14.0 Gecko driver: 0.21.0 Firefox: 62.0 code from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("https://www.autotrader.com/cars-for-sale/searchresults.xhtml?zip=84025&amp;keywordPhrases=rebuilt%20title&amp;startYear=2014&amp;endYear=2018&amp;sellerTypes=p&amp;searchRadius=0&amp;sortBy=derivedpriceDESC&amp;numRecords=25&amp;firstRecord=0") keyword_text_field = driver.find_element_by_xpath('//*[@id="558450155"]') keyword_text_field.clear() keyword_text_field.send_keys('Ford') search_button = driver.find_element_by_xpath('//*[@id="mountNode"]/div/div[4]/div[3]/div[1]/div[1]/div/div[2]/div/div[18]/div[2]/button') search_button.click() driver.close()
type: Answer

http://stackoverflow.com/q/52349684
tagged with: tkinter-canvas
has comment: http://stackoverflow.com/comment/91751245
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91644657
tagged with: tkinter
answer count: 0
has comment: http://stackoverflow.com/comment/91751461
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91659270
has title: AttributeError: 'AxesSubplot' object has no attribute 'set_canvas'
has comment: http://stackoverflow.com/comment/91809043
has body: Good morning, I am using tkinter with matplotlib but I am facing a problem which I will write down. I tried many solution but nothing worked, so if you had faced the problem before or if you just know it help me please with it. Here is my code: import matplotlib matplotlib.use('TkAgg') from tkinter import * import tkinter.simpledialog import matplotlib.pyplot as plt import datetime from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg root = Tk() root.geometry('1000x600') middle = Frame(root) middle.pack() payments = {'.':0} m = datetime.datetime.now() def digram1(): global m purpose = list(payments.keys()) amounts = list(payments.values()) plt.plot((purpose),(amounts)) plt.xlabel('Purpose') plt.ylabel('Amounts') plt.title('Outgoings for the '+ str(m.month)+'th month\n'+str(datetime.date.today())) plt.show fig = Figure(figsize=(5,5),dpi = 100) ex = fig.add_subplot(111) canvas = FigureCanvasTkAgg(ex,master=root) canvas.show() canvas.get_tk_widget().pack(side =tk.top,fill=tk.Both, expand = True) digram1m = Button(middle,text='1st digram',command=digram1, height = 5,width =15 , fg ='green') digram1m.grid(row = 5 , column = 6 ,sticky=E) root.mainloop() and here is the output: Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\A\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) File "&lt;ipython-input-1-6c5b0c8eaae5&gt;", line 33, in digram1 canvas = FigureCanvasTkAgg(ex,master=root) File "C:\Users\A\Anaconda3\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 173, in __init__ FigureCanvasAgg.__init__(self, figure) File "C:\Users\A\Anaconda3\lib\site-packages\matplotlib\backend_bases.py", line 1780, in __init__ figure.set_canvas(self) AttributeError: 'AxesSubplot' object has no attribute 'set_canvas' I am using Jupyter notebook 5.4.0. Thank you for your time..
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91644580
type: Question
has comment: http://stackoverflow.com/comment/91810980
has comment: http://stackoverflow.com/comment/91658854

http://stackoverflow.com/q/52369437
tagged with: seaborn
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91683615
tagged with: lambda
score: 2
answer count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/91683415
has body: I have a CSV with the fields "Description" and "Area". I want to graph how many are in each area. I am getting the following error when I run my code: ----&gt; 4 sns.countplot(x = feedback_df['Area'], order = varieties, ax = ax) ValueError: min() arg is an empty sequence Here is the code I am running to give a first pass at this : feedback = pd.read_csv('feedback.csv') feedback[feedback['Description'].duplicated(keep = False)].sort_values('Description').head(8) feedback = feedback.drop_duplicates('Description') feedback_df = feedback.groupby('Area').filter(lambda x: len(x) &gt; 10599) Types = feedback_df['Area'].value_counts().index.tolist() fig, ax = plt.subplots(figsize = (25, 10)) sns.countplot(x = variety_df['Area'], order = varieties, ax = ax) plt.xticks(rotation = 90) plt.show()
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/33151453
has title: Python - ValueError: min() arg is an empty sequence when plotting graph from CSV
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python-3.x

http://stackoverflow.com/comment/91505316
type: AnswerComment
type: Comment
has text: That's slightly misleading, though, because what `id()` returns is *not* the ID of the `Global_number` variable, but the ID of the *object* that `Global_number` currently refers to. If you change `Global_number` to refer to a different object, then `id()` will return the ID of that object instead: that's how names work in Python.
score: 1
comment on: http://stackoverflow.com/a/52278589

http://stackoverflow.com/q/52339314
downvote count: 0
score: 1
type: Question
tagged with: reactjs
has answer: http://stackoverflow.com/a/53877642
tagged with: react-table
upvote count: 1
answer count: 1
has body: I'm having trouble getting data from the backend (Python API) to show in react-table manually. I've read the documentation and I'm trying to use the example here: https://react-table.js.org/#/story/server-side-data I'm only seeing data in one column and only for 6 records which is really weird. It's probably the way I'm mixing in async/await syntax with the example code which uses a promise. I was able to create a simple react-table fetching data with the same async/await syntax, but when I added the server-side data code from the example (the requestData function) it wouldn't work. I've spent days on this and looking all over Stackoverflow and the internet. I'm a newbie so please go easy on me. Here's what I have: import React from 'react' import { render } from 'react-dom' import ReactTable from 'react-table' import api from 'src/api' import { orderBy } from 'lodash' // importing react-table css would not work so I added it using cdn link const requestData = async (pageSize, page, sorted, filtered) =&gt; { // api is a wrapper for axios.create() const rawData = await api.admin.exercise.feed() return new Promise((resolve, reject) =&gt; { let filteredData = rawData; if (filtered.length) { filteredData = filtered.reduce((filteredSoFar, nextFilter) =&gt; { return filteredSoFar.filter(row =&gt; { return (row[nextFilter.id] + "").includes(nextFilter.value); }); }, filteredData); } const sortedData = orderBy( filteredData, sorted.map(sort =&gt; { return row =&gt; { if (row[sort.id] === null || row[sort.id] === undefined) { return -Infinity; } return typeof row[sort.id] === "string" ? row[sort.id].toLowerCase() : row[sort.id]; }; }), sorted.map(d =&gt; (d.desc ? "desc" : "asc")) ); const res = { rows: sortedData.slice(pageSize * page, pageSize * page + pageSize), pages: Math.ceil(filteredData.length / pageSize) }; resolve(res); }); }; export class ExerciseList extends React.Component { constructor() { super(); this.state = { data: [], pages: null, loading: true }; this.fet…
favorite count: 0
has title: react-table not rendering server-side data in table (with manual pagination, filtering & sorting)
type: UnansweredQuestion
tagged with: python
tagged with: axios

distinct
tag name: distinct
type: Tag
tags question: http://stackoverflow.com/q/52314725

http://stackoverflow.com/q/52284676
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52284699
type: Question
has title: how to convert a column of string to a list
answer count: 2
score: 0
duplicate of: http://stackoverflow.com/q/952914
possible better answer: http://stackoverflow.com/a/52284932
has answer: http://stackoverflow.com/a/52284932
accepted answer: http://stackoverflow.com/a/52284699
has body: I have select a string column from a table. Now I want to take all the values and convert to a list of string. I used the following code but it does not work. top_feature = rf_varimp'variable'.values.tolist() top_feature the output is: [['mrkd100006'], ['mrkd100005'], ['ccs2376'], ['ccs644'], ['ccs3262']] what I expect for the output is something like: ['mrkd100006', 'mrkd100005', 'ccs2376', 'ccs644', 'ccs3262']
tagged with: python
linked to: http://stackoverflow.com/q/952914

database-testing
tags question: http://stackoverflow.com/q/52300270
type: Tag
tag name: database-testing

http://stackoverflow.com/comment/91679806
score: 0
has text: @Tarun.P Thanks for the suggestion. I will try your advice but I think it will be difficult to reproduce this error. At first, I suspected alias of the query result has some connection to the problem, but it's not...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52364695

http://stackoverflow.com/q/52283411
downvote count: 1
type: Question
tagged with: url-parameters
has comment: http://stackoverflow.com/comment/91516042
linked to: http://stackoverflow.com/q/32235698
duplicate of: http://stackoverflow.com/q/32235698
answer count: 1
has title: How to get parameters from URL in python flask
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
has answer: http://stackoverflow.com/a/52283986
tagged with: python
type: AnsweredQuestion
score: 0
has body: I have following codes: {{ q.title }} {{ q.text }} Answer and in the flask I have this code: @app.route("/answer" , methods=['GET']) def answer(): atitle = request.args.get('t') return render_template('answer.html' , value=atitle) I tried differend ways and also used: @app route("/answer/<t>" , methods=['GET']) but none of them is working and I keep recieving "GET /answer/Java HTTP/1.1" 404
upvote count: 1
tagged with: web-services
accepted answer: http://stackoverflow.com/a/52283986

http://stackoverflow.com/q/52420056
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52429837
type: UnansweredQuestion
tagged with: python
has body: I'd like to take a list of 1000 np.ndarrays (each element in the list is an array whose shape is 3X3X8) and use this list as a pandas DataFrame column, so that each cell in the column is a matrix. How can it be accomplished?
upvote count: 1
has comment: http://stackoverflow.com/comment/91784006
type: Question
linked to: http://stackoverflow.com/q/19574258
score: 1
tagged with: dataframe
tagged with: pandas
downvote count: 0
answer count: 1
has title: putting matrix in one pandas DataFrame cell
favorite count: 0

http://stackoverflow.com/a/52316070
has body: I have fixed the code for you. You were calling the function twice so it ran it twice. Once when you wanted it to in the first function but again in the second function when you wanted to get the number of players again. You can use a global variable for this since the number of players won't change. def getNumberOfPlayers(): global numberPlayers numberPlayers = int(input('Enter number of players (2-4): ')) if numberPlayers &lt;2 or numberPlayers &gt;4: numberPlayers = int(input('Invalid: Enter number of players (2-4): ')) print('Thanks, there are', numberPlayers, 'players in the game') return numberPlayers def getNameOfPlayers(): playerNames=[] for i in range (numberPlayers): names=input('Enter a player name, then press enter: ') playerNames.append(names) print(playerNames) print('Player 1 is', playerNames[0]) print('Players 2 is', playerNames[1]) return playerNames getNumberOfPlayers() getNameOfPlayers()
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52315965
answers question: http://stackoverflow.com/q/52315965
has comment: http://stackoverflow.com/comment/91580096
type: Answer
has comment: http://stackoverflow.com/comment/91580074

http://stackoverflow.com/q/52276651
has answer: http://stackoverflow.com/a/52276697
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: css
downvote count: 0
type: UnansweredQuestion
tagged with: django
has body: django - I don't see anything from database when i want to display the contents on cards/index page. in the admin section it's working but here not working. BTW sorry my bad communication urls.py from django.urls import path from . import views urlpatterns = [ path('', views.all_id_cards), ] views.py from django.shortcuts import render from .models import IdCard def all_id_cards(request): cards = IdCard.objects.all() return render(request, 'cards/cards_index.html', { 'cards': cards }) models.py from django.db import models # Create your models here. class IdCard(models.Model): emp_id = models.CharField(max_length=12) emp_name = models.CharField(max_length=40) emp_title = models.CharField(max_length=30) emp_telephone = models.CharField(max_length=12) emp_email = models.CharField(max_length=30) emp_generation = models.CharField(max_length=20) emp_status = models.CharField(max_length=20) def __str__(self): return self.emp_name cards_index.html Homepage Identity Cards {% for cards in cards %} {{ IdCard.emp_name }} {% endfor %}
score: 1
tagged with: database
type: Question
has title: django - I don't see anything from database when i want to display the contents on cards/index page
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/a/58072486
has comment: http://stackoverflow.com/comment/139431733
downvote count: 0
score: 26
upvote count: 26
type: Answer
has body: First update and then install python3-pip. So the following two commands should work. sudo add-apt-repository universe sudo apt-get update sudo apt-get install python3-pip
answers question: http://stackoverflow.com/q/52394543

http://stackoverflow.com/q/52424068
tagged with: routes
answer count: 2
has comment: http://stackoverflow.com/comment/91792046
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52427570
upvote count: 2
possible better answer: http://stackoverflow.com/a/52460634
tagged with: python
has answer: http://stackoverflow.com/a/52460634
score: 2
type: AnsweredQuestion
tagged with: subnet
has comment: http://stackoverflow.com/comment/91792092
tagged with: ip
type: Question
accepted answer: http://stackoverflow.com/a/52427570
has comment: http://stackoverflow.com/comment/91792652
has title: If I have a starting and an ending IP, how can I find the subnet?
has body: I need to block some IPs from some countries but I'm only given the starting IP and the ending IP like this: 11.22.33.44 - 11.22.35.200 I'd like to calculate the subnet to have it like this: (not accurate) 11.22.33.44/14 How can I determine the subnet given an IP address range in Python?

http://stackoverflow.com/comment/139908957
type: Comment
has text: Clean and easy approach. Thanks for point out.
comment on: http://stackoverflow.com/a/73420463
score: 0
type: AnswerComment

http://stackoverflow.com/q/52328327
answer count: 0
has comment: http://stackoverflow.com/comment/91603475
type: Question
has comment: http://stackoverflow.com/comment/91603583
has comment: http://stackoverflow.com/comment/91603610
has comment: http://stackoverflow.com/comment/91603618
score: 0
tagged with: bash
has title: python 3 EOFError: EOF when reading a line %%bash
tagged with: python-3.x
has body: %%writefile mains_script.py from math import pi def mains(): def circle_area(r): return pi * (r ** 2) def circle_circumference(r): return 2 * pi * r radius = float(input("Enter radius: ")) print("Area =", circle_area(radius)) print("Circumference =", circle_circumference(radius)) if (__name__ == '__main__'): mains() %%bash python3 mains_script.py Traceback (most recent call last): File "mains_script.py", line 23, in &lt;module&gt; mains() File "mains_script.py", line 16, in mains radius = float(input("Enter radius: ")) EOFError: EOF when reading a line I treid try, exceptEOFError:break. it returns "break outside loop" def circle_circumference(r): return 2 * pi * r try: radius = float(input("Enter radius: ")) print("Area =", circle_area(radius)) print("Circumference =", circle_circumference(radius)) except EOFError: break if (__name__ == '__main__'): mains() File "mains_script.py", line 21 break ^ SyntaxError: 'break' outside loop I tried try,except EOFError: return too. it just print radius:, then stops there. Please help. ignore for word requirementsignore for word requirementsignore for word requirements
type: UnansweredQuestion
tagged with: eoferror
tagged with: python

http://stackoverflow.com/q/52308953
score: 1
accepted answer: http://stackoverflow.com/a/52309184
upvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91564979
answer count: 2
has answer: http://stackoverflow.com/a/52309120
downvote count: 0
has answer: http://stackoverflow.com/a/52309184
has title: the the step size problem in linespace function
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52309120
tagged with: python
type: AnsweredQuestion
has body: import numpy as np z=np.linspace(10,20,5) z1=np.linspace(10,20,5,endpoint=False) print(z) print(z1) The first z is printed out: [ 10. 12.5 15. 17.5 20.] The Second z1 is printed out: [ 10. 12. 14. 16. 18.] My confusion: when it is z, endpoint=True, the number of equally spaced samples to be generated, num=5, that is, five Numbers, so there are four steps, and it's easy to calculate that each step is 2.5. But: when it is z1, endpoint=False, according to endpoint definition: if the sequence contains 20, it will be rejected, but the sequence is still 5 Numbers, 4 steps long, why is the last number of sequences 18. Not 19. Or other?

http://stackoverflow.com/q/52425824
has body: I have a problem about how to reload pytorch model with different batch size. In training, my batch size is 64, but in inference, I would like the batch size is 1(feed data one by one). This is the code I used to save and restore model: torch.save(agent.qnetwork_local.state_dict(), './ckpt/checkpoint.pth') saved_model = QNetwork(state_size=37, action_size=4, seed=0) saved_model.load_state_dict(torch.load('./ckpt/checkpoint.pth')) And I got this error when running the inference model: RuntimeError: size mismatch, m1: [37 x 1], m2: [37 x 64] at /Users/soumith/code/builder/wheel/pytorch-src/aten/src/TH/generic/THTensorMath.cpp:2070 This error means the model's input must be 37x64, where 37 is the data dimension and 64 is the training batch size. But testing input is 37x1 which means data dimension is 37 and batch size is 1. Is there any solution to different batch size in reload pytorch model? Thank you very much.
favorite count: 0
has comment: http://stackoverflow.com/comment/91876584
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53795685
has title: pytorch restore model with different batch size
tagged with: python
has comment: http://stackoverflow.com/comment/91819144
has comment: http://stackoverflow.com/comment/94440121
tagged with: pytorch
has comment: http://stackoverflow.com/comment/91829926
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/53901285
has comment: http://stackoverflow.com/comment/91829504
upvote count: 5
tagged with: neural-network
score: 4
answer count: 2
tagged with: deep-learning

http://stackoverflow.com/comment/91865020
type: Comment
comment on: http://stackoverflow.com/q/52397563
score: 0
type: QuestionComment
has text: Have you tried running flask with uWSGI and at least 2 threads?

http://stackoverflow.com/a/52294262
answers question: http://stackoverflow.com/q/52294174
has body: You can use enumerate to keep track of the original index before you slice the list with k as the starting index: from operator import itemgetter def find_min_index(A, k): return min(list(enumerate(A))[k:], key=itemgetter(1))[0] so that: print(find_min_index([1, 2, 5, -1], 0)) print(find_min_index([1, 1, 1, 5, 9], 2)) would output: 3 2
score: 0
type: Answer

http://stackoverflow.com/q/52342123
downvote count: 0
tagged with: python-2.7
answer count: 1
favorite count: 0
has title: I would like to add a scroll bar to a QVBoxLayout
tagged with: pyside2
has answer: http://stackoverflow.com/a/52347035
tagged with: python
score: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52347035
has body: How do I add a scroll bar to my QVBoxLayout in PySide2. self.mainWidget = QtWidgets.QWidget() self.window.setCentralWidget(self.mainWidget) self.vertical_layout_main = QtWidgets.QVBoxLayout(self.mainWidget) scroll = QtWidgets.QScrollArea() scroll.setWidget(self.vertical_layout_main) scroll.setFixedHeight(400) self.vertical_layout_main.addWidget(scroll) Update: def populate_lights(self): self.vertical_layout_lights = QtWidgets.QVBoxLayout(self.mainWidget) self.vertical_layout_main.addLayout(self.vertical_layout_lights) for light in self.lights: horizontal_layout_light = QtWidgets.QVBoxLayout(self.mainWidget) light_label = QtWidgets.QPushButton(light) light_label.setCheckable(True) light_label.toggled.connect(partial(self.light_label_event,light)) horizontal_layout_light.addWidget(light_label) self.vLayout.addLayout(horizontal_layout_light) def light_palette_ui(self): self.vertical_layout_main = QtWidgets.QVBoxLayout(self.mainWidget) self.scroll_widget = QtWidgets.QWidget() self.scroll_widget.setLayout(self.vertical_layout_main) self.scroll = QtWidgets.QScrollArea() self.scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.scroll.setWidgetResizable(False) self.scroll.setWidget(self.scroll_widget) self.vLayout = QtWidgets.QVBoxLayout(self.mainWidget) self.vLayout.addWidget(self.scroll) self.populate_lights() self.window.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.window.show()
type: Question
upvote count: 4

http://stackoverflow.com/comment/91737244
has text: @AnYan No need for `if`, `sys.argv` values are always strings
comment on: http://stackoverflow.com/a/52380563
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52304816
favorite count: 0
has answer: http://stackoverflow.com/a/52304838
type: UnansweredQuestion
score: -3
tagged with: python
has title: find the index i of a sorted array y[:], such that y[i-1] <= x <y[i]
has body: getindex(x,y) Input: a value x, and a sorted array y[:] (no repeat element) Output: the index i, such that y[i-1] &lt;= x &lt;y[i] The time complexity should be O(log(N)) Is there a Python/Numpy function we can use? For example: y[0]=-0.2 y[1]=1.5 y[2]=1.9 y[3]=3.2 Then getindex(-4.0,y) returns 0 getindex(0.5,y) returns 1 getindex(6.0,y) returns 4
downvote count: 3
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/25081644
tagged with: sorting
duplicate of: http://stackoverflow.com/q/25081644
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/91566992
has text: OK, removing my comment. But author should be more careful :)
comment on: http://stackoverflow.com/a/52309878
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/52331595
possible better answer: http://stackoverflow.com/a/52331659
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/52331659
has comment: http://stackoverflow.com/comment/91610132
downvote count: 1
has comment: http://stackoverflow.com/comment/91611312
has comment: http://stackoverflow.com/comment/91610698
type: Question
has answer: http://stackoverflow.com/a/52335595
score: 1
has answer: http://stackoverflow.com/a/52333180
linked to: http://stackoverflow.com/q/1098549
has comment: http://stackoverflow.com/comment/91610331
has title: The right way to use **kwargs in Python
has comment: http://stackoverflow.com/comment/91610036
has answer: http://stackoverflow.com/a/52331715
tagged with: keyword-argument
answer count: 6
favorite count: 0
accepted answer: http://stackoverflow.com/a/52335595
has answer: http://stackoverflow.com/a/52331989
has body: I took a look at this question but it doesn't exactly answer my question. As an example, I've taken a simple method to print my name. def call_me_by_name(first_name): print("Your name is {}".format(first_name)) Later on, I realized that optionally, I would also like to be able to print the middle name and last name. I made the following changes to accommodate that using **kwargs fearing that in the future, I might be made to add more fields for the name itself (such as a 3rd, 4th, 5th name etc.) I decided to use **kwargs def call_me_by_name(first_name,**kwargs): middle_name = kwargs['middle_name'] if kwargs.get('middle_name') else "" last_name = kwargs['last_name'] if kwargs.get('last_name') else "" print("Your name is {} {} {}".format(first_name,middle_name,last_name)) My only concern here is that as I continue to implement support for more names, I end up writing one line of code for every single keyword argument that may or may not come my way. I'd like to find a solution that is as pythonic as possible. Is there a better way to achieve this ? EDIT 1 I want to use keyword arguments since this is just an example program. The actual use case is to parse through a file. The keyword arguments as of now would support parsing a file from 1) A particular byte in the file. 2) A particular line number in the file. Only one of these two conditions can be set at any given point in time (since it's not possible to read from a particular byte offset in the file and from a line number at the same time.) but there could be more such conditions in the future such as parse a file from the first occurrence of a character etc. There could be 10-20 different such conditions my method should support BUT only one of those conditions would ever be set at any time by the caller. I don't want to have 20-30 different IF conditions unless there's no other option.
has answer: http://stackoverflow.com/a/52331667
tagged with: python

http://stackoverflow.com/comment/91715668
score: 0
has text: What's exactly your problem? Is your code not working? Or you need to add the other information to your email address?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52385753

http://stackoverflow.com/comment/91712086
type: QuestionComment
type: Comment
has text: @DiabJerius We were able to implement it using Inline C as you suggested. Thank you. We added your solution to our summarized answer below.
comment on: http://stackoverflow.com/q/52366418
score: 0

http://stackoverflow.com/q/52392398
tagged with: serial-port
tagged with: python
has comment: http://stackoverflow.com/comment/91835447
score: 2
has comment: http://stackoverflow.com/comment/91803040
tagged with: beagleboneblack
type: AnsweredQuestion
has title: pyserial/Modbus - troubleshooting "No communication with instrument"
tagged with: beagleboard
downvote count: 0
has comment: http://stackoverflow.com/comment/91837581
has comment: http://stackoverflow.com/comment/91834627
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/91730084
accepted answer: http://stackoverflow.com/a/52498930
has body: Beaglebone Black Wireless: Ubuntu 16.04, Computer: Ubuntu 16.04, Python 3.5.2 I am trying to communicate with a device via Modbus using a Beaglebone Black. I have read of people doing this same thing with a USB/RS485 dongle using minimalmodbus. I've tried changing up the settings; every possible baud rate, shorter cable, etc. There must be something within the Beagle that needs to be configured/is mis-configured for this type of work. Code #!/usr/bin/env python # -*- coding; utf-8 -*- import minimalmodbus import serial import time i = minimalmodbus.Instrument(port='/dev/ttyUSB0', slaveaddress=1, mode='rtu') i.serial.baudrate = 115200 i.serial.bytesize = 8 i.serial.parity = serial.PARITY_EVEN i.serial.stopbits = 1 i.serial.timeout = 1 i.handle_local_echo = None while True: try: print(i.read_registers(2008, 2, 3)) except serial.serialutil.SerialException as error: print(error) except FileNotFoundError as error2: print(error2) except IOError as error3: print(error3) time.sleep(1) ...using a USB/RS485 dongle. Using this dongle/code combination yields perfect results on my computer (for the past 4 months) but not the Beagle today. Computer: Message received: [0, 0] Beagle: Error received: IOError: No communication with instrument (no answer) I am looking for possible avenues of troubleshooting. I have verified that the cable is not too long, and the USB dongle is OK. I have also ruled out any code issues. Edit 1: Forgot to include lsusb and ls /dev/ttyUSB*: Bus 002 Device 004: ID 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter Bus 002 Device 003: ID 04d9:0024 Holtek Semiconductor, Inc. Bus 002 Device 002: ID 0409:0059 NEC Corp. HighSpeed Hub Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub and /dev/ttyUSB0 Edit 2: I am able to achieve a loopback setup using pyserial and shorting the Rxd and Txd + and - terminals. Edit 3: I have tried all possible wiring configurations. Only one configura…
has comment: http://stackoverflow.com/comment/91835273
has answer: http://stackoverflow.com/a/52498930
answer count: 1
tagged with: minimalmodbus
has comment: http://stackoverflow.com/comment/91834528
has comment: http://stackoverflow.com/comment/91820376
favorite count: 0
has comment: http://stackoverflow.com/comment/91835537
has comment: http://stackoverflow.com/comment/91835108
has comment: http://stackoverflow.com/comment/91761929

http://stackoverflow.com/q/52393234
downvote count: 1
tagged with: ncurses
type: Question
has answer: http://stackoverflow.com/a/52395211
score: 0
has title: Curses isn't registering mouse clicks in Python
answer count: 1
has body: I want to make naughts and crosses (or tic-tac-toe in some places) in Python. Here is my code so far. import curses board = {"1A": " ", "2A": " ", "3A": " ", "1B": " ", "2B": " ", "3B": " ", "1C": " ", "2C": " ", "3C": " "} s = curses.initscr() sh, sw = s.getmaxyx() w = curses.newwin(sh, sw, 0, 0) curses.mousemask(1) w.nodelay(False) def printboard(): w.addstr(sh // 2 - 2, sw // 2 - 4, "{} | {} | {}".format(board.get("1A"), board.get("2A"), board.get("3A"))) w.hline(sh // 2 - 1, sw // 2 - 4, "-", 9) w.addstr(sh // 2, sw // 2 - 4, "{} | {} | {}".format(board.get("1B"), board.get("2B"), board.get("3B"))) w.hline(sh // 2 + 1, sw // 2 - 4, "-", 9) w.addstr(sh // 2 + 2, sw // 2 - 4, "{} | {} | {}".format(board.get("1C"), board.get("2C"), board.get("3C"))) while True: printboard() w.addstr(sh // 2 + 4, 1, "Naught's turn. Click on where you would like to place your naught.") w.refresh() event = w.getch() if event == curses.KEY_MOUSE: _, mousex, mousey, _, _ = curses.getmouse() print(mousex, mousey) w.refresh() I've read the docs, and the code looks correct. When I run it in the terminal, the board appears, and it prints the text. But when I left click, the program does nothing. I don't know what's wrong with it. EDIT: Found out why it wasn't working. I just added curses.mousemask(curses.BUTTON1_CLICKED) before w.nodelay(False) and w.keypad(True) after w.nodelay(False).
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: curses
tagged with: mouse
upvote count: 1

http://stackoverflow.com/a/52397060
answers question: http://stackoverflow.com/q/52396963
has body: Try splitting the words and use indices: pdf_content = "the quick brown fox jumps over the lazy dog" word = "brown" words = pdf_content.split() pos = words.index(word) found = word if pos &gt; 0: found = words[pos - 1] + " " + found if pos &lt; len(words) - 1: found = found + " " + words[pos + 1] print(found)
score: 0
type: Answer

http://stackoverflow.com/comment/91533189
type: QuestionComment
comment on: http://stackoverflow.com/q/52290839
score: 0
has text: The output for `type(df['images'][0])` is `numpy.ndarray`. The shape, `df['images'][0].shape` is `(48, 48)`
type: Comment

http://stackoverflow.com/q/52395887
accepted answer: http://stackoverflow.com/a/54175392
has title: How to remove extra quotes in pymysql
tagged with: python
has comment: http://stackoverflow.com/comment/91737067
has comment: http://stackoverflow.com/comment/91737111
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/54175392
has comment: http://stackoverflow.com/comment/91737146
has body: This code uses pymysql, however when i try to insert the variable title into the sql query it comes out with 'title' for example when i set title to = test the database created is 'test' is there a way to create the table without the extra quotes import pymysql connection = pymysql.connect( host='localhost', user='root', password='', db='comments', ) c= connection.cursor() sql ='''CREATE TABLE IF NOT EXISTS `%s` ( `comment_id` int(11) NOT NULL, `parent_comment_id` int(11) NOT NULL, `comment` varchar(200) NOT NULL, `comment_sender_name` varchar(40) NOT NULL, `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ''' c.execute(sql, (title))
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91737055
has comment: http://stackoverflow.com/comment/91736854
tagged with: sql
answer count: 1
tagged with: pymysql
has comment: http://stackoverflow.com/comment/91736807
has comment: http://stackoverflow.com/comment/91737162

http://stackoverflow.com/q/52372214
has answer: http://stackoverflow.com/a/52372410
type: Question
tagged with: heroku
tagged with: heroku-cli
tagged with: twitter
tagged with: conda
upvote count: 2
has body: I created a twitter bot in python/jupyter notebook that I'm now trying to launch on Heroku. You can see it here: https://github.com/ivorygrant/TwitterAnalyzer Anyway, I'm having a really tough time trying to figure this out. I've tried following several pages but I'm just not getting it. When I try to push the app, I get an error saying Could not find a version that satisfies the requirement anaconda-client==1.6.14 According to PyPI the latest version according to pip is 1.2.2 but for some reason I have a higher version. One suggestion was to remove the version in the requirements.txt, that didn't work. I then changed it to 1.2.2 but no luck. From what I understand the error lies in the usage of conda vs pip? When I ran the freeze requirements, it automatically added anaconda-client. I even tried removing that requirement, but then I get another error that another distribution doesn't match, this time clyent. If someone can walk me through or point me in the right direction, the basic idea or steps I need to take and I will figure it out! I think the solution is "if no match, point to this source (conda) and check here" or get rid of conda but that might mess more things up? help!
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/20101834
score: 2
downvote count: 0
has title: Heroku Failed Push: Distribution version mismatch with Anaconda-Client

http://stackoverflow.com/comment/91663902
type: AnswerComment
has text: Why use `proc.stdout.read()` instead of `proc.communicate()[0]`?
comment on: http://stackoverflow.com/a/52355592
type: Comment
score: 1

http://stackoverflow.com/comment/91564430
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52308643
has text: You should have also gotten an error message.
score: 1

http://stackoverflow.com/q/52311029
has comment: http://stackoverflow.com/comment/91586972
has answer: http://stackoverflow.com/a/58571104
has comment: http://stackoverflow.com/comment/91571957
tagged with: google-cloud-sql
favorite count: 0
has comment: http://stackoverflow.com/comment/91576177
type: UnansweredQuestion
tagged with: google-app-engine
tagged with: python
has comment: http://stackoverflow.com/comment/91577176
has title: GCP at the standard environment: MySQL db connection refused
score: 3
has comment: http://stackoverflow.com/comment/91577971
downvote count: 0
has body: My goal is to take a working Python 2.7 project (MySQL + MS Word files) to work at GCP. I realize that I need App Engine - where the app will be running (scaling, etc). Cloud SQL working as MySQL db. For that I've followed that Cloud SQL for MySQL tut and Cloud SQL instance is created with root user. Both App Engine app and Cloud SQL instance are in the same project. Cloud Storage The SQL second generation instance is successfully created and a root user is set. How I run or deploy I use Cloud Shell to test the app - dev_appserver.py $PWD and deploy the app from Cloud Shell - gcloud app deploy. It works at appspot.com till I try to use MySQL connection in it. MySQL connection The MySQL connection code is taken from here: import MySQLdb import webapp2 CLOUDSQL_CONNECTION_NAME = os.environ.get('CLOUDSQL_CONNECTION_NAME') CLOUDSQL_USER = os.environ.get('CLOUDSQL_USER') CLOUDSQL_PASSWORD = os.environ.get('CLOUDSQL_PASSWORD') DB_NAME='test-db' def connect_to_cloudsql(): # When deployed to App Engine, the `SERVER_SOFTWARE` environment variable # will be set to 'Google App Engine/version'. if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'): # Connect using the unix socket located at # /cloudsql/cloudsql-connection-name. cloudsql_unix_socket = os.path.join( '/cloudsql', CLOUDSQL_CONNECTION_NAME) db = MySQLdb.connect( unix_socket=cloudsql_unix_socket, user=CLOUDSQL_USER, passwd=CLOUDSQL_PASSWORD) # If the unix socket is unavailable, then try to connect using TCP. This # will work if you're running a local MySQL server or using the Cloud SQL # proxy, for example: # # $ cloud_sql_proxy -instances=your-connection-name=tcp:3306 # else: db = MySQLdb.connect( host='127.0.0.1', user=CLOUDSQL_USER, passwd=CLOUDSQL_PASSWORD, db=DB_NAME) return db db = connect_to_cloudsql() Variables are set in app.yaml: runtime: python27 api_version: 1 threadsafe: true env_variables: CLOUDSQL_CONNECTION_NAME: coral-heuristic-215610:us-central1:db-basic-1 CLOUDSQL_USER: root CLOUDSQL…
has comment: http://stackoverflow.com/comment/91580293
tagged with: google-app-engine-python
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91572446
has comment: http://stackoverflow.com/comment/91579865
has answer: http://stackoverflow.com/a/53227918
has comment: http://stackoverflow.com/comment/91578665
upvote count: 3
tagged with: google-cloud-platform
has comment: http://stackoverflow.com/comment/91575596
has comment: http://stackoverflow.com/comment/91576133

http://stackoverflow.com/comment/91631398
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52342165
type: Comment
has text: how to fix that?

http://stackoverflow.com/a/52274483
score: 0
has body: The text you are referring to (You are authenticated as ...) can be found in this template: python3.6/site-packages/django/contrib/admin/templates/admin/login.html You can override this template to remove the messsage. For example, look into this question for how to override djangos default templates.
type: Answer
answers question: http://stackoverflow.com/q/52274257

http://stackoverflow.com/q/52339204
has comment: http://stackoverflow.com/comment/91626211
linked to: http://stackoverflow.com/q/2315520
type: Question
has comment: http://stackoverflow.com/comment/91626327
has comment: http://stackoverflow.com/comment/91626429
answer count: 2
has comment: http://stackoverflow.com/comment/91625746
has comment: http://stackoverflow.com/comment/91625856
score: 4
favorite count: 0
tagged with: language-lawyer
has title: Python modifying dict entries in-place during iteration
has answer: http://stackoverflow.com/a/52339430
has comment: http://stackoverflow.com/comment/91627066
upvote count: 4
has comment: http://stackoverflow.com/comment/91626590
tagged with: python-3.x
downvote count: 0
has comment: http://stackoverflow.com/comment/91626210
has answer: http://stackoverflow.com/a/78994241
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91625764
has comment: http://stackoverflow.com/comment/91626262
tagged with: python
tagged with: dictionary
has body: I know that in the general case, it’s unsafe to mutate a dict while iterating over it: d = {1: 2, 3: 4} for k in d.keys(): d[k + 1] = d[k] + 1 This yields a RuntimeError as expected. However, while reading the documentation for dict, I found the following (emphasis mine): Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries. So I tried the following code: d = {1: 2, 3: 4} for k in d.keys(): d[k] = d[k] + 1 Note: I did not add or remove any entries during the iteration; I only updated existing entries. I've tried it with a few examples and so far have not received a RuntimeError, and the loop works as expected. Is this guaranteed to work by the language? Or have I just been lucky so far? Note: I am using Python 3, so d.keys() returns a dynamic view rather than a list).

http://stackoverflow.com/comment/91864645
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52460744
has text: [No, it's not.](https://bottlepy.org/docs/dev/api.html#bottle.BaseRequest.url) `url` is an attribute (not method) of the `Request` (not `Bottle`) class. I suggest that you read point #2 in my answer (XY problem). If you tell us what you're trying to do (in a new question would be best), we can help you with /that/ (instead of with specifically getting `get_url` to work - which apparently has not solved your problem (XY))

http://stackoverflow.com/q/52366421
accepted answer: http://stackoverflow.com/a/52366706
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91677495
downvote count: 1
tagged with: scipy
upvote count: 16
type: Question
score: 15
has comment: http://stackoverflow.com/comment/91677371
tagged with: numpy
has answer: http://stackoverflow.com/a/52366706
answer count: 1
tagged with: arrays
tagged with: scikit-learn
favorite count: 0
linked to: http://stackoverflow.com/q/41102645
linked to: http://stackoverflow.com/q/5751114
has body: This question is intended to be a canonical duplicate target Given two arrays X and Y of shapes (i, n) and (j, n), representing lists of n-dimensional coordinates, def test_data(n, i, j, r = 100): X = np.random.rand(i, n) * r - r / 2 Y = np.random.rand(j, n) * r - r / 2 return X, Y X, Y = test_data(3, 1000, 1000) what are the fastest ways to find: The distance D with shape (i,j) between every point in X and every point in Y The indices k_i and distance k_d of the k nearest neighbors against all points in X for every point in Y The indices r_i, r_j and distance r_d of every point in X within distance r of every point j in Y Given the following sets of restrictions: Only using numpy Using any python package Including the special case: Y is X In all cases distance primarily means Euclidean distance, but feel free to highlight methods that allow other distance calculations.
tagged with: python
has title: How to do n-D distance and nearest neighbor calculations on numpy arrays

http://stackoverflow.com/q/52346114
has title: How to check which timezone the app will run in azure
tagged with: python
type: AnsweredQuestion
has body: I have a python web app which extracts few files from the webserver. Files are named as per date, so it looks like transData2018/09/13.csv These files are uploaded by someone whose timezone is GMT-4. My timezone is GMT+8. As of now, I am running the python app locally so the app is ahead. Now because it is ahead of date time, the code has to look for the files of previous day. So considering if today's date is 15-Sept, code has to look for files with date 14-Sept. This all setup works fine locally. Now my plan is to deploy this python app on azure web app platform. Once deployed, I do not know which timezone it will work in and what time it will pick. Based on that, should the code look for the previous date in the files or just the todays date. In the code I am doing: previous_date = str(datetime.now().date() - timedelta(days=1)) to get the previous date value but this will probably fail in scenario: If they uploaded the file on 15th-Sept so the files will have name transData2018/09/15.csv, but the code will look for the file transData2018/09/14.csv which is not correct. How should I deal with this situation? Thanks
tagged with: timezone
upvote count: 3
has comment: http://stackoverflow.com/comment/91658837
type: Question
score: 3
tagged with: azure-web-app-service
accepted answer: http://stackoverflow.com/a/52346195
downvote count: 0
answer count: 1
favorite count: 0
tagged with: azure
has answer: http://stackoverflow.com/a/52346195

http://stackoverflow.com/q/52429174
downvote count: 1
type: Question
upvote count: 0
score: -1
has answer: http://stackoverflow.com/a/52429428
linked to: http://stackoverflow.com/q/100003
answer count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91801959
tagged with: python
has comment: http://stackoverflow.com/comment/91802047
has comment: http://stackoverflow.com/comment/91848844
tagged with: metaclass
has title: Python 3 type is both an object and class?
has body: I am reading Learning python. Regarding metaclass, the book said type is an object and also is itself class. I am trying to search python doc online but don't see any similar description. Can someone point me any official doc? Thinking a bit more on this statement that type is both object and class, I think it makes sense. The reasons are as following. type is callable, seeing type(). Then it should be either a function or object which has implemented call any object is instanced from a class. Given it's in the top hierarchy, it makes sense that its class is itself. My second question is that metaclass is subclass of type class? Is it still true that metaclass is also an instance of type object/class? Because when Metaclass(...) is invoked, type.call is invoked then Metaclass must be instance of type
has comment: http://stackoverflow.com/comment/91802056
has comment: http://stackoverflow.com/comment/91802121

http://stackoverflow.com/comment/91541887
type: Comment
score: 1
has text: @user2357112 thanks for pointing out. A regex based solution would need to run in a loop until no change is done. That is not guaranteed to be linear, so I switched to a stack based solution.
type: AnswerComment
comment on: http://stackoverflow.com/a/52282003

http://stackoverflow.com/q/52332877
has title: svg tag scraping from funnels
has body: I am trying to scrape data from here but getting error. I have taken code from here Scraping using Selenium and python This code was working perfectly fine but now I am getting error wait.until(EC.visibility_of_element_located((By.LINK_TEXT, "All Boards"))) raise TimeoutException(message, screen, stacktrace)
has comment: http://stackoverflow.com/comment/91636722
type: AnsweredQuestion
favorite count: 0
tagged with: http://stackoverflow.com/tag/svg
type: Question
has answer: http://stackoverflow.com/a/52345876
has comment: http://stackoverflow.com/comment/91636625
tagged with: python
linked to: http://stackoverflow.com/q/51611963
answer count: 1
score: -1
accepted answer: http://stackoverflow.com/a/52345876
downvote count: 2
tagged with: selenium
tagged with: web-scraping
upvote count: 1

http://stackoverflow.com/comment/91750051
has text: It's not needed. I've updated my answer with better explanations.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52403161
type: AnswerComment

http://stackoverflow.com/a/52314630
score: 3
has body: Just use np.where() a = np.array(a) b = np.array(b) a = np.where(b == 0, a, b) If you want to get fancy and save memory, use np.place() np.place(a, b != 0, b[b != 0]) EDIT: Since 0 == -0 evaluates True, you don't need any other checks
accepted answer of: http://stackoverflow.com/q/52314573
answers question: http://stackoverflow.com/q/52314573
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3

http://stackoverflow.com/comment/94176683
has text: No. pdfkit has system dependencies.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52325580
type: AnswerComment

http://stackoverflow.com/a/52386606
answers question: http://stackoverflow.com/q/52386447
downvote count: 0
has comment: http://stackoverflow.com/comment/91717968
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52386447
type: Answer
has comment: http://stackoverflow.com/comment/91717688
score: 2
has body: This should help. import pprint d = {'query': {'bool': {'minimum_should_match': 2, 'should': [{'match': {'Name': {'query': 'Nametest', 'boost': 5, 'fuzziness': 3}}}, {'match': {'Address': {'query': 'NONE', 'boost': 4, 'fuzziness': 3}}}, {'match': {'Site': {'query': 'Adeswfvfv', 'boost': 4, 'fuzziness': 3}}}, {'match': {'Phone': {'query': '5680728.00', 'boost': 4, 'fuzziness': 2}}}], 'must': []}}} d["query"]['bool']['should'] = [i for i in d["query"]['bool']['should'] if list(i['match'].items())[0][1]["query"] != 'NONE'] pprint.pprint(d) Output: {'query': {'bool': {'minimum_should_match': 2, 'must': [], 'should': [{'match': {'Name': {'boost': 5, 'fuzziness': 3, 'query': 'Nametest'}}}, {'match': {'Site': {'boost': 4, 'fuzziness': 3, 'query': 'Adeswfvfv'}}}, {'match': {'Phone': {'boost': 4, 'fuzziness': 2, 'query': '5680728.00'}}}]}}}
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91717908

http://stackoverflow.com/q/52372698
tagged with: python
tagged with: scrapy
type: Question
has answer: http://stackoverflow.com/a/52372872
score: 0
has title: problems inserting other characters postgres database through scrapy
has comment: http://stackoverflow.com/comment/91690737
has body: Hello everyone I'm starting with scrapy and I'm doing scrapy to a supermarket but the urls and product names have characters like "ñ" so when I'm scraping it it stop saving me those information in my database and it just save the info until before it bumps into the url or name with that character "ñ" specifically I've read a lot about encode and decode functions and I've tried many solutions people posted here but it doesn't work. SCRAPY CODE # -*- coding: utf-8 -*- import scrapy import psycopg2 #Para establecer conexion con la base de datos. from scrapy.spiders import CrawlSpider, Rule #Para la creacion del bot y sus reglas de busqueda from scrapy.linkextractors import LinkExtractor #Para extraer link de las paginas visitadas import time #--------------------------------------------------------------------------------------------------------------------------------- # #Creando la conexion. conn = psycopg2.connect(database="namedb", user="postgres", password="root", host="127.0.0.1", port="5432") # #Creando cursor. cur = conn.cursor() #--------------------------------------------------------------------------------------------------------------------------------- #Funciones def leer_datos(nombre_archivo): """Lee un archivo txt y devuelve un array donde cada posicion es una fila del archivo. Argumentos: nombre_archivo: String. No debe tener la extension. """ array = [] archivo = open(nombre_archivo + '.txt','r') linea = archivo.readline() while linea != '': # Lee el archivo por lineas y las agrega al array. cadena = linea.strip('\n') #Saca el valor '\n' de la linea array.append(cadena) #Agrega la linea al array linea = archivo.readline() archivo.close() # Cierra archivo return array def insertar_datos(nombre_archivo,cadena): """Inserta un string en una fila de un archivo txt. Argumentos: nombre_archivo: String. No debe tener la extension. cadena: String a escribir en el archivo. """ archivo = open(nombre_archivo + '.txt', "r+") contenido = archivo.read() #Lee todo el…
answer count: 1
tagged with: postgresql
has comment: http://stackoverflow.com/comment/91690048
type: UnansweredQuestion

http://stackoverflow.com/comment/91741293
has text: You could use multi-processing to split the workload into smaller portions of the pixel grid. That way if it is required to loop through the pixels like you do it can make that complete a lot faster.
type: Comment
comment on: http://stackoverflow.com/q/52398598
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91492997
score: 0
comment on: http://stackoverflow.com/q/52272903
type: QuestionComment
type: Comment
has text: How do expect us to answer this?

http://stackoverflow.com/q/52374477
score: 1
type: Question
has answer: http://stackoverflow.com/a/52375999
accepted answer: http://stackoverflow.com/a/52375999
has comment: http://stackoverflow.com/comment/91693882
upvote count: 1
answer count: 1
favorite count: 0
has body: I have the following signal for creating a profile when a new user registers and then sends an email to the admin informing them of the new user @receiver(post_save, sender=User) def create_user_profile(sender, **kwargs): '''Create a profile for a new user''' if kwargs['created']: Profile.objects.create(user=kwargs['instance']) @receiver(post_save, sender=User) def notify_admin(sender, instance, created, **kwargs): '''Notify the administrator that a new user has been added.''' if created: subject = 'New Registration created' message = 'A new candidate %s has registered with the site' % instance.email from_addr = 'no-reply@example.com' recipient_list = ('admin@example.com', ) send_mail(subject, message, from_addr, recipient_list) I am looking to also notify the admin when a profile is updated but am struggling to come up with a solution. Any ideas?
has title: Django Profile Update on existing profile
tagged with: django
tagged with: python
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/91593519
score: 1
type: Comment
type: QuestionComment
has text: Removing the axis worked perfectly, thank you!
comment on: http://stackoverflow.com/q/52305912

http://stackoverflow.com/comment/91560287
score: 0
type: QuestionComment
type: Comment
has text: You can just write a function that takes a `request` object and return something roughly like `{dateobjectnow'': datetime.datatime.now()}` and put it inside the context processors in `projects.settings.TEMPLATES['OPTIONS']['context_processors']`, now every view you have has this template variable.
comment on: http://stackoverflow.com/q/52296306

http://stackoverflow.com/a/52404250
upvote count: 1
answers question: http://stackoverflow.com/q/52403943
has body: Your primary key is probably an integer, but in the main code (not the snippet) you're passing it a string with parentheses as part of the string. So in the main code the query will contain WHERE id_column='(566)' and simply won't match any records. Try: while not pk: pk = input() primary_key = int(pk) and see if that works any better. The ? placeholder in the SQL query will automatically put quotes round strings but not around numbers so you need to be sure the parameters you pass have the correct type.
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/a/52346227
type: Answer
has body: link = games[0].find("td",{"class":"right gamelink"}).find('a') print(link['href'])
score: 1
accepted answer of: http://stackoverflow.com/q/52346159
upvote count: 1
answers question: http://stackoverflow.com/q/52346159
has comment: http://stackoverflow.com/comment/91638503
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52318675
has body: I am writing a Python script which reads data from multiple JSON files and writes it into a single output CSV file. I've written some code but it is not correct. I've formatted JSON for simplicity here otherwise it's on a single line. Each "requestId" contains multiple "id" values. My current code is able to read only one "id" and repeats it 200 times. Not sure why this is happening. JSON File { "success":true, "errors":[ ], "requestId":"3561c", "result":[ { "id":257268, "name":"02 ", "description":"", "createdAt":"2017-10-06T11:29:40Z+0000", "updatedAt":"2017-11-07T13:38:11Z+0000", "url":"https", "subject":{ "type":"Text", "value":"Are you ready" }, "fromName":{ "type":"Text", "value":"Centre" }, "fromEmail":{ "type":"Text", "value":"abc@xyz.com" }, "replyEmail":{ "type":"Text", "value":"noreply@xwz.com" }, "folder":{ "type":"Folder", "value":8041, "folderName":"A" }, "operational":false, "textOnly":false, "publishToMSI":false, "webView":false, "status":"approved", "template":681, "workspace":"R", "version":1, "autoCopyToText":false }, { "id":257273, "name":"02a", "description":"", "createdAt":"2017-10-06T11:29:46Z+0000", "updatedAt":"2017-11-07T13:38:19Z+0000", "url":"https:", "subject":{ "type":"Text", "value":"Still have questions?" }, "fromName":{ "type":"Text", "value":"Centre" }, "fromEmail":{ "type":"Text", "value":"abc@xyz.com" }, "replyEmail":{ "type":"Text", "value":"noreply@xwz.com" }, "folder":{ "type":"Folder", "value":8041, "folderName":"A" }, "operational":false, "textOnly":false, "publishToMSI":false, "webView":false, "status":"approved", "template":681, "workspace":"R", "version":1, "autoCopyToText":false }, Python Code import json import csv import os import codecs import sys reload(sys) sys.setdefaultencoding('utf8') file_dir = os.path.normpath('/home/pp/jobs/staging/') exp_dir = os.path.normpath('/home/pp/jobs/CSV/') exp_file_name = 'emails.csv' exp_path = os.path.join(exp_dir, exp_file_name) my_dict_list =[] try: for f in os.listdir(file_dir): …
has answer: http://stackoverflow.com/a/52318813
upvote count: 1
type: Question
has title: Python - Script reads one value from JSON and writes it 200 times in CSV
tagged with: http://stackoverflow.com/tag/json
answer count: 3
accepted answer: http://stackoverflow.com/a/52318813
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/52318898
has answer: http://stackoverflow.com/a/52318898
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52318909
score: 1

http://stackoverflow.com/comment/91712891
has text: Any particular reason why you need it in that format?
comment on: http://stackoverflow.com/q/52384451
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52427702
tagged with: attributeerror
has answer: http://stackoverflow.com/a/52427760
accepted answer: http://stackoverflow.com/a/52427760
has title: python:AttributeError: 'GameStats' object has no attribute 'click_first'
score: 0
answer count: 1
has body: I'm new on python and sorry class GameStats(): def __init__(self,ai_setting): self.ai_setting = ai_setting self.game_active = False self.reset_stats() self.click_first = True def reset_stats(self): if self.click_first: self.cobweb_left = self.ai_setting.web_limit self.click_first = False else: self.cobweb_left = self.ai_setting.web_limit+1 An error:AttributeError: 'GameStats' object has no attribute 'click_first' I don't know why we can't use the value of self.click_first to test? And I try to set a new variable just like this : click = self.click_first if click: but it is wrong. Many thanks!!!
tagged with: python
type: AnsweredQuestion
type: Question

http://stackoverflow.com/q/52292541
accepted answer: http://stackoverflow.com/a/52488993
has comment: http://stackoverflow.com/comment/91557658
tagged with: tensorflow
type: Question
has body: I do know that I can separate my data by their label before I load them into my network. Let's say there are 3 classes, with labels 0,1,2. I can do it by: dataset1 = tf.data.TextLineDataset(train_csv_file1).map(_parse_csv_train) dataset2 = tf.data.TextLineDataset(train_csv_file2).map(_parse_csv_train) dataset3 = tf.data.TextLineDataset(train_csv_file3).map(_parse_csv_train) I am just curious about the following: Suppose we have the dataset: dataset = tf.data.TextLineDataset(train_csv_file).map(_parse_csv_train) which contains all the data from the 3 classes, is there a way to call some function like dataset.selectDataByLabel(label=="2") [this is a made-up function] so that I can divide the dataset into 3 parts according to their labels?
answer count: 1
downvote count: 0
tagged with: tensorflow-datasets
favorite count: 0
has answer: http://stackoverflow.com/a/52488993
score: 2
has comment: http://stackoverflow.com/comment/91533994
upvote count: 2
tagged with: python
type: AnsweredQuestion
has title: Tensorflow - Is there a way to separate tf.data.Dataset by label?

http://stackoverflow.com/comment/101536456
comment on: http://stackoverflow.com/q/52350165
type: QuestionComment
has text: For Python 3.7.0 you need to use pywin32 224 (or later). Thanks to Mark Hammond who generated this new version of pywin32 that solves the issue.
score: 0
type: Comment

http://stackoverflow.com/q/52381909
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91713150
favorite count: 0
has comment: http://stackoverflow.com/comment/91713371
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91713121
has body: I've integrated Jinja2 in TurboGears 2.3.12 and in my template file, I have used the following code &lt;input type='text' value='{{ obj.attr }}' /&gt; I got None in the textbox as the object was new. I want to remove the None to an empty string. Found the following solutions 1. &lt;input type='text' value='{{ obj.attr or '' }}' /&gt; and 2. https://stackoverflow.com/a/17661969/2102143 I want to integrate the 2nd solution in TurboGears as it will be available to the entire app and also can avoid the or ''
tagged with: jinja2
has comment: http://stackoverflow.com/comment/91712911
has comment: http://stackoverflow.com/comment/91713650
linked to: http://stackoverflow.com/q/11146619
tagged with: turbogears2
downvote count: 0
score: 1
type: Question
has title: Suppress 'None' in Jinja2 in TurboGears using Environment.finalize
has answer: http://stackoverflow.com/a/52386118
tagged with: python-2.7
upvote count: 1
has comment: http://stackoverflow.com/comment/91716429

http://stackoverflow.com/q/52403860
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91751773
type: Question
has title: Array Issue in guizero
score: 0
has comment: http://stackoverflow.com/comment/91751493
has comment: http://stackoverflow.com/comment/91751807
tagged with: python
has body: I am writing a simple sort program in python and encounter this error. I want to add values to the array (Inside GUI ). RL[0]=Text(app,size=10,font="Times New Roman",color="black",grid=[0,14]) TypeError: 'tuple' object does not support item assignment Code: from guizero import App from guizero import App,Text from guizero import App,TextBox from guizero import App,PushButton from guizero import Slider from guizero import Picture,Window app=App(title="Sample", height=480, width=800, layout='grid') #Update multi ,single,Initial app.bg = "white" RL=("A","B","C","D","E","F") RL[0]=Text(app,"",size=10,font="Times New Roman",color="black",grid=[0,14]) RL[1]=Text(app,"",size=10,font="Times New Roman",color="black",grid=[1,14]) RL[2]=Text(app,"",size=10,font="Times New Roman",color="black",grid=[2,14]) RL[3]=Text(app,"",size=10,font="Times New Roman",color="black",grid=[3,14]) RL[4]=Text(app,"",size=10,font="Times New Roman",color="black",grid=[4,14]) app.display()
answer count: 0

http://stackoverflow.com/q/52419417
favorite count: 0
has answer: http://stackoverflow.com/a/52419497
accepted answer: http://stackoverflow.com/a/52419497
possible better answer: http://stackoverflow.com/a/52419628
tagged with: python
has comment: http://stackoverflow.com/comment/91781961
tagged with: dictionary
type: AnsweredQuestion
tagged with: list
score: 1
has body: I have a dictionary called dict which looks like this: {1: [0, 1], 2: [2, 3], 3: [4], 4: [5, 6, 7, 8], 5: [9, 10], 7: [11, 12], 8: [13, 14, 15], 9: [16], 10: [17], 11: [18], 13: [19], 14: [20], 15: [21], 17: [22], 18: [23, 24], 19: [25], 21: [26, 27, 28], 22: [29], 24: [30, 31, 32], 25: [33, 34], 27: [35], 28: [36], 31: [37, 38, 39, 40, 41, 42], 32: [43, 44, 45, 46, 47], 34: [48, 49, 50, 51, 52], 35: [53, 54, 55, 56], 36: [57, 58, 59], 37: [60], 40: [61, 62], 41: [63, 64, 65, 66], 43: [67], 44: [68, 69], 45: [70, 71], 48: [72, 73, 74], 49: [75, 76], 51: [77], 52: [78, 79], 53: [80, 81], 54: [82], 55: [83], 58: [84, 85, 86], 59: [87], 61: [88, 89], 62: [90], 63: [91], 64: [92, 93], 65: [94], 68: [95], 69: [96], 71: [97], 73: [98, 99], 74: [100], 76: [101], 77: [102]} I have a list called remainID which looks like this: [[13, 24, 62, 69, 34, 31], [44, 11, 2, 55, 22, 53], [59, 40, 3, 54, 32, 71], [15, 64, 73, 5, 10], [68, 61, 9, 18, 48], [41, 58, 65, 1, 27], [37, 7, 51, 35, 25], [17, 74, 63, 8, 36]] remainID contains a list of lists which are all the values of the keys in the dictionary. I would like to change all the keys values in remainID to the dictionary value pair of the key. This would mean that instead of having a list that has multiple lists of the keys in dict, I would like a list that has multiple lists of the values in the dict. However, the number of lists in remainID cannot change but the length of each list might be different. How do I do this? For example, consider the first list in remainID: [13, 24, 62, 69, 34, 31] This list should become: [19, 30, 31, 32, 90, 48, 49, 50, 51, 52, 37, 38, 39, 40, 41, 42]
has title: Accessing values from a dictionary using a list of lists and returning a list of lists
type: Question
has answer: http://stackoverflow.com/a/52419628
tagged with: python-2.7
answer count: 2
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91781992

http://stackoverflow.com/q/52342662
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52343171
has body: The aim is to print a pattern half triangle depending upon the user input for example if the user input is 3 the pattern would be 1 1 2 1 2 3 but upon executing there is a space after the each element of the last column and a new line (\n) after the last row. i would like to remove that please help. 1 \n 1 2 \n 1 2 3 \n likewise whereas the expected output is 1\n 1 2\n 1 2 3 here is the code i wrote rows = int(input()) num = 1 for i in range (0, rows): num = 1 for j in range(0, i + 1): print(num,end=" ") num = num + 1 print("")
has answer: http://stackoverflow.com/a/52343461
has answer: http://stackoverflow.com/a/52343029
accepted answer: http://stackoverflow.com/a/52343461
has answer: http://stackoverflow.com/a/52342690
tagged with: python
has title: printing a number pattern in python without white space and new line at the end
possible better answer: http://stackoverflow.com/a/52342690
favorite count: 0
score: -1
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52342890
answer count: 5
downvote count: 2
upvote count: 1
type: Question

http://stackoverflow.com/comment/91797627
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52415457
has text: Thanks! When I apply model_performance on test data set, from the output I do see the threshold. Is there a way to find the threshold using the test data set?

http://stackoverflow.com/comment/91585250
score: 1
has text: Thanks for your effort, but this is not going to work at all. The line `kwargs['default'] = 'DEFAULT'` cannot be in the `__init__` function it assumes you can up-front get all the values. I cannot afford to have a copy of the "other" keys in this dict, there can be thousands, this has to be done *on the fly*. The keys that have to be put in *on the fly* are not fixed, they get determined when the instance items get iterated over. And of course the values for those keys are not guaranteed to be available before the start of the iteration either (otherwise it would not be *on-the-fly*).
type: AnswerComment
comment on: http://stackoverflow.com/a/52314764
type: Comment

http://stackoverflow.com/comment/91526852
score: 1
comment on: http://stackoverflow.com/q/52289379
type: Comment
type: QuestionComment
has text: @ReblochonMasque Yes it is. There is something called Psuedo Inverse for such matrices. I think he is referring to that

http://stackoverflow.com/comment/91760395
has text: Not very general, but I think this works for your situation: `{k: dict2[k[:3]+")"] for k, v in dict1.items()}`
score: 0
comment on: http://stackoverflow.com/q/52408268
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91743364
has text: You can get name like this: `n = tf.constant(2).name`
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52399505

http://stackoverflow.com/comment/91974109
score: 0
type: AnswerComment
type: Comment
has text: Thanks Gang for quick reply. Yes. script name is server.py and it has import logging I tried with above suggestion but I got below error. AttributeError: <function getLogger at 0x7f4689667510> does not have the attribute 'info' so I added "getLogger.level.." and tried with with patch('scripts.server.logging.getLogger.level.info') as mock_info: self.server_obj.logger.info.assert_called_with('Started Redis instance') but getting ModuleNotFoundError: No module named 'scripts.server.logging'; 'scripts.server' is not a package Am I missing something?
comment on: http://stackoverflow.com/a/52458365

http://stackoverflow.com/comment/91670401
has text: Where does this go in my code? Sorry I am very new to Python and MongoDb
comment on: http://stackoverflow.com/a/52363018
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/52319559
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/52319779
has body: PROBLEM SOLVED. the issue was with jaraco module, that i used for clipboard manipulation, i used pyperclip instead. I made a python app with tkinter that works fine, but I wanted to make an exe from it so it's user friendly in windows. I used cx_Freeze library for that, that works fine too, but not always. When creating the exe using cx_Freeze you can specify base parameter, if you give none that will open 2 windows, cmd window and a GUI window for your app. To get rid of the cmd window you can specify "Win32GUI" as base parameter for cx_Freeze. This ignores the cmd window and just opens the GUI, it seems to be working, but not always. Sometimes opening the exe file will start the proccess but no GUI will show. Opening cmd and going to the directory of your exe and starting it from there will actually show the GUI and fix the problem untill you restart your pc (you can open the app without cmd with everything working untill restart) It seems that as long as cmd window is in your ram, the GUI will show, otherwise it "doesn't know" and fails to show GUI. The code can be found here: https://github.com/GrishaDev/ClipMagic clip.py is the entire app setup.py is the file used with cx_Freeze to get exe of the app, that's where you specify base parameter and such. the piece of code where the problem most likely is (setup.py): import sys from cx_Freeze import setup, Executable # import os # os.environ['TCL_LIBRARY'] = "C:\\Users\\Grisha\\AppData\\Local\\Programs\\Python\\Python35\\tcl\\tcl8.6" # os.environ['TK_LIBRARY'] = "C:\\Users\\Grisha\\AppData\\Local\\Programs\\Python\\Python35\\tcl\\tk8.6" import os.path PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__)) os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6') os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6') base = None if sys.platform == "win32": base = "Win32GUI" setup(name="clipmagic", version="1", description="Extended clipboard", options={'build_exe':…
has comment: http://stackoverflow.com/comment/91587155
linked to: http://stackoverflow.com/q/52246748
type: Question
has answer: http://stackoverflow.com/a/52319779
score: -1
has comment: http://stackoverflow.com/comment/91586797
has comment: http://stackoverflow.com/comment/91587182
tagged with: windows
answer count: 1
downvote count: 1
tagged with: cmd
has title: python tkinter exe built with cx_Freeze for windows won't show GUI
favorite count: 0
tagged with: cx-freeze
tagged with: tkinter
tagged with: python

http://stackoverflow.com/comment/91785944
score: 0
has text: skip if the entire row is an exact match, else append to existing table.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52421332

http://stackoverflow.com/comment/91658273
has text: this gives me a single column with the string of word and frequency in the same cell. if possible, can we get a single column for word and another column for frequency?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52337825
type: AnswerComment

http://stackoverflow.com/q/52334538
has answer: http://stackoverflow.com/a/52334748
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/54954401
tagged with: python-turtle
tagged with: python
tagged with: turtle-graphics
has body: I'm trying to write turtle code with turtle shape and a color and drawing T letter. The following is my code: It gives me run time Error with shape! Please help me to correct it! Thanks import turtle # Import the required library ft = turtle.Turtle ft.shape("turtle") ft.color(255) ft.forward(100) ft.backward(50) ft.left(90) ft.forward(200)
upvote count: 2
has comment: http://stackoverflow.com/comment/91616310
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/52335668
type: Question
has title: 'str' object has no attribute 'turtle' in Python turtle
score: 0

http://stackoverflow.com/comment/91640913
type: QuestionComment
comment on: http://stackoverflow.com/q/52303723
has text: Yes. Do you know what could cause the result to be 0?
score: 0
type: Comment

http://stackoverflow.com/comment/91683198
type: Comment
comment on: http://stackoverflow.com/a/52362410
has text: I knew `seaborn` was nice for plotting the regression + the confidence interval, but is there anyway to have it actually return the fit that way you can predict without reading it off of the graph?
type: AnswerComment
score: 0

http://stackoverflow.com/q/52291284
has answer: http://stackoverflow.com/a/52298326
type: Question
tagged with: numpy
has title: Find maxima of segmented regions
downvote count: 0
has comment: http://stackoverflow.com/comment/91540820
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 3
upvote count: 3
has body: I have 2 3D grayscale images of equal dimensions. The first image (img) is the raw data of a 3D volume (obtained using a microscope) and contains various cells. Example slice of raw 3d image The second image (imglab) is a masked version of the raw image where each identified cell is filled with a single, unique value (i.e. cell 1 = all 1s, cell 2 = all 2s). All non cell regions are zeros. Example slice of masked 3d image I am now trying to find the coordinates of the maximum value of each cell from the raw data that corresponds to the labeled mask array. Currently, I have a loop which is extremely inefficient. I suspect there is a way to setup multiple conditions using a single np.where call, but I can't figure out how to do this. The current for loop method is below: coordinates = [] for i in range(1, int(imglab.max())): # Number of cells = max value of label image max_val = np.max(img[imglab == i]) max_coord = np.where((img == max_val) &amp; (imglab == i)) coordinates.append(max_coord)
tagged with: image-processing

http://stackoverflow.com/comment/91640556
has text: Yes I think the best thing is to not call super at all, but recreate the relevant parts in your own `__init__`.
score: 2
comment on: http://stackoverflow.com/q/52347470
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91801637
comment on: http://stackoverflow.com/q/52428989
has text: There is no way that `device['cad_id']` doesn't work while `device['id']` works when both of the keys actually present in the dictionary. The problem is somewhere else.
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52365561
tagged with: python
has comment: http://stackoverflow.com/comment/91675786
answer count: 2
upvote count: 1
tagged with: topic-modeling
accepted answer: http://stackoverflow.com/a/52366062
tagged with: nonetype
has answer: http://stackoverflow.com/a/52365919
has body: I'm sorry, but I still can not solve this None problem. I am using an NMF algorithm to have the themes of a corpus and then I try to retrieve the documents attached to each topic. But None prevents me! When I try to retrieve the documents, I have an error Script: import pandas import numpy as np import pandas as pd from sklearn.decomposition import NMF from sklearn.feature_extraction.text import TfidfVectorizer def display_topics(model, feature_names, n_top_words): for topic_idx, topic in enumerate(model.components_): print "Topic %d:" % (topic_idx) print " ".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]]) text = pandas.read_csv('pretraitement_virgile.csv', encoding = 'utf-8') good_text = text['phrase'] bad_text = text['raw_phrase'] bad_text_list = bad_text.values.tolist() good_text_list = good_text.values.tolist() tfidf_vectorizer = TfidfVectorizer() tfidf = tfidf_vectorizer.fit_transform(good_text_list) tfidf_feature_names = tfidf_vectorizer.get_feature_names() topics_number = 3 # Run NMF nmf = NMF(n_components=topics_number, random_state=1, alpha=.1, l1_ratio=.5, init='nndsvd').fit(tfidf) document_topics = nmf.fit_transform(tfidf) n_top_words = 10 print 'NMF topics' topics = display_topics(nmf, tfidf_feature_names, n_top_words) print topics print print 'Documents per topic' for topic in range(len(topics)): if topic == None: pass else: print("Topic {}:".format(topic)) docs = np.argsort(document_topics[:, topic])[::-1] for mail in docs[:3]: bad_text_list_n = " ".join(bad_text_list[mail].split(",")[:2]) print (" ".join(good_text_list[mail].split(",")[:2]) + ',' + bad_text_list_n) I tried to put a condition to ignore the Name, but it does not work.I still have the same error. Topic 0: order cancel delivery date not want store always well ahead Topic 1: product not broken only package arrived received color color delivered Topic 2: product not return site store receipt order available in advance None Documents par topic Traceback (most recent c…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91675562
downvote count: 0
possible better answer: http://stackoverflow.com/a/52365919
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/91675516
tagged with: nmf
has answer: http://stackoverflow.com/a/52366062
has title: How to remove None from the result of a function?

http://stackoverflow.com/comment/91650991
score: 2
type: Comment
has text: your indentation is broken, please fix your code and edit it so it is clear what belongs where. suggested indentation-depth is 4 spaces per level (https://www.python.org/dev/peps/pep-0008/#indentation)
type: QuestionComment
comment on: http://stackoverflow.com/q/52353021

http://stackoverflow.com/comment/91687449
type: QuestionComment
comment on: http://stackoverflow.com/q/52371412
has text: what should be the expected output?
score: 0
type: Comment

http://stackoverflow.com/comment/91490810
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52271543
has text: @andreahmed Edited mine
score: 0

http://stackoverflow.com/q/52352524
type: UnansweredQuestion
tagged with: python
has title: Print numpy array
has comment: http://stackoverflow.com/comment/91650148
answer count: 0
has body: I have a random numpy array that i want to print out beside the player name. Right now it prints out the entire array beside a single player where I want to print all elements from index 0 with player 0, then increment the player and print out the second row of elements etc. import numpy as np import random startPosition = [] for i in range (5): r = random.randint(1,5) if r not in startPosition: startPosition.append(r) stats = np.random.randint(10,20,(5, 3)) d = {}; x = 5 while x &gt; len(d): name = raw_input('Enter player name') d[name] = ""; names = d.keys() from numpy import array arr = array(d) for x in names: print "Player:", x,",Scores:", ('\n'.join([''.join(['{:4}'.format(item) for item in row]) for row in stats]))
downvote count: 1
type: Question
tagged with: numpy
tagged with: arrays
has comment: http://stackoverflow.com/comment/91650196
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/91650012
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91650329

http://stackoverflow.com/comment/132656500
type: QuestionComment
comment on: http://stackoverflow.com/q/52423507
has text: use this link `https://stackoverflow.com/a/75175057/12780274` is very simple
score: 0
type: Comment

http://stackoverflow.com/q/52429033
tagged with: flask
favorite count: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: I have a Flask template that displays a page with a dropdown list of owners, a table with the owner's win-loss record, and a radio to toggle between regular season record and playoff record. The desired workflow is: If navigated to the page through the navigation bar, it should default to /matchup-history/regular. (this works) Else it should route accordingly whenever the radio is toggled. (this doesn't work) matchup-history.html {%- extends "base.html" -%} {% block nav_matchups %}active{% endblock %} {%- block content -%} {%- for o in owners %} {%- if request.form['owner_id'] == o['owner_id']|string() %} {{o['first_name'] + " " + o['last_name'] }} {%- else %} {{o['first_name'] + " " + o['last_name'] }} {%- endif %} {%- endfor %} {% block matchup_type_radio %}{% endblock %} {%- if records|length > 0 %} {%- for th in table_headers %} {{ th }} {%- endfor %} {%- for r in records %} {%- for cn in column_names %} {{ r[cn] }} {%- endfor %} {%- endfor %} {%- endif %} {% endblock -%} matchup-history/regular.html {%- extends "matchup-history.html" -%} {% block matchup_type_radio %} Regular Season Playoffs {% endblock %} matchup-history/playoffs.html {%- extends "matchup-history.html" -%} {% block matchup_type_radio %} Regular Season Playoffs {% endblock %} app.py @app.route('/matchup-history/<string:matchup_type>', methods=['GET', 'POST']) def show_matchup_history(matchup_type): table_headers = ["Opponent", "Wins", "Losses"] column_names = ["opponent_owner_name", "wins", "losses"] owners = queries.get_owners() if request.method == 'POST': owner_id = request.form['owner_id'] else: owner_id = owners[0]['owner_id'] if matchup_type == REGULAR_SEASON: records = queries.get_matchup_history_regular(owner_id) else: records = queries.get_matchup_history_playoffs(owner_id) return render_template("matchup-history/{matchup_type}.html".format(matchup_type=matchup_type), title='Matchup History', table_headers=table_headers, column_names=column_names, owners=owners, records=records) The pa…
upvote count: 2
has answer: http://stackoverflow.com/a/52431849
accepted answer: http://stackoverflow.com/a/52431849
has title: Flask passing request.form value to url_for
type: Question
score: 2
type: AnsweredQuestion
tagged with: forms
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/91786788
score: 0
has text: your when should look like: `f.when(array_contains(df_categories.parents, "0"), SOME_VALUE).otherwise(..)` and replace SOME_VALUE with the value you want to have if the comparison is fulfilled
type: AnswerComment
comment on: http://stackoverflow.com/a/52421459
type: Comment

http://stackoverflow.com/a/52294229
type: Answer
answers question: http://stackoverflow.com/q/52294174
has body: You can add k to the index calculated from a sliced input list: def find_min_index(A, k): sliced = A[k:] return k + sliced.index(min(sliced)) find_min_index([1, 2, 5, -1], 2) # 3 find_min_index([1, 1, 1, 5, 9], 2) # 2
score: 0

http://stackoverflow.com/a/52421016
has body: Does response.xpath('//h3[@class="geodir-entry-title"]/a/@href').extract() or response.xpath('//header[@class="geodir-entry-header"]/h3/a/@href').extract() Work for you? Looks like you just missed the h3 tag which contains the a tags you need.
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/52420801
score: 3
accepted answer of: http://stackoverflow.com/q/52420801
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52351641
has title: Floor and ceil function in python
upvote count: 0
answer count: 1
favorite count: 0
has body: I want to round up a float value to an integer in python to multiple of five. say 3.6 to 10 or 21.3 to 25
tagged with: python
has comment: http://stackoverflow.com/comment/91649326
score: -1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91648312
has answer: http://stackoverflow.com/a/52351677
downvote count: 1
type: Question

http://stackoverflow.com/a/52405033
accepted answer of: http://stackoverflow.com/q/52404998
upvote count: 6
answers question: http://stackoverflow.com/q/52404998
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 6
has body: Use: N = 3 df = pd.concat([df] * N, ignore_index=True) print (df) col 0 0 1 60 2 300 3 320 4 0 5 60 6 300 7 320 8 0 9 60 10 300 11 320

http://stackoverflow.com/q/52305421
has comment: http://stackoverflow.com/comment/100048951
downvote count: 0
has comment: http://stackoverflow.com/comment/96821671
has body: I'm trying to prefer packages from CondaForge (for availability and compatibility). However, Conda seems to want to prefer versions of core libraries (e.g. NumPy) from other channels. For example, when I try to install a new library, Conda offers to downgrade NumPy, but if I ask for the same library and NumPy, Conda no longer advises downgrade. Why? $ conda install -c conda-forge beautifulsoup4 The following NEW packages will be INSTALLED: beautifulsoup4: 4.6.3-py36_0 conda-forge The following packages will be UPDATED: numpy-base: 1.14.3-py36h0ea5e3f_1 --&gt; 1.15.0-py36h3dfced4_0 The following packages will be DOWNGRADED: blas: 1.1-openblas conda-forge --&gt; 1.0-mkl numpy: 1.15.1-py36_blas_openblashd3ea46f_1 conda-forge [blas_openblas] --&gt; 1.15.0-py36h1b885b7_0 scikit-learn: 0.19.2-py36_blas_openblasha84fab4_201 conda-forge [blas_openblas] --&gt; 0.19.1-py36hedc7406_0 scipy: 1.1.0-py36_blas_openblash7943236_201 conda-forge [blas_openblas] --&gt; 1.1.0-py36hc49cb51_0 Proceed ([y]/n)? n $ conda install -c conda-forge beautifulsoup4 numpy The following NEW packages will be INSTALLED: beautifulsoup4: 4.6.3-py36_0 conda-forge Proceed ([y]/n)? y Is there a preference that will give better behaviour?
upvote count: 8
type: Question
tagged with: numpy
has title: conda-forge: Why does Conda inconsistently want to downgrade NumPy?
has answer: http://stackoverflow.com/a/52305581
has answer: http://stackoverflow.com/a/56386152
tagged with: conda
answer count: 3
has answer: http://stackoverflow.com/a/52335461
favorite count: 0
score: 8
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/67107320
answers question: http://stackoverflow.com/q/52317696
score: 10
upvote count: 10
type: Answer
has body: Two ways to run a python 3 script with a filename 'fibo.py': The argument is the name of the .py file. python fibo.py The argument is the name of a Python module, without .py python -m fibo
downvote count: 0

http://stackoverflow.com/comment/91663102
comment on: http://stackoverflow.com/q/52359312
type: QuestionComment
has text: `iter` has not been yet implemented for Blackman windows (check [here](https://github.com/pandas-dev/pandas/issues/11704) ) so I'd guess getting the `max` is still not possible?
score: 0
type: Comment

http://stackoverflow.com/comment/107247402
type: AnswerComment
comment on: http://stackoverflow.com/a/60619417
type: Comment
score: 1
has text: Hi @Chandra, could you please elaborate on the answer you provided? Which check boxes it needs to be checked?

http://stackoverflow.com/q/52320928
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52321105
type: Question
has comment: http://stackoverflow.com/comment/91589631
answer count: 1
has body: Just curious: Is there a way to (ab)use the string.formatmethod without any arguments? Say I want a string like this: 'foo bar ' # Desired string I could create a template string like: 'foo{:3}bar{:4}' And then use it with dummy parameters like: &gt;&gt;&gt; 'foo{:3}bar{:4}'.format('', '') 'foo bar ' &gt;&gt;&gt; 'foo{:3}bar{:4}'.format(*' ') 'foo bar ' Since omitting parameters will give this error: &gt;&gt;&gt; 'foo{:3}bar{:4}'.format() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IndexError: tuple index out of range I can even create a single dummy variable like: 'foo{s:3}bar{s:4}'.format(s='') But is there an even more elegant way to create parameterized strings using string.format?
has comment: http://stackoverflow.com/comment/91589456
has comment: http://stackoverflow.com/comment/91589565
has title: Python: Is it possible to use the string.format method without arguments?
has comment: http://stackoverflow.com/comment/91589708
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/52321105
has comment: http://stackoverflow.com/comment/91589625

http://stackoverflow.com/a/52272998
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52272850
upvote count: 1
type: Answer
has body: If your dataframe is structured correctly, your code will work: df = pd.DataFrame({'TR_2018': [17102.2], 'TR_2016': [2111.5]}) df['RevenueCAGR'] = np.power(df['TR_2018']/df['TR_2016'], 1/3) -1 print(df) TR_2016 TR_2018 RevenueCAGR 0 2111.5 17102.2 1.008262

http://stackoverflow.com/a/52307825
score: 0
answers question: http://stackoverflow.com/q/52293475
type: Answer
has body: Note: Not tested. Use at own risk. The main idea is to read data in chunks (number of rows) and append them to the file by passing the chunksize argument to read_csv. This argument can optionally be passed to to_csv for the same purpose. Although I have not profiled this code, in general, reading in chunks and writing in chunks can improve IO performance, especially for large files. def combine_directory_txt(file_paths, output_filename, chunksize): """Merge collection of files. :param file_paths: Collection of paths of files to merge. :param output_filename: Path of output file (i.e., merged file). :param chunksize: Number of lines to read in at one time. """ with open(output_filename, "wb") as outfile: chunk_transfer(file_paths[0], outfile, chunksize, append=False) for path in file_paths[1:]: chunk_transfer(path, outfile, chunksize, append=True) def chunck_transfer(path, outfile, chunksize, append, include_index=False): """Transfer file at path to outfile in chunks. :param path: Path of file to transfer. :param outfile: File handler for output file. :param chunksize: Number of lines to read at a time. :param append: Whether to append to file or write new file. :param include_index: Whether to include index of dataframe. """ with open(path, "rb") as infile: df = pd.read_csv(infile, sep='|', error_bad_lines=False, # low_memory=False, encoding='mbcs', chunksize=chunksize) if append: include_header = False mode = 'a' else: include_header = True mode = 'w' # Possible to pass chunksize as an argument to to_csv df.to_csv(outfile, mode=mode, header=include_header, index=include_index)

http://stackoverflow.com/q/52314785
has comment: http://stackoverflow.com/comment/91689933
has comment: http://stackoverflow.com/comment/91579531
upvote count: 3
tagged with: gpu
favorite count: 0
type: UnansweredQuestion
has title: Tensorflow: terminate called after throwing an instance of 'std::system_error'
tagged with: python
score: 3
answer count: 0
downvote count: 0
has body: My script fails always on session = tf.Session(config=config) with this error terminate called after throwing an instance of 'std::system_error' what(): Resource temporarily unavailable Neúspěšně ukončen (SIGABRT) import os import subprocess import tensorflow as tf def setGPU(): free_gpu = subprocess.check_output( 'nvidia-smi -q | grep "Minor\|Processes" | grep "None" -B1 | tr -d " " | cut -d ":" -f2 | sed -n "1p"', shell=True) if len(free_gpu) == 0: print ('No free GPU available!') sys.exit(1) os.environ['CUDA_VISIBLE_DEVICES'] = free_gpu.decode().strip() print('I got GPU!') return int(free_gpu.strip()) setGPU() config = tf.ConfigProto() config.gpu_options.per_process_gpu_memory_fraction = 0.5 session = tf.Session(config=config) Did anybody encounter something similer - any advice?
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/91785667
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52421063
has text: Those links are good enough for you to get started. For source control, I suggest https://www.fullstackpython.com/source-control.html

http://stackoverflow.com/comment/91508536
has text: Thanks for the post which is pretty helpful. Please have a look at the end of my edited post.
type: AnswerComment
comment on: http://stackoverflow.com/a/52280138
score: 0
type: Comment

http://stackoverflow.com/comment/91700441
comment on: http://stackoverflow.com/q/52377783
type: QuestionComment
type: Comment
score: 0
has text: Why are you _only_ subtracting 26, though? What if I ask you to rotate 'a' by 26*2=52, or 26*100? You obviously want to get back to ord('a')=97, but you're only subtracting 26..

http://stackoverflow.com/comment/91640469
type: Comment
comment on: http://stackoverflow.com/q/52339088
type: QuestionComment
has text: what happens if the shape is not convex?
score: 0

http://stackoverflow.com/comment/91558465
has text: Your data has only data at a date granularity. Were you expecting time as well? Cos it is not in the data you are scraping. If not, not sure what you mean by a full date.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52305465

http://stackoverflow.com/a/52397728
accepted answer of: http://stackoverflow.com/q/52397284
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52397284
has body: The problem is with the code you are using to convert county_name to lower. Map returns an iterator and you need to store it in a data type. Plus when you are using pandas, you can simply use the pandas str methods. df2['county_name'] = df2['county_name'].str.lower() df1['county_name'] = df1['county_name'].str.lower() df1['fips_county'] = df1['fips_county'].astype(str).str.zfill(3) df1['fips'] = df1'fips_state','fips_county'.astype(str).apply(lambda x: ''.join(x), axis=1) df1.merge(df1) You get fips_state fips_county county_name fips 0 48 000 texas 48000 1 48 001 anderson 48001 2 48 003 andrews 48003 3 48 005 angelina 48005
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91776055
comment on: http://stackoverflow.com/q/52377410
score: 0
has text: It seems to me that we are caught between a rock and a hard place. Changing the encoding format for Python would change a rare problem (cannot encode in Thrift C++ and decode in Thrift Python) into a common problem (cannot encode in old version of Thrift Python and decode in new version of Thrift Python)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52293174
downvote count: 0
tagged with: paramiko
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52307563
has comment: http://stackoverflow.com/comment/91820505
score: 1
favorite count: 0
type: Question
tagged with: ssh
tagged with: python
tagged with: dictionary
answer count: 1
linked to: http://stackoverflow.com/q/3294889
has answer: http://stackoverflow.com/a/52307563
upvote count: 1
has body: In Paramiko, how to pass a list or dict to exec_command and save results to a list or dict? I need sleep between exec_command. Commands are not executed sequentially, but in the order of 1, 2, 1. stdin, stdout, stderr = ssh.exec_command(d.values()[0]) reuslt1 = stdout.read() stdin, stdout, stderr = ssh.exec_command(d.values()[1]) reuslt2 = stdout.read() stdin, stdout, stderr = ssh.exec_command(d.values()[0]) reuslt3 = stdout.read() If there are no two problems mentioned above, I have tried map(), it works fine. cmd = ['xxx', 'xxx'] def func(cmd): stdin, stdout, stderr= ssh.exec_command(cmd) result = stdout.read() return result list(map(func, cmd)) My problem is that I need to SSH a remote Linux, replace a string in a file. ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, port, username, password) command = { "search" : "grep$img_name ='string' file", "modify" : "sed -i 's/$img_name = $now/$img_name = $word/g' file", } stdin, stdout, stderr = ssh.exec_command(command.values()[0]) before = stdout.read() sleep(1) ##If I don't add the wait, I will grep the string twice before the modification. ssh.exec_command(command.values()[1]) sleep(1) stdin, stdout, stderr = ssh.exec_command(command.values()[0]) after = stdout.read() ##Confirm that my modification was successful ssh.close() I don't want to repeat coding stdin, stdout, stderr = ssh.exec_command().
has title: In Paramiko, execute commands from a list or dict and save the result to a list or dict
has comment: http://stackoverflow.com/comment/91540360

pypdf
tags question: http://stackoverflow.com/q/52303980
type: Tag
tag name: pypdf
tags question: http://stackoverflow.com/q/52271908
tags question: http://stackoverflow.com/q/52285281
tags question: http://stackoverflow.com/q/52282223
tags question: http://stackoverflow.com/q/52306584
tags question: http://stackoverflow.com/q/52315259

http://stackoverflow.com/q/52429406
answer count: 6
possible better answer: http://stackoverflow.com/a/52429725
has title: Python: union of set of tuples
has answer: http://stackoverflow.com/a/52429455
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/52429473
has comment: http://stackoverflow.com/comment/91802622
has comment: http://stackoverflow.com/comment/91802682
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/52429717
has body: Let's say we have two sets: t = {('b', 3), ('a', 2)} r = {('b', 4), ('c', 6)} I want a union on 1st element to result in u = {('b', 3), ('a', 2), ('c', 6)} if duplicate symbol is present in both place (example 'b' in the above) then the element of the first list should be retained. Thanks.
has comment: http://stackoverflow.com/comment/91802401
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52429668
accepted answer: http://stackoverflow.com/a/52429455
has answer: http://stackoverflow.com/a/52429495
has answer: http://stackoverflow.com/a/52429725
type: Question
score: 2
downvote count: 0

http://stackoverflow.com/comment/91786719
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52421459
has text: So would I put that array statement inside my f.when()?
type: AnswerComment

http://stackoverflow.com/q/52336807
has comment: http://stackoverflow.com/comment/91621231
tagged with: pyqt
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/91621173
favorite count: 0
has body: I'm trying to get an image to fit my label entirely without using setScaledContents(True) since I'd like my ImageGrab to have the exact same dimensions as the QLabel space. I use a PIL ImageGrab with a bbox. if I chance the parameters to a wider width and higher height it will crash the program without any errors. I have attached a picture where the Image in the Label is localed left center. I'd like it to the top left. So that it can expand down and to the right if I increased the size. But I am curious as to why I am unable to increase the size of the bbox. (0, 0, 400, 220) works fine but (0, 0, 420, 220) will not upload the Image and closes down the GUI without any errors. I'd like to have a ImageGrab with bbox (0, 0, 800, 700) and a QLabel with size(800, 700) so it can fit it perfectly. class Main(QMainWindow): def __init__(self, parent=None): QWidget.__init__(self, parent) self.setGeometry(200, 200, 1000, 700) self.setWindowTitle('threads') self.mainFrame = QFrame(self) self.mainFrame.resize(1000, 650) self.mainFrame.move(0, 50) self.mainFrame.setStyleSheet("background-color: rbg(50, 50, 50)") self.testButton = QPushButton("Click", self) self.testButton.resize(500,30) self.connect(self.testButton, SIGNAL("clicked()"), self.Capture) self.label_ = QLabel(self.mainFrame) self.label_.move(10, 10) self.label_.resize(980, 630) self.label_.setStyleSheet("background-color: rbg(150, 150, 150)") @pyqtSlot(QImage) def ChangeFrame(self, image): pixmap = QPixmap.fromImage(image) self.label_.setPixmap(pixmap) def Capture(self): self.thread_ = CaptureScreen() self.connect(self.thread_, SIGNAL("ChangeFrame(QImage)"), self.ChangeFrame, Qt.QueuedConnection) self.thread_.start() class CaptureScreen(QThread): pixmap = pyqtSignal(QImage) def __init__(self, parent = None): QThread.__init__(self) def __del__(self): print("?????") self.exiting = True self.wait() def run(self): while(True): time.sleep(1/60) img = ImageGrab.grab(bbox=(0, 0, 420, 220)) frame = ImageQt(img) frame = QImage…
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has title: Pixmap image size in Qlabel
has answer: http://stackoverflow.com/a/52337767
accepted answer: http://stackoverflow.com/a/52337767
type: Question
tagged with: qlabel
tagged with: pyqt4

http://stackoverflow.com/q/52290821
type: Question
has comment: http://stackoverflow.com/comment/91530564
has body: I have 3 models - site, organization and institution defined as below. The problem is that when I run the migrations I get the following error: File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 42, in defaulterrorhandler raise errorvalue django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'None) NOT NULL, `site_uid` varchar(50) NOT NULL)' at line 1") site.py class Site(models.Model): STATUS = ( ('Active', 'Active'), ('Pending', 'Pending'), ('Incomplete', 'Incomplete') ) uid = models.CharField(primary_key=True, max_length=50, unique=True, editable=False) site_name = models.CharField(max_length=100, null=False, default='') country = models.CharField(max_length=100, null=False, default='') postcode = models.CharField(max_length=20, null=False, default='') full_address = models.TextField(max_length=200, null=False, default='') status = models.CharField(max_length=20, choices=STATUS, default='Pending') created_on = models.DateTimeField(default=date.today) def __str__(self): return self.site_name organization.py class Organization(models.Model): STATUS = ( ('Active', 'Active'), ('Pending', 'Pending'), ('Incomplete', 'Incomplete') ) uid = models.CharField(primary_key=True, max_length=50, unique=True, editable=False, default=uuid.uuid4) organization_name = models.CharField(max_length=100, null=False, default='') country = models.CharField(max_length=100, null=False, default='') postcode = models.CharField(max_length=20, null=False, default='') full_address = models.TextField(max_length=50, null=True, blank=True) status = models.CharField(max_length=20, choices=STATUS, default='Pending') created_on = models.DateTimeField(default=date.today) def __str__(self): return self.organization_name institution.py class Institution(models.Model): uid = models.CharField(primary_key=True, max_length=50, unique=True, editable=False, default=uuid.uuid4…
has answer: http://stackoverflow.com/a/52292680
score: 0
has comment: http://stackoverflow.com/comment/91530342
has comment: http://stackoverflow.com/comment/91530993
has comment: http://stackoverflow.com/comment/91529448
answer count: 1
has comment: http://stackoverflow.com/comment/91529861
has comment: http://stackoverflow.com/comment/91529606
has comment: http://stackoverflow.com/comment/91530030
has comment: http://stackoverflow.com/comment/91530620
has comment: http://stackoverflow.com/comment/91530963
has title: Django migrate returning 1064 - You have an error in your SQL syntax
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/31336423
accepted answer: http://stackoverflow.com/a/52292680
has comment: http://stackoverflow.com/comment/91530931
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91530852

http://stackoverflow.com/q/52369454
accepted answer: http://stackoverflow.com/a/52369557
type: Question
has title: Concatenate Excel files, use filename as an index throwing an error
downvote count: 0
has body: I have around 20 XLSX files ranging from 4-10 mb. I want to grab a certain sheet in those xlsx files and concat them into one file. Each xlsx file is named in a sequential week order, and the sheet I am trying to parse has no date, so I'm using the file_name as the the index and will reverse engineer a week date. I am using the following code, which I use quite often to concat multiple files into one df. I am also using basename to add in the name but get the following error. ValueError: Length mismatch: Expected axis has 461 elements, new values have 457 elements import pandas as pd from os.path import basename import os import glob path = os.getcwd() allFiles = glob.glob(path + "/*.xlsx") frame = pd.DataFrame() master_list = [] for file_ in allFiles: df = pd.read_excel(file_,sheet_name = "Base data",index_col=None, header=0) df.index = [os.path.basename(f)] * len(data) master_list.append(df) frame = pd.concat(master_list)
tagged with: pandas
answer count: 1
favorite count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52369557
type: AnsweredQuestion
score: 1

http://stackoverflow.com/a/52373735
answers question: http://stackoverflow.com/q/52373683
type: Answer
has comment: http://stackoverflow.com/comment/112478762
score: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/112575746
has body: seq = "mango mango peach".split() [x for x in seq if x not in seq[seq.index(x)+1:]]
upvote count: 4
has comment: http://stackoverflow.com/comment/91692224
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52373683
has comment: http://stackoverflow.com/comment/113716020

http://stackoverflow.com/q/52427782
tagged with: matplotlib
score: 0
has title: Matplotlib pyplot crush a ladder python
answer count: 1
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52427969
tagged with: python
has body: I have this sample data (I report just few rows): date price sentiment 0 2018-09-18 0.0034 0.250000 1 2018-09-17 0.0034 0.083333 2 2018-09-16 0.0034 0.281250 3 2018-09-15 0.0035 0.096774 4 2018-09-14 0.0036 -0.039216 5 2018-09-13 0.0034 0.416667 6 2018-09-12 0.0031 0.061224 My code sample is this: import pandas as pd import datetime as dt import matplotlib.pyplot as plt df = df.set_index(pd.to_datetime(df.date), drop=True) params = {"text.color" : "black", 'figure.figsize': (13, 5), "xtick.color" : "crimson", "ytick.color" : "crimson"} plt.rcParams.update(params) fig = plt.figure() df.price.plot(grid=True, label="Price", legend=True, color='#228B22', title='Price vs Sentiment') df.sentiment.plot(grid=True, secondary_y=True, label="Sentiment", legend=True, color='#3D59AB') plt.show() I would like to crash the sentiment line in my plot in order to take a look better at the variations, maybe showing the entire range [-1;1] of the sentiment. Any suggestions? How could I improve my plot below?
linked to: http://stackoverflow.com/q/14762181
has comment: http://stackoverflow.com/comment/91798905
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52427969

http://stackoverflow.com/a/52289929
has body: Using sum with an appropriate generator expression producing the probability weighted lengths: chars = {'m': '110', 'a': '0', 's': '111', 'y': '10'} probs = [('m', 0.16666666666666666), ('a', 0.5), ('s', 0.16666666666666666), ('y', 0.16666666666666666)] avg_len = sum(p * len(chars[c]) for c, p in probs) # ^^^^^^^^^^^^^^^^^ --- prob-weighted length of char c # 1.8333333333333333 print('average length of character: {:.2f}'.format(avg_len))
type: Answer
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52289808

http://stackoverflow.com/comment/91710169
type: Comment
has text: @MuhammadDanial your issue is not related to age verification popup, the data is most likely loaded via javascript: https://stackoverflow.com/questions/8550114/can-scrapy-be-used-to-scrape-dynamic-content-from-websites-that-are-using-ajax?rq=1
comment on: http://stackoverflow.com/a/52382116
score: 0
type: AnswerComment

http://stackoverflow.com/q/52335671
has comment: http://stackoverflow.com/comment/91619195
tagged with: python
type: AnsweredQuestion
downvote count: 0
has body: I would like to shorten my ODE equations somehow, becuase the code will become messy otherwise. I have tried using ancillary functions, like fe() here, but this doesn't work. The code below is just an example Any advice is welcomed! Thanks! # Import the required modules import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint # Here the parameters a,b,c,d = 1,1,1,1 def fe(P[0]): return d*P[0] # Define a function which calculates the derivative def dP_dl(P, l): return [P[0]*(a - b*P[1]), -P[1]*(c - fe(P[0]) )] ts = np.linspace(0, 12, 100) P0 = [1.5, 1.0] Ps = odeint(dP_dl, P0, ts) prey = Ps[:,0] predators = Ps[:,1] plt.plot(ts, prey, "+", label="Rabbits") plt.plot(ts, predators, "x", label="Foxes") plt.xlabel("Time") plt.ylabel("Population") plt.legend(); This is what i got from the python console. Python 3.6.3 |Anaconda, Inc.| (default, Oct 15 2017, 07:29:16) [MSC v.1900 32 bit (Intel)] Type "copyright", "credits" or "license" for more information. IPython 6.1.0 -- An enhanced Interactive Python. runfile('C:/Users/Matteo S/Desktop/vocaboli tedesco/untitled0.py', wdir='C:/Users/Matteo S/Desktop/vocaboli tedesco') Traceback (most recent call last): File "C:\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "", line 1, in runfile('C:/Users/Matteo S/Desktop/vocaboli tedesco/untitled0.py', wdir='C:/Users/Matteo S/Desktop/vocaboli tedesco') File "C:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile execfile(filename, namespace) File "C:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Matteo S/Desktop/vocaboli tedesco/untitled0.py", line 17 def fe(P[0]): ^ SyntaxError: invalid syntax
score: 1
has comment: http://stackoverflow.com/comment/91638851
tagged with: odeint
tagged with: ode
type: Question
accepted answer: http://stackoverflow.com/a/52336160
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/91619324
favorite count: 0
has title: How to shorten ODE equations using ancillary functions
has answer: http://stackoverflow.com/a/52336160

http://stackoverflow.com/comment/91548404
comment on: http://stackoverflow.com/a/52300147
score: 1
type: AnswerComment
has text: Seems you have overcomplicated the solution (while question still is not quite clear)
type: Comment

http://stackoverflow.com/comment/91549406
type: AnswerComment
type: Comment
has text: df[~df.ids.fillna('').str.contains('Extra',case=False)]
score: 1
comment on: http://stackoverflow.com/a/52300311

http://stackoverflow.com/comment/91757556
has text: Try looking at answers on [this](https://stackoverflow.com/questions/6913532/display-a-decimal-in-scientific-notation) page
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52406584

http://stackoverflow.com/a/52453924
type: Answer
has body: DIY use the library that I have created https://github.com/omar7altawil/LSM9DS1-I2C
score: 0
answers question: http://stackoverflow.com/q/52421371

http://stackoverflow.com/a/52328031
answers question: http://stackoverflow.com/q/52327864
accepted answer of: http://stackoverflow.com/q/52327864
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: From the ls output ---------- 1 sungha sungha 1418 Sep 14 13:54 Elliptic_main.py Notice the ---------- part that shows which permissions are set (see for example in this wiki for further details) In your case you don't have ANY permissions on that file which is why you see Permission error Try chmod 600 # in case sungha is your username chmod 666 # otherwise Check the manpage of chmod by typing man chmod in your terminal for further details on what the difference is between the two
upvote count: 3
score: 3

http://stackoverflow.com/a/52324016
upvote count: 1
downvote count: 0
has body: How about using the pop method, very good for what you are doing here: import random dogs = ['Bob', 'Fred', 'Jess', 'Rick', 'Alice', 'Joe', 'Max', 'Will'] for x in range(3): selection = random.randint(0, len(dogs)-1) goner = dogs.pop(selection) print(goner) Output (xenial)vash@localhost:~/python$ python3.7 pop.py Max Bob Joe When using pop you would need to use len due to the fact the list is going to change sizes and you are going to need a random int for that new list size.
type: Answer
answers question: http://stackoverflow.com/q/52322207
score: 1

http://stackoverflow.com/q/52295286
tagged with: hadoop
has title: How to make Group By and sort in Python for mapreducer in hadoop
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
upvote count: 1
type: Question
tagged with: group-by
tagged with: sorting
tagged with: mapreduce
has body: I have a dataset with 100k rows with 17 cols. I would like to know how to groupby and sort in hadoop mapreducer using python here is my mapper.py #!/usr/bin/python import sys for line in sys.stdin: data = line.strip().split(",") if len(data) == 17: VendorID, tpep_pickup_datetime, tpep_dropoff_datetime, passenger_count, trip_distance, RatecodeID, store_and_fwd_flag, PULocationID, DOLocationID, payment_type, fare_amount, extra, mta_tax, tip_amount, tolls_amount, improvement_surcharge, total_amount = data print passenger_count,"\t",PULocationID,"\t", DOLocationID my reducer.py #!/usr/bin/python import sys for line in sys.stdin: data_mapped = line.strip().split("\t") if len(data_mapped) != 3: continue passenger_count, PULocationID, DOLocationID = data_mapped passenger_count = int(passenger_count) if passenger_count &lt;2: print passenger_count,"\t", PULocationID, "\t", DOLocationID to run mapreducer in hadoop I used this cmd hadoop jar /usr/hdp/current/hadoop-mapreduce-client/hadoop-streaming.jar -mapper mapper.py -reducer reducer.py -input /user/maria_dev/trim_table.csv -output /user/maria_dev/joboutput1 -file /root/mapper.py /root/reducer.py the output of my joboutput 1 161 142 1 170 162 1 233 248 1 68 230 1 237 237 and so on with some duplication and unsorted. Hope someone could help me. the output I wanted is count|PULocationID|DOLocationID I wanted to sort by count desc

http://stackoverflow.com/q/52297574
has comment: http://stackoverflow.com/comment/91543165
has title: find the entire string based on only the substring from a string
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/52297692
upvote count: 1
downvote count: 1
possible better answer: http://stackoverflow.com/a/52297665
has answer: http://stackoverflow.com/a/52297713
type: Question
has answer: http://stackoverflow.com/a/52297665
tagged with: python-3.6
answer count: 3
has answer: http://stackoverflow.com/a/52297692
favorite count: 0
has body: This might be a repetitive question, after searching for a bit, I couldn't find an answer and thus I am posting the question. How do I find the entire string based on only the substring from a string? import re test = 'INFO: 106.00s - SearchDriver: GET CThru=27.027 OThru=25.566 CErr=0.000 CResp=0.013 OResp=0.011 CSD=0.015 OSD=0.010 C90%Resp=0.025 O90%Resp=0.025' To get the value of CThru=27.027, I'm trying to do this. re.findall("CThru=*", test) but it returns only ['CThru=']
tagged with: python
tagged with: regex

http://stackoverflow.com/comment/91543934
type: QuestionComment
score: 0
has text: it fails because `\v` is interpreted as a vertical tabulation.
type: Comment
comment on: http://stackoverflow.com/q/52297758

http://stackoverflow.com/a/52398470
type: AcceptedAnswer
upvote count: 1
has body: sess.run(...) returns the result of evaluating the tensor result given the data passed to feed_dict. So, what you want is output = sess.run(result, feed_dict = {x: x_tensor_ch, w:w_tensor_ch})
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52398441
answers question: http://stackoverflow.com/q/52398441

http://stackoverflow.com/comment/91593753
type: Comment
comment on: http://stackoverflow.com/a/52308225
type: AnswerComment
score: 0
has text: Does tagging just help the programmer or also change the program?

http://stackoverflow.com/comment/91754302
has text: I am not familiar with shell. Do you need to compare every entry in file2 with every entry in file1 or do you only need to compare the ones, where `chr` match?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52404173
score: 1

http://stackoverflow.com/comment/91610648
type: AnswerComment
comment on: http://stackoverflow.com/a/52331533
has text: Do you expect the value of `timee` to be changed outside the function? Because then you will need to either `return timee` and capture the result, or use `global`
score: 0
type: Comment

http://stackoverflow.com/a/52349940
downvote count: 0
answers question: http://stackoverflow.com/q/52349926
has body: It's just a shell command. Not any different from cd or grep, etc. In the case of Python, the python command invokes the Python interpreter, starting either an interactive session, or, if a file is specified, running the file through the interpreter. But it just tells the shell something to do.
accepted answer of: http://stackoverflow.com/q/52349926
upvote count: 6
type: AcceptedAnswer
type: Answer
score: 6

http://stackoverflow.com/a/52304904
type: Answer
has body: Solution people = { 2308:[ {'name':'john'},{'age':'24'},{'employed':'yes'} ], 3452:[ {'name':'sam'},{'age':'45'},{'employed':'yes'} ], 1234:[ {'name':'victor'},{'age':'72'},{'employed':'no'} ] } people_over_30 = {} for k, v in people.items(): for i in range(len(v)): if int(v[i].get('age', 0)) &gt; 30: people_over_30[k] = [v] print(people_over_30) Output (xenial)vash@localhost:~/python$ python3.7 quote.py {3452: [[{'name': 'sam'}, {'age': '45'}, {'employed': 'yes'}]], 1234: [[{'name': 'victor'}, {'age': '72'}, {'employed': 'no'}]]} Comments Unless this is your desired structure for this particular code, I would suggest reformatting your dictionary to look like this people = { 2308: {'name':'john','age':'24','employed':'yes'} , 3452: {'name':'sam','age':'45','employed':'yes'} , 1234: {'name':'victor','age':'72','employed':'no'} } And then your work would be much simpler and able to handle with this instead for k, v in people.items(): if int(v.get('age', 0)) &gt; 30: people_over_30[k] = [v]
answers question: http://stackoverflow.com/q/52286402
score: 0

http://stackoverflow.com/q/52386872
tagged with: compare
answer count: 1
has body: I'm still new to python and cannot achieve to make what i'm looking for. I'm using Python 3.7.0 I have one file, called log.csv, containing a log of CANbus messages. I want to check what is the content of column label Data2 and Data3 when the ID is 348 in column label ID. If they are both different from "00", I want to make a new string called fault_code with the "Data3+Data2". Then I want to check on another CSV file where this code string appear, and print the column 6 of this row (label description). But this last part I want to do it only one time per fault_code. Here is my code: import csv CAN_ID = "348" with open('0.csv') as log: reader = csv.reader(log,delimiter=',') for log_row in reader: if log_row[1] == CAN_ID: if (log_row[5]+log_row[4]) != "0000": fault_code = log_row[5]+log_row[4] with open('Fault_codes.csv') as fault: readerFC = csv.reader(fault,delimiter=';') for fault_row in readerFC: if "0x"+fault_code in readerFC: print("{fault_row[6]}") Here is a part of the log.csv file Timestamp,ID,Data0,Data1,Data2,Data3,Data4,Data5,Data6,Data7, 396774,313,0F,00,28,0A,00,00,C2,FF 396774,314,00,00,06,02,10,00,D8,00 396775,**348**,2C,00,**00,00**,FF,7F,E6,02 and this is a part of faultcode.csv Level;LED Flashes;UID;FID;Type;Display;Message;Description;RecommendedAction 1;2;1;**0x4481**;Warning;F12001;Handbrake Fault;Handbrake is active;Release handbrake 1;5;1;**0x4541**;Warning;F15001;Fan Fault;blablabla;blablalba 1;5;2;**0x4542**;Warning;F15002;blablabla First of all I get a TabError whith the second "with as". P:\07 CAN\04 CanLoger\03 Script>python script.py File "script.py", line 12 readerFC = csv.reader(fault,delimiter=';') ^ TabError: inconsistent use of tabs and spaces in indentation There is another syntax if you have a "with as" inside a "with as"? Also do you think of a better way to do this task? I've read that Pandas can be very good for large files. As log.csv can have 100'000+ row, it's maybe a better idea to use it. What do you think? Thank you for y…
favorite count: 0
has answer: http://stackoverflow.com/a/52387149
has comment: http://stackoverflow.com/comment/91719187
tagged with: python
has comment: http://stackoverflow.com/comment/91718367
downvote count: 1
has comment: http://stackoverflow.com/comment/91718336
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/5685406
has title: Parsing two files with Python
score: -1
accepted answer: http://stackoverflow.com/a/52387149
type: Question
linked to: http://stackoverflow.com/q/45621722
has comment: http://stackoverflow.com/comment/91718276
upvote count: 0
duplicate of: http://stackoverflow.com/q/45621722
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/a/52384594
score: 1
answers question: http://stackoverflow.com/q/52383786
upvote count: 1
has body: You can create DatetimeIndex and then use DataFrame.between_time: df['time1'] = pd.to_datetime(df['time1']) df = df.set_index('time1') df = df.between_time('07:20:00','13:50:00') If working with times use boolean indexing: print (type(df.loc[0, 'time1'])) &lt;class 'datetime.time'&gt; from datetime import time df = df[(df.time1 &gt; time(7,20,0)) &amp; (df.time1 &lt; time(13,50,0))] Or convert times to timedeltas: #if input are strings print (type(df.loc[0, 'time1'])) &lt;class 'str'&gt; df['time1'] = pd.to_timedelta(df['time1']) #if input are times print (type(df.loc[0, 'time1'])) &lt;class 'datetime.time'&gt; df['time1'] = pd.to_timedelta(df['time1'].astype(str)) print (type(df.loc[0, 'time1'])) &lt;class 'pandas._libs.tslibs.timedeltas.Timedelta'&gt; df = df[(df['time1']&gt; '07:20:00') &amp; (df['time1'] &lt; '13:50:00')]
type: Answer
downvote count: 0

http://stackoverflow.com/comment/91798284
score: 0
type: Comment
has text: @RafaelVidal Well what do you mean, the code is the same? Still the same "problem". Thank you.
type: AnswerComment
comment on: http://stackoverflow.com/a/52425147

http://stackoverflow.com/comment/91793991
type: Comment
has text: Thank you! I think it worked. Is there an "easy" way to change strings into floats?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52425509

http://stackoverflow.com/comment/91542466
type: Comment
comment on: http://stackoverflow.com/a/52297283
type: AnswerComment
has text: It's not a list, it's a Pandas Series, the error is clear it's not a list.
score: 0

http://stackoverflow.com/a/52279464
answers question: http://stackoverflow.com/q/52279094
has body: Just use get_dummies() import pandas as pd df=pd.DataFrame({'Gender':['M','F','I']}) pd.get_dummies(df) Gender_F Gender_I Gender_M 0 0 1 1 0 0 0 1 0
accepted answer of: http://stackoverflow.com/q/52279094
downvote count: 0
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/52413898
type: Answer
answers question: http://stackoverflow.com/q/52394833
has body: You could get your url parameters from view_kwargs argument of your middleware's process_view method. From that you can simply make a query to get the id. I am assuming that your url has a parameter named slug, then you can do something like this: class MultipleProxyMiddleware(MiddlewareMixin): def process_view(self, request, view_func, view_args, view_kwargs): # PostDetail is CBV with slug. if view_func.__name__ == PostDetail.__name__: ip, is_routable = get_client_ip(request) cache_name = f'post_{uuid.uuid4()}' post_id = Post.objects.get(slug=view_kwargs['slug']).id cache.set(cache_name, { 'ip': ip, 'post_id': post_id, 'created': now(), }, timeout=None)
score: 0

http://stackoverflow.com/q/52413773
has answer: http://stackoverflow.com/a/52414075
accepted answer: http://stackoverflow.com/a/52437378
tagged with: command-line
type: AnsweredQuestion
type: Question
has title: How to run a python script taking arguments with blender?
has answer: http://stackoverflow.com/a/52437378
has body: I have a script I want to run within blender to generate AO maps (script was given to me and the source guarantees it works). I try to run the script as follows: blender --background --python /opt/ff/product_builder/furniture_builder/generate_ao_maps.py --input_dir /tmp/test.obj --output_dir /tmp/test.png --mode ao Which produces: AL lib: (EE) UpdateDeviceParams: Failed to set 44100hz, got 48000hz instead found bundled python: /usr/share/blender/2.79/python Traceback (most recent call last): File "/opt/ff/product_builder/furniture_builder/generate_ao_maps.py", line 195, in &lt;module&gt; main() File "/opt/ff/product_builder/furniture_builder/generate_ao_maps.py", line 178, in main args = parse_args() File "/opt/ff/product_builder/furniture_builder/generate_ao_maps.py", line 21, in parse_args return parser.parse_args(os.getenv(BLENDER_ENV).split(' ')) AttributeError: 'NoneType' object has no attribute 'split' Error: File format is not supported in file '/tmp/test.obj' Blender quit If I run this same script without blender (but with the argument) it tells me: Traceback (most recent call last): File "/opt/ff/product_builder/furniture_builder/generate_ao_maps.py", line 5, in &lt;module&gt; import bpy ImportError: No module named bpy What do I need to do to pass the parameters to the script and get it working?
tagged with: blender
has comment: http://stackoverflow.com/comment/91822033
answer count: 2
score: 0
possible better answer: http://stackoverflow.com/a/52414075
tagged with: scripting
tagged with: python

http://stackoverflow.com/q/52404794
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/30635145
answer count: 0
has body: I have a dataset like this: I want to create a dataframe for each type of COD_VARIABLE, for instance I want a dataframe called 179(doesnt matter the name ofc) with all the rows that have 179 on COD_VARIABLE, and so on with the other values of COD_VARIABLE. I know how to do it one by one but would be useful to know how to make a function of for loop that does it. I checked this but it doesnt help me: Create multiple dataframes in loop
has comment: http://stackoverflow.com/comment/91753819
tagged with: dataframe
linked to: http://stackoverflow.com/q/19790790
type: Question
tagged with: numpy
duplicate of: http://stackoverflow.com/q/19790790
has title: Create different dataframe from one given condition
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/91753362

http://stackoverflow.com/comment/91594843
has text: your code works and solved my problem but can u help me with one more thing ? why there is last part new_list=list1[j-40:] #the last part of the list i dont want anything left in the list
type: Comment
comment on: http://stackoverflow.com/a/52323667
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91661053
score: 1
comment on: http://stackoverflow.com/q/52357594
type: QuestionComment
has text: @Robin then provide a [mcve]: **complete** - **verifiable**
type: Comment

http://stackoverflow.com/comment/91632736
type: Comment
comment on: http://stackoverflow.com/q/52342504
type: QuestionComment
has text: s variable stores and also mailer stores, i didn include.
score: 0

http://stackoverflow.com/comment/91624513
has text: Provide Good examples if you want to receive answers. `Orange 2018-08-30 820 870` How 870? From the top, Orange 1000 `-10` = 990; 900`-20` = 880(not 870);820``-30``=790....
score: 0
comment on: http://stackoverflow.com/q/52335386
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52358785
has body: You confused the order of clauses in the nested list comprehension. Correct expression: return [next_node for node in nodes for next_node in (node.left, node.right) if next_node] Think of a nested LC as a nested loop: an iteration of the outer loop (for node in nodes) is executed first.
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52358763
upvote count: 2
answers question: http://stackoverflow.com/q/52358763

http://stackoverflow.com/a/52361792
has comment: http://stackoverflow.com/comment/91668318
accepted answer of: http://stackoverflow.com/q/52361701
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52361701
upvote count: 3
type: Answer
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/91668358
has body: Use numpy.where: mask = df['NId'].notna() df['Cat'] = np.where(mask, 'NId','GId') df['Id'] = np.where(mask, df['NId'].astype(str), df['BName']) df['IdQ'] = np.where(mask, 'NId:' + df['NId'].astype(str), 'BId:' + df['BId']) print (df) Group NId BName BId Cat Id IdQ 0 Fruit Banana NaN nan NId Banana NId:Banana 1 Vegetable Onion GTwo 5252 NId Onion NId:Onion 2 Fruit Grapes NaN nan NId Grapes NId:Grapes 3 Vegetable Potato GSix 5678 NId Potato NId:Potato 4 Fruit Apple NaN nan NId Apple NId:Apple 5 Vegetable NaN GOne 5125 GId GOne BId:5125 6 Vegetable NaN GNine 5923 GId GNine BId:5923

http://stackoverflow.com/a/52390431
score: 11
has comment: http://stackoverflow.com/comment/91726047
downvote count: 0
has comment: http://stackoverflow.com/comment/91726090
has comment: http://stackoverflow.com/comment/91726116
upvote count: 11
has comment: http://stackoverflow.com/comment/91725973
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52390359
has body: You can use an outer product to get the desired output. You just have to append 100000 at the end in the answer as answer = np.append(answer, 100000) as pointed out by @Matt Messersmith Explanation Create a range of values on a logarithmic scale from 0.01 to 10000 [1.e-02 1.e-01 1.e+00 1.e+01 1.e+02 1.e+03 1.e+04] and then create a multiplier array [1 2 3 4 5 6 7 8 9] Finally, take the outer product to generate your desired range of values. a1 = np.logspace(-2, 4, 7) # a1 = 10.**(np.arange(-2, 5)) Alternative suggested by @DSM in the comments a2 = np.arange(1,10,1) answer = np.outer(a1, a2).flatten() Output [1.e-02 2.e-02 3.e-02 4.e-02 5.e-02 6.e-02 7.e-02 8.e-02 9.e-02 1.e-01 2.e-01 3.e-01 4.e-01 5.e-01 6.e-01 7.e-01 8.e-01 9.e-01 1.e+00 2.e+00 3.e+00 4.e+00 5.e+00 6.e+00 7.e+00 8.e+00 9.e+00 1.e+01 2.e+01 3.e+01 4.e+01 5.e+01 6.e+01 7.e+01 8.e+01 9.e+01 1.e+02 2.e+02 3.e+02 4.e+02 5.e+02 6.e+02 7.e+02 8.e+02 9.e+02 1.e+03 2.e+03 3.e+03 4.e+03 5.e+03 6.e+03 7.e+03 8.e+03 9.e+03 1.e+04 2.e+04 3.e+04 4.e+04 5.e+04 6.e+04 7.e+04 8.e+04 9.e+04]
answers question: http://stackoverflow.com/q/52390359
has comment: http://stackoverflow.com/comment/91725978
type: Answer

http://stackoverflow.com/comment/115809890
has text: @HanishShalah You have to match the wheel to your platform. The file you tried is for Python 3.8 64-bit. Check your Python version as described in the answer and try again with the appropriate `.whl` file.
type: AnswerComment
comment on: http://stackoverflow.com/a/55630212
type: Comment
score: 2

forms
tags question: http://stackoverflow.com/q/52341937
tags question: http://stackoverflow.com/q/52399776
tags question: http://stackoverflow.com/q/52340667
type: Tag
tags question: http://stackoverflow.com/q/52429033
tags question: http://stackoverflow.com/q/52310042
tags question: http://stackoverflow.com/q/52275690
tag name: forms
tags question: http://stackoverflow.com/q/52273358
tags question: http://stackoverflow.com/q/52362710

http://stackoverflow.com/comment/91678509
comment on: http://stackoverflow.com/a/52366719
has text: I mentioned that in the answer that it might not be what you want to do during the first iteration as i will be 0. The Java code in the question was starting the loop from 0 and I didn't want to deviate from that.
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52346223
type: Question
tagged with: algorithm
has comment: http://stackoverflow.com/comment/91638173
answer count: 2
has answer: http://stackoverflow.com/a/52346431
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52346541
type: UnansweredQuestion
tagged with: python
has title: Python: Longest Plateau Problem: to find the length and location of the longest contiguous sequence of equal values
downvote count: 0
score: 1
has body: The question is to solve the following question in Sedgewick Wayne's Python book: Given an array of integers, compose a program that finds the length and location of the longest contiguous sequence of equal values where the values of the elements just before and just after this sequence are smaller. I tried on this problem, and encountered some problems. Here are my codes: import sys import stdio # Ask the user input for the list of integers numList = list(sys.argv[1]) maxcount = 0 value = None location = None i = 1 while i &lt; len(numList) - 1: resList = [] count = 0 # If i &gt; i-1, then we start taking i into the resList if numList[i] &gt; numList[i - 1]: # start counting resList += [numList[i]] # Iterating through the rest of the numbers j = i + 1 while j &lt; len(numList): # If the j element equals the i, then append it to resList if numList[i] == numList[j]: resList += [numList[j]] j += 1 elif numList[i] &lt; numList[j]: # if j element is greater than i, break out the loop i = j break else: # if j element is smaller than i, count equals length of resList count = len(resList) if count &gt; maxcount: maxcount = count value = resList[1] location = i i = j else: # if not greater than the previous one, increment by 1 i += 1 stdio.writeln("The longest continuous plateau is at location: " + str(location)) stdio.writeln("Length is: " + str(maxcount)) stdio.writeln("Number is: " + str(value)) The result shows: python exercise1_4_21.py 553223334445554 The longest continuous plateau is at location: 11 Length is: 3 Number is: 5 python exercise1_4_21.py 1234567 The longest continuous plateau is at location: None Length is: 0 Number is: None But somehow, if the list given is in the format of having a group of continuous integers that is greater than the previous one, but then this group ends the list with no integer following it, my program simply doesn't end.... exercise1_4_21.py 11112222111444 Traceback (most recent call last): File "exercise1_4_21.py", line 32, in &lt;m…

http://stackoverflow.com/q/52282105
has comment: http://stackoverflow.com/comment/91512578
favorite count: 0
has comment: http://stackoverflow.com/comment/91512341
has comment: http://stackoverflow.com/comment/91535874
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Get unique id of computer in python
has comment: http://stackoverflow.com/comment/91512854
linked to: http://stackoverflow.com/q/16858782
has comment: http://stackoverflow.com/comment/91512527
score: 0
has body: I need to generate license for each software I distribute in the market. And I will store that license and computer unique id in my server database. So, What is the Computer's Unique Id in present? How to get it in Python-3 I Googled for it, but most answers I got is taking MAC Id, nowdays anyone can change the MAC Id.So, What is the best id that cannot be changed and is visible in Python-3
type: Question
has answer: http://stackoverflow.com/a/67241746
has comment: http://stackoverflow.com/comment/91512632
has comment: http://stackoverflow.com/comment/91512553
upvote count: 4
downvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/91512418
has comment: http://stackoverflow.com/comment/91512627
has answer: http://stackoverflow.com/a/52282660
tagged with: license-key
linked to: http://stackoverflow.com/q/3443093

http://stackoverflow.com/comment/91544272
has text: `json.loads(results).__class__()` results in `''` while `json.loads(json.loads(results)).__class__()` results in `{}` Why do I need to do `json.loads` twice?
comment on: http://stackoverflow.com/q/52297481
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52428467
tagged with: python
has comment: http://stackoverflow.com/comment/91800598
answer count: 0
downvote count: 0
score: 1
has title: python 'import' package works in shell but not in Jupyter Notebook. Why?
has comment: http://stackoverflow.com/comment/91801179
type: Question
upvote count: 1
tagged with: virtualenv
has body: I'm trying to import a custom package into my Jupyter Notebook, but I'm have issues. The package works when I open my terminal however I get a 'no module error' when importing the package into my notebook. I've set up a virtual environment with python3 -m venv and used setuptools to create a setup.py so I can use my custom packages This is my project structure ./-- notebook -- my_notebook.ipynb └── src -- funct -- func.py └── setup.py I also know I've correctly installed the package: $ pip3 list Package Version Location ---------- ------- ------------------------------------------------------- pip 18.0 setuptools 39.0.1 src 0.1.0 /Users/me/project In my terminal: $ python3 &gt;&gt;&gt; import src &gt;&gt;&gt; from src.funct import func &gt;&gt;&gt; func.foo() 'Foo' However, when I run import src in my notebook, I get: import src ImportError: No module named src This is my setup.py from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='Example', author='me', license='MIT', ) If the package can be imported correctly into my python shell, why can't it be imported into my notebook? Is this a permissions issue, and if so how can I check that? Any help would be appreciated. Thank you. * Update * Here is the SOURCES.txt generated from the setup.py README.md src/__init__.py src.egg-info/PKG-INFO src.egg-info/SOURCES.txt src.egg-info/dependency_links.txt src.egg-info/top_level.txt src/funct/__init__.py src/funct/func.py So now I'm more confused on why it won't import.
favorite count: 0
tagged with: jupyter-notebook
type: UnansweredQuestion

http://stackoverflow.com/q/52357501
favorite count: 0
type: Question
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/44911679
has answer: http://stackoverflow.com/a/58378200
score: 4
has answer: http://stackoverflow.com/a/52357888
has title: Django/django-tables2 html table on row click to edit form
has answer: http://stackoverflow.com/a/64127558
has body: sorry this post may be messy not sure how do explain what I am looking for very well but here goes nothing. I have a Django App and using django-table2 to print a data model to a table, the next thing I am looking to do it when the user clicks on the table row to redirect the page to a equivalent edit form urls.py path('', CustomerView.as_view(), name='customer'), path('customer_edit/', views.customer_edit, name='customer_edit'), tables.py import django_tables2 as tables from customer.models import Customer class CustomerTable(tables.Table): account = tables.Column(attrs={'td': {'class': 'account'}}) class Meta: model = Customer attrs = {'id': 'table'} exclude = ('is_deleted',) template_name = 'django_tables2/bootstrap-responsive.html' views.py from django.shortcuts import render from django_tables2 import RequestConfig from customer.models import Customer from customer.tables import CustomerTable from django.views.generic import TemplateView class CustomerView(TemplateView): template_name = 'customer/customer.html' def get(self, request, *args, **kwargs): table = CustomerTable(Customer.objects.all().filter(is_deleted=False)) RequestConfig(request).configure(table) return render(request, 'customer/customer.html', {'table': table}) def customer_edit(request): return render(request, 'customer/customer_edit.html') template {% extends 'base.html' %} {% load render_table from django_tables2 %} {% block head %} Dev Genie - Customers {% endblock %} {% block body %} {% render_table table %} {% endblock %} I am struggling to get the account code from the onclick even to pass the account code back to Django to move to the next page to begin editing the record I really think I am barking up the wrong tree with this any help would be very much appreciated
has answer: http://stackoverflow.com/a/69262199
answer count: 5
type: UnansweredQuestion
upvote count: 4
has answer: http://stackoverflow.com/a/52374960
downvote count: 0
tagged with: django-tables2

http://stackoverflow.com/comment/91570383
comment on: http://stackoverflow.com/a/52310674
has text: @tda Thanks for the suggestion
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91674433
score: 0
comment on: http://stackoverflow.com/q/52361288
type: Comment
type: QuestionComment
has text: @Angela miti is the nepali date while date in the model is used for english date

http://stackoverflow.com/comment/91534023
type: Comment
comment on: http://stackoverflow.com/q/52293079
has text: Do you think `datadf['new'] = matchlist` ?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91767683
has text: Do you understand how the data of that structured array is laid out? What you get with `my_array['field1']` and `my_array[0]`. As for the last, I suspect `numba` has no indication that `my_array` is a structured array or that the `[v]` indexing step requires something different from an ordinary 2d column access.
comment on: http://stackoverflow.com/q/52409479
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52376115
score: -2
has title: django models error when inputting form data
has answer: http://stackoverflow.com/a/52376338
upvote count: 1
possible better answer: http://stackoverflow.com/a/52376485
favorite count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/91697095
tagged with: python
type: AnsweredQuestion
downvote count: 3
tagged with: django-forms
has answer: http://stackoverflow.com/a/52376485
type: Question
answer count: 2
has body: Full Traceback I am a beginner in django, and am having some trouble inputting form data to database. I am getting a `TypeError at /Info/ Info() got an unexpected keyword argument 'email'` when I feel I am doing it correctly Here is my models.py from django.db import models # Create your models here. class Info(models.Model): address = models.CharField(max_length=70) email = models.EmailField(max_length=32) My Views.py def Info(request): if request.method == 'POST': form = InfoForm(request.POST) if form.is_valid(): address = request.POST.get('address') email = request.POST.get('email') Facts = Info(email = email) Facts.save() else: form = InfoForm() return render(request, 'index/index.html', {'title': 'Info'}) def index(request): return render(request, 'index/index.html', {'title': 'Home'}) My Forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class InfoForm(forms.Form): address = forms.CharField() email = forms.EmailField() Thanks. Any help is appreciated.
accepted answer: http://stackoverflow.com/a/52376338

http://stackoverflow.com/q/52384271
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52384728
has comment: http://stackoverflow.com/comment/91725244
has comment: http://stackoverflow.com/comment/91785708
has comment: http://stackoverflow.com/comment/91786081
answer count: 2
has comment: http://stackoverflow.com/comment/91723438
downvote count: 0
possible better answer: http://stackoverflow.com/a/52384853
has comment: http://stackoverflow.com/comment/91723895
favorite count: 0
has answer: http://stackoverflow.com/a/52384853
has title: Django & Python : Format a FloatField in django form by adding separators
has answer: http://stackoverflow.com/a/52384728
has comment: http://stackoverflow.com/comment/91713655
tagged with: python
score: 2
upvote count: 2
has body: Well I dont know how to do this on django, so please help me do so. my float field is like : montant= forms.FloatField(initial="0",required = False) I want to show separators in my numbers to be lisible Example: when I write on the field the number is like : 1000000.00 what I need when writing on the field is I want the number looks like : 1 000 000.00 Any help please ? Thank You in advance
tagged with: django
tagged with: django-forms

http://stackoverflow.com/comment/92189796
comment on: http://stackoverflow.com/q/52428553
has text: @TasosGlrs I use the same function. You can see the accuracy graph in Tensorboard without any additional configuration? Which Tensorflow version?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91600331
type: QuestionComment
type: Comment
has text: thank you for the direction. I will post my query on the other portal. Plot show probabilities vs. frequency
score: 0
comment on: http://stackoverflow.com/q/52326469

http://stackoverflow.com/a/57484556
score: -4
has comment: http://stackoverflow.com/comment/117461831
has comment: http://stackoverflow.com/comment/101452803
upvote count: 4
downvote count: 8
answers question: http://stackoverflow.com/q/52346942
type: Answer
has comment: http://stackoverflow.com/comment/133620286
has body: Is such a thing possible? Yes, although it is not recommended. In my opinion, your best bet is to open and read your existing file, move it to an editable format, remove whatever text that you don't want present and then convert it back. However, you could extract the data and remove it from memory by using: import PyPDF2 # creating a pdf file object pdfFileObj = open('example.pdf', 'rb') # creating a pdf reader object pdfReader = PyPDF2.PdfFileReader(pdfFileObj) # printing number of pages in pdf file print(pdfReader.numPages) # creating a page object pageObj = pdfReader.getPage(0) # extracting text from page print(pageObj.extractText()) # closing the pdf file object pdfFileObj.close() Line by line, this program would: pdfFileObj = open('example.pdf', 'rb') Open the example.pdf and save the file object as pdfFileObj. pdfReader = PyPDF2.PdfFileReader(pdfFileObj) Create an object of PdfFileReader and pass the PDF file object whole getting a PDF reader object. print(pdfReader.numPages) Give the number of pages. pageObj = pdfReader.getPage(0) Create an object of PageObject class. PDF reader object has function getPage() which takes page number (starting form index 0) as an argument and returns the page object. print(pageObj.extractText()) Extract text from the PDF page. pdfFileObj.close() Close the PDF file object. The replacement text would simply be "", as you want to remove all instances / cases of a certain piece of text.

http://stackoverflow.com/q/52410410
tagged with: loops
tagged with: web-scraping
has answer: http://stackoverflow.com/a/52411586
has body: I am web scraping one website. When I scrape one URL, I write it to a dict. What I want to do is to write every dictionary to a json file. When I do the following loop, the file is saved as not a list, but as this structure {} {} that is not readable. df_price_m = {} with open(r"C:\Users\USER\Desktop\diploma\information.json", 'w', encoding='utf8') as fout: row = 0 for url in data: row +=1 driver.get(url) user_name_xpath = "//h1[@itemprop='name' and @data-shmid='profilePrepName']" user_name = get_elements(user_name_xpath) user_about_xpath = "//*[@class='desktop-profile-page__about-text']" user_about = get_elements(user_about_xpath) df_info['id'] = url df_info['user_name'] = user_name[0] df_info['user_about'] = user_about[0] json.dump(df_price_m, fout, ensure_ascii=False) I get the folowing json: {"id": "www.aina.com", user_name: "Aina Nurma", "user_about": "I am a student"} {"id": "www.aina.ru", user_name: "Aina Nur", "user_about": "I am a teacher"}
type: Question
tagged with: http://stackoverflow.com/tag/json
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
has title: Save every scraped element in a loop to a json file

http://stackoverflow.com/comment/91730358
type: Comment
has text: It doesn't. The while loop runs to completion, it modifies the variable `ans` and then the `if` statement checks the value of `ans` that resulted from running the while loop.
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52392605

http://stackoverflow.com/a/52316253
has comment: http://stackoverflow.com/comment/91580057
type: Answer
upvote count: 1
has body: This will do the work I guess. Please check and let me know. Thank you. import pandas as pd import matplotlib.pyplot as plt dict1 = { '400.0': [0.051198, 0.051198, 0.045406, 0.15855, 0.33586, 0.079011, 0.085342], '420.0': [0.046287, 0.046287, 0.0061685, 0.099437, 0.27868, 0.093667, 0.093032], '440.0': [0.046454, 0.046454, 0.0015765, 0.052886, 0.23238, 0.084899, 0.088889], '460.0': [0.041944, 0.041944, 0.0083426, 0.027038, 0.19666, 0.032842, 0.07963], '480.0': [0.025476, 0.025476, 0.021437, 0.02845, 0.16916, 0.066085, 0.11551], '500.0': [0.037221, 0.037221, 0.02546, 0.01049, 0.14636, 0.15647, 0.17047], '520.0': [0.020769, 0.020769, 0.057708, 0.013889, 0.11284, 0.17052, 0.15862], '540.0': [0.0029368, 0.0029368, 0.086186, 0.026225, 0.090237, 0.098873, 0.072785], '560.0': [0.0024553, 0.0024553, 0.1034, 0.057088, 0.077615, 0.048153, 0.037146], '580.0': [0.020523, 0.020523, 0.105, 0.076162, 0.067578, 0.047222, 0.062943], '600.0': [0.042838, 0.042838, 0.09883, 0.077351, 0.056873, 0.048235, 0.096264], '620.0': [0.05615, 0.05615, 0.096128, 0.073473, 0.046765, 0.031932, 0.10801], '640.0': [0.065999, 0.065999, 0.093658, 0.088445, 0.040698, 0.0082049, 0.095002], '660.0': [0.099263, 0.099263, 0.074047, 0.13282, 0.041967, 0.016028, 0.1117], '680.0': [0.14634, 0.14634, 0.028374, 0.19581, 0.071541, 0.036822, 0.14719], '700.0': [0.13285, 0.13285, 0.023217, 0.23739, 0.0053786, 0.059918, 0.17545]} df = pd.DataFrame(dict1) df.plot.density() plt.show()
score: 1
answers question: http://stackoverflow.com/q/52316072
downvote count: 0

http://stackoverflow.com/a/52355784
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/91663624
downvote count: 0
answers question: http://stackoverflow.com/q/52355668
type: Answer
has body: I recently answered similar question yesterday with a similar output. I am not sure if it was you who posted it again. Nevertheless, there were couple of errors in defining variable in your code. Following is the working version with the output. The modified/added lines are marked by a comment # repeat = 50 samplesize = 14 samplesize_list = [2, 5, 7] std_list = [10, 20, 30] mean_list = [1000, 2000, 3000] repeat_median = np.empty(repeat, dtype = float) for j in range(len(samplesize_list)): size = samplesize_list[j] for z in range(len(std_list)): std = std_list[z] # modified, you used the same name as variable for m in range(len(mean_list)): mean = mean_list[m] # modified, you used the same name as variable for i in range(repeat): sample_data = np.random.normal(mean, std, size) repeat_median[i] = np.median(sample_data) plt.subplot(len(samplesize_list), 1, j+1) sns.distplot(repeat_median, color = 'blue', label='Size %d'%samplesize_list[j]) # added legend plt.legend(loc = "upper right") plt.tight_layout() # added for better subplot adjustment Output A less verbose way of writing your code using list comprehensions for j, size in enumerate(samplesize_list): for z, std in enumerate(std_list): for m, mean in enumerate(mean_list): for i in range(repeat): sample_data = np.random.normal(mean, std, size) repeat_median[i] = np.median(sample_data)

http://stackoverflow.com/q/52378289
answer count: 0
tagged with: google-api
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91781517
has comment: http://stackoverflow.com/comment/91710421
tagged with: python
tagged with: dialogflow-es
tagged with: google-oauth
type: Question
has body: So my code works on console but if I try to import the module or run the code on the web I get google.api_core.exceptions.ServiceUnavailable: 503 Deadline Exceeded error. def detect_intent_texts(project_id, session_id, texts, language_code): """Returns the result of detect intent with texts as inputs. Using the same `session_id` between requests allows continuation of the conversaion.""" import dialogflow_v2 as dialogflow session_client = dialogflow.SessionsClient() session = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session)) for text in texts: text_input = dialogflow.types.TextInput( text=text, language_code=language_code) query_input = dialogflow.types.QueryInput(text=text_input) response = session_client.detect_intent( session=session, query_input=query_input) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print (detect_intent_texts('newagent-38239', '12121211', ['Hi there'], 'en-US')) I have the authentication setup and env variable GOOGLE_APPLICATION_CREDENTIALS setup. Like I said earlier the code works on the console or if I try to run the program like python main.py. If I try to import the module or run it on the web server it fails:
score: 0
has title: Dialogflow v2 api fails on authentication in Python
has comment: http://stackoverflow.com/comment/91736362

http://stackoverflow.com/comment/91800118
has text: How do you see that it does not return? Are you using a debugger or is it that yu expect an action that does not happen. I doubt the program gets stuck at a `return` statement. It is more likely somewhere in the framework in such a case.
comment on: http://stackoverflow.com/q/52423018
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52295301
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/106941409
has body: I've got a 360 million record dataframe of bird sighting data and I'd like to compute the centroid of each bird species as a function of yearday using dask in a distributed way. I would like to do: df2 = df.groupby(['VERNACULARNAME', 'yearday']).mean() but I need to first compute yearday, and I can't figure out if there is a way to do this on the fly with dask. I was hoping that dask might just persist the new data to the dask workers, but when I try: def yearday(r): r['yearday'] = dt.datetime(r['YEAR'], r['MONTH'], r['DAY']).timetuple().tm_yday return r df.apply(yearday, axis=1).persist() it does not scale. If someone wants to actually try, the data can be loaded like this: import dask.dataframe as dd df = dd.read_parquet('s3://esipfed/ebird/EOD_CLO_2016.parq.gz', storage_options={'anon': True, 'use_ssl': False}) Note: Although I called this dataset EOD_CLO_2016.parq.gz, it is chunked over many objects in the S3 bucket to facilitate parallelization. Each chunk is gzipped. Is there any way to do this compuation on the fly in a distributed way or do I need to write another data file with the yearday column before I use groupby to do the scalable part?
has comment: http://stackoverflow.com/comment/91542756
has comment: http://stackoverflow.com/comment/91544673
has comment: http://stackoverflow.com/comment/91539196
has title: Parallel computation with dask when dataframe column needs to be computed
type: Question
has comment: http://stackoverflow.com/comment/91539419
has comment: http://stackoverflow.com/comment/91545424
tagged with: fastparquet
has comment: http://stackoverflow.com/comment/91547199
has answer: http://stackoverflow.com/a/52303939
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91547372
tagged with: dask
accepted answer: http://stackoverflow.com/a/52303939
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/91578013
comment on: http://stackoverflow.com/q/52314931
score: 0
type: Comment
has text: In SO you should not publish the same question several times, do not you think that it will bore us ?, If you want your question to be attractive and therefore we are interested in helping you, there are many ways to do it, such as showing what you have done, and showing the message of error, etc. Do not post the same question several times. read [ask] and review the [tour]
type: QuestionComment

http://stackoverflow.com/comment/91790319
type: AnswerComment
comment on: http://stackoverflow.com/a/52418130
type: Comment
has text: Both of these options worked - thank you so much. Will be reading up on .swaplevel()
score: 1

http://stackoverflow.com/comment/91534691
has text: Possible duplicate of [What is the fastest/most efficient way to loop through a large collection of files and save a plot of the data?](https://stackoverflow.com/questions/23572714/what-is-the-fastest-most-efficient-way-to-loop-through-a-large-collection-of-fil)
type: QuestionComment
comment on: http://stackoverflow.com/q/52279699
type: Comment
score: 0

http://stackoverflow.com/a/52294645
score: 14
has comment: http://stackoverflow.com/comment/91541859
upvote count: 14
has body: custom_settings is supposed to be a class attribute: class IndexSpider(scrapy.Spider): name = "indices" # set custom settings custom_settings = { 'DOWNLOAD_DELAY': 2, 'ITEM_PIPELINES': { 'freedom.pipelines.IndexPipeline': 300 } } def __init__(self, *args, **kwargs): super(IndexSpider, self).__init__(*args, **kwargs)
accepted answer of: http://stackoverflow.com/q/52294394
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52294394
type: Answer

http://stackoverflow.com/q/52324657
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52324946
accepted answer: http://stackoverflow.com/a/52324946
has title: Conditional search in future rows within groupby in pandas
tagged with: dataframe
has body: Following is the dataframe I have. The 'Target' column is the desired output. Group Item Value Target 1 0 5 0 1 1 4 0 1 0 6 0 1 0 3 1 1 1 2 0 1 0 1 1 2 1 8 0 2 0 9 0 2 0 7 1 In a given Group, if Item == 1, then I am trying to find the first future/next row where the Value is less than the corresponding Value for Item == 1. For example, in the second row, the Item == 1 and the corresponding Value is 4. The first future row where Value is less than 4 is the 4th row which has a Value of 3. Thereby, Target column specifies the find with a 1. It could be possible where two Item==1 has the same future row where conditions satisfy. In that case, we can also have a 1 in Target. import pandas as pd df = pd.DataFrame({'Group1': [1,1,1,1,1,1,2,2,2], 'Item': [0,1,0,0,1,0,1,0,0], 'Value': [5,4,6,3,2,1,8,9,7]}) df['next_Value'] = df.groupby(['Group'])['Value'].shift(-1)
type: Question
tagged with: numpy
answer count: 1
score: 0
tagged with: pandas
tagged with: python

http://stackoverflow.com/q/52325498
tagged with: python
type: AnsweredQuestion
has body: I want to encapsulate my uncicode variable in quotes. q = u'turtle' print(q) prints turtle The goal is to encapsulate turtle inside the unicode type with quotes so it looks like this q = u'"turtle"' or prints as "turtle" but still retain its unicode type. How do i go about inserting that?
downvote count: 2
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52325689
has title: Encapsulating unicode string with quotes
score: -1
tagged with: python-2.7
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52325689

http://stackoverflow.com/comment/91734195
comment on: http://stackoverflow.com/a/52393830
type: AnswerComment
type: Comment
score: 7
has text: Incredible effort, +1 for sure. Sure are a lot of Chris’ in here :)

http://stackoverflow.com/comment/91732537
score: 0
type: Comment
type: QuestionComment
has text: @Metropolis: Think I got it upon reading it again. Thank you. I realize the the premisconception I had was that once it checked in the while loop that 2**3 is not 4, as you said in your example, it dumped 2 from its memory. Thanks a lot.
comment on: http://stackoverflow.com/q/52392605

http://stackoverflow.com/a/52393953
answers question: http://stackoverflow.com/q/52393787
score: 1
has comment: http://stackoverflow.com/comment/91733712
upvote count: 1
type: AcceptedAnswer
has body: Use groupby.agg with a dictionary of aggregation functions for each column. import pandas as pd d = {'product': pd.Series.nunique, 'country': lambda x: 5 if (x=='World').any() else 1} df.groupby('name').agg(d).reset_index() Output: name product country 0 A 2 1 1 B 1 5
has comment: http://stackoverflow.com/comment/91734143
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52393787

http://stackoverflow.com/comment/91583243
score: 1
has text: The Arduino does `Serial.readStringUntil("\n")` - but you are never writing a newline from the Python side, the only way that statement can complete is due to a timeout.
comment on: http://stackoverflow.com/q/52317731
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52321165
has comment: http://stackoverflow.com/comment/91590425
has comment: http://stackoverflow.com/comment/91590524
upvote count: 4
has comment: http://stackoverflow.com/comment/91590052
score: 4
answers question: http://stackoverflow.com/q/52321121
has body: filter may intuitively feel like the right function, but you almost certainly should use loc to filter your data (on your examples link above, it says "See also: loc" in a big yellow box). For this simple example, you could also use boolean indexing: &gt;&gt;&gt; df1.loc[df1['PHASE'] == 'F'] # or boolean indexing via df1[df1['PHASE'] == 'F'] landuse_SUB_ID TYPE RECD_DATE PHASE LAND_USE CPACTIONDA 3 34 1 2000-04-14 F REC 2000-04-14 4 34 1 2000-04-14 F SFD 2000-04-14 10 53 1 2000-02-22 F SFD 2000-02-22
has comment: http://stackoverflow.com/comment/91591929
has comment: http://stackoverflow.com/comment/91590757
downvote count: 0
has comment: http://stackoverflow.com/comment/91590713
has comment: http://stackoverflow.com/comment/91590189
type: Answer
has comment: http://stackoverflow.com/comment/91590862

http://stackoverflow.com/comment/91629933
has text: yes @travishaycock, just use lambda function and by iterating with the value and give your specific ans,
comment on: http://stackoverflow.com/a/52341440
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/52396923
type: Question
has body: I'm developing a calculator program in Python, and need to remove leading zeros from numbers so that calculations work as expected. For example, if the user enters "02+03" into the calculator, the result should return 5. In order to remove these leading zeroes in-front of digits, I asked a question on here and got the following answer. self.answer = eval(re.sub(r"((?&lt;=^)|(?&lt;=[^\.\d]))0+(\d+)", r"\1\2", self.equation.get())) I fully understand how the positive lookbehind to the beginning of the string and lookbehind to the non digit, non period character works. What I'm confused about is where in this regex code can I find the replacement for the matched patterns? I found this online when researching regex expressions. result = re.sub(pattern, repl, string, count=0, flags=0) Where is the "repl" in the regex code above? If possible, could somebody please help to explain what the r"\1\2" is used for in this regex also? Thanks for your help! :)
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/52397131
accepted answer: http://stackoverflow.com/a/52397128
has comment: http://stackoverflow.com/comment/91738804
favorite count: 0
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/52397128
has title: Need a specific explanation of part of a regex code
type: AnsweredQuestion
tagged with: tkinter
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/52397131
has answer: http://stackoverflow.com/a/52396961

http://stackoverflow.com/a/52427071
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/52427024
has body: Use groupby with size and reshape by unstack, last add_prefix: df = df.groupby(['term','score']).size().unstack(fill_value=0).add_prefix('score ') Or use crosstab: df = pd.crosstab(df['term'],df['score']).add_prefix('score ') Or pivot_table: df = (df.pivot_table(index='term',columns='score', aggfunc='size', fill_value=0) .add_prefix('score ')) print (df) score score 0 score 1 score 2 score 3 term anything 0 1 0 0 something 0 1 1 0 that 0 1 1 0 the other 0 0 1 1 this 2 0 0 0
has comment: http://stackoverflow.com/comment/91797450
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91799430
has comment: http://stackoverflow.com/comment/91903970
accepted answer of: http://stackoverflow.com/q/52427024
type: Answer
has comment: http://stackoverflow.com/comment/91903614
has comment: http://stackoverflow.com/comment/91903586

http://stackoverflow.com/comment/91593267
score: 0
type: AnswerComment
has text: Yes, *retaining an XML's structure while deleting its contents is not an unreasonable ask*, but you don't have XML. You have "XML," and that makes all the difference in the world: "XML" cannot be parsed because "XML" adheres to no standards or rules. This is my last comment. Good luck.
type: Comment
comment on: http://stackoverflow.com/a/52317039

http://stackoverflow.com/q/52329793
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52329983
type: Question
tagged with: python
tagged with: http://stackoverflow.com/tag/zip
score: 0
answer count: 1
has title: Getting an Error while encountering a non Zip file
has body: I wanted to get the comment data of Zip files from an entire folder, but when ever it encounters any other file besides a Zip file it gives me an error: Traceback (most recent call last): File "C:\Users\user\Desktop\New folder\ec5.py", line 11, in with ZipFile(zfile, 'r') as testzip: File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\zipfile.py", line 1200, in init self._RealGetContents() File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\zipfile.py", line 1267, in _RealGetContents raise BadZipFile("File is not a zip file") zipfile.BadZipFile: File is not a zip file Is it possible to fix it useing anything along the lines of: try: exception This is the code: import os import unicodedata from zipfile import ZipFile rootFolder = u"C:/Users/user/Desktop/archives/" zipfiles = [os.path.join(rootFolder, f) for f in os.listdir(rootFolder)] for zfile in zipfiles: print("Opening: {}".format(zfile)) with ZipFile(zfile, 'r') as testzip: print(testzip.comment) # comment for entire zip l = testzip.infolist() #list all files in archive for finfo in l: # per file/directory comments print("{}:{}".format(finfo.filename, finfo.comment))
has answer: http://stackoverflow.com/a/52329983

http://stackoverflow.com/a/52396235
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52325100
downvote count: 0
has body: I was able to get output in csv . It took some time though @api.representation('text/csv') def data_csv(data, code, headers): '''Get result in csv ''' resp = make_response(convert_data(data), code) resp.headers.extend(headers) return resp
upvote count: 2

import
type: Tag
tags question: http://stackoverflow.com/q/52277705
tags question: http://stackoverflow.com/q/52355523
tags question: http://stackoverflow.com/q/52370677
tags question: http://stackoverflow.com/q/52364721
tags question: http://stackoverflow.com/q/52417661
tags question: http://stackoverflow.com/q/52277772
tag name: import
tags question: http://stackoverflow.com/q/52319008
tags question: http://stackoverflow.com/q/52342513
tags question: http://stackoverflow.com/q/52335995

http://stackoverflow.com/comment/91535488
comment on: http://stackoverflow.com/a/52284520
score: 0
type: AnswerComment
has text: Thank you so much, this helped for the image part. But what about the audio and text files? can they be accessed the same way?
type: Comment

http://stackoverflow.com/q/52279133
type: Question
has comment: http://stackoverflow.com/comment/91506401
has body: How do I copy cells from one excel file and append it at the end of another file which already has data using python using xlrd. I am able to load the files and read the contents of the cell but i want to copy the cell values from a file (say A.xlsx) and append the values in another excel file (say B.xlsx) which already has data. I would like to append the data at the end of the current data in file B.xlsx import os import xlrd def openxlfile(): workbook = xlrd.open_workbook(filename = "C:\\A\\A.xlsx") workbook = xlrd.open_workbook(filename = "C:\\B\\B.xlsx") worksheet = workbook.sheet_by_index(0) print(worksheet.cell_value(3,8)) openxlfile()
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91506302
has comment: http://stackoverflow.com/comment/125638274
tagged with: python
has comment: http://stackoverflow.com/comment/91506763
has title: How to copy cells from one excel file and append it at the end of another file which already has data using python
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/91506674
upvote count: 1
tagged with: excel

http://stackoverflow.com/a/52356689
score: 2
has comment: http://stackoverflow.com/comment/91658761
has body: See argsort: df['Order'] = df['Frequency'].argsort() + 1 df returns Category Frequency Order 0 a 5 3 1 b 10 1 2 c 2 2
downvote count: 0
answers question: http://stackoverflow.com/q/52356567
has comment: http://stackoverflow.com/comment/91658724
upvote count: 2
type: Answer

http://stackoverflow.com/comment/91700017
has text: @CPerkins The error message is a translation (as it's Korean). Sorry for all the confusion but please look at the error code.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52364695
type: QuestionComment

http://stackoverflow.com/comment/91619188
score: 0
has text: @KevinNgo It's not a dumb question; hindsight is brilliant :) I was curious why you thought you needed it a second time - indentation is important and you were already in a context block from the first `with`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52335559

http://stackoverflow.com/comment/106794219
type: Comment
comment on: http://stackoverflow.com/a/52352077
has text: That would be a negative. This is not a S/MIME-case. It's a simple case of trying to extract X.509 out of PKCS#7-file.
score: 0
type: AnswerComment

localization
tags question: http://stackoverflow.com/q/52370844
type: Tag
tags question: http://stackoverflow.com/q/52373931
tag name: localization

http://stackoverflow.com/q/52379582
tagged with: selenium
upvote count: 1
possible better answer: http://stackoverflow.com/a/52379724
has comment: http://stackoverflow.com/comment/91703598
accepted answer: http://stackoverflow.com/a/52379672
downvote count: 1
type: Question
has body: There is a question bothering me for a long time. I'm studying in web element locating and control/read text from a web page. I've to try to commend blow and fine element success but return empty. driver.find_element(By.XPATH, '//table[1]//tr[2]//td[1]').text I want to read text the blue line text in the PIC, but I don't know why to get empty data every time.
has comment: http://stackoverflow.com/comment/91703599
answer count: 2
favorite count: 0
has answer: http://stackoverflow.com/a/52379672
tagged with: element
has title: Can't fine element text with XPath
has comment: http://stackoverflow.com/comment/91703824
tagged with: python
has answer: http://stackoverflow.com/a/52379724
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/52303249
type: Question
has body: Is there a way to point pytest at a differnt pytest.ini file? The application I am working on has one pytest.ini file that is used for running unittests when it spins up, and I do not want to modify that file. I do however want to point pytest at a different file when running my automation tests via pytest.main() pytest.main(['-p', 'no:django', '-v', '--json-report', '-m', test_marker]) Is there a way to tell pytest to use a pytest.ini file from another location?
accepted answer: http://stackoverflow.com/a/52313467
tagged with: pytest
has title: force pytest.main() to use a different pytest.ini
upvote count: 4
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52313467
tagged with: python
has comment: http://stackoverflow.com/comment/91589935
type: AnsweredQuestion
score: 4

http://stackoverflow.com/q/52346725
type: Question
has title: Can I add outlier detection and removal to Scikit learn Pipeline?
has body: I want to create a Pipeline in Scikit-Learn with a specific step being outlier detection and removal, allowing the transformed data to be passed to other transformers and estimator. I have searched SE but can't find this answer anywhere. Is this possible?
tagged with: python
accepted answer: http://stackoverflow.com/a/52346726
answer count: 1
has comment: http://stackoverflow.com/comment/91673572
downvote count: 1
upvote count: 17
score: 16
has comment: http://stackoverflow.com/comment/91673963
has comment: http://stackoverflow.com/comment/91674132
has answer: http://stackoverflow.com/a/52346726
has comment: http://stackoverflow.com/comment/91674199
has comment: http://stackoverflow.com/comment/91674043
type: AnsweredQuestion
tagged with: scikit-learn
favorite count: 0
has comment: http://stackoverflow.com/comment/91674167

http://stackoverflow.com/a/52287419
has body: The function to delete keys doesn't seem right. Apart from that I have tried to make minimal changes to your code. from functools import reduce import json def delete_nested(dictionary, paths): """ Delete the keys specified as path in paths from dictionary. """ for path in paths: parent_path, last_key = path[:-1], path[-1] parent = reduce(dict.get, parent_path, dictionary) if(parent==None): sys.exit("The path {path} is invalid".format(path=path)) if(not(isinstance(parent, dict))): sys.exit("The path {path} doesn't contain a dict".format(path=parent_path)) del parent[last_key] def equal(d1, d2, ignore_keys=[]): """ Check if d1 and d2 are equal less the ignore_keys """ d1_, d2_ = d1.copy(), d2.copy() delete_nested(d1_, ignore_keys) delete_nested(d2_, ignore_keys) return d1_ == d2_ Example execution: d1 = json.loads("""{ "A": "123456789", "B": { "firstElement": "abc", "lastElement": "def" }, "C": { "firstElement": "chi", "lastElement": "jul" } }""") d2 = json.loads("""{ "C": { "firstElement": "chi", "lastElement": "jul" }, "A": "78901234", "B": { "firstElement": "abc", "lastElement": "e" } }""") print(equal(d1, d2, ["A",["B","lastElement"]])) # prints True
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52287067
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52287067
type: Answer

http://stackoverflow.com/q/52356607
tagged with: list
has comment: http://stackoverflow.com/comment/91657726
has comment: http://stackoverflow.com/comment/91658093
has body: I created a dictionary with a for loop. Now i want to add the index values of the words in a list to this dictionary. So the value of num in enumerate(olist) has to be added to the corresponding word in the dictionary. Code: def reverse_dict(input): output = collections.defaultdict(list) for key, val in input.items(): for item in val: output[item].append(key) return output def main(): olist = [] worddict = {} for line in sys.stdin: i,u,t,w = line.split('\t') splitword = (w.split()) olist.extend(splitword) worddict[i] = splitword for num,name in enumerate(olist): #splitword.extend([num]) #worddict[i].extend([num]) print("{} [{}]".format(name.strip(), num)) output = reverse_dict(worddict) print(output) Current output1: RT [0] @AfshinEllian1 [1] : [2] Kennelijk [3] vinden [4] ze [5] daar [6] etc.. Current output2 : {'RT': ['1035421930541772800', '1035421931321864192'], '@AfshinEllian1': ['1035421930541772800'], ':': ['1035421930541772800', '1035421931321864192'], 'Kennelijk': ['1035421930541772800'], 'vinden': ['1035421930541772800'], 'ze': ['1035421930541772800'], 'daar': ['1035421930541772800'], 'aan': ['1035421930541772800'], 'die': ['1035421930541772800'], 'gezellige': ['1035421930541772800'], 'tafel': ['1035421930541772800'], 'normaal': ['1035421930541772800'], 'dat': ['1035421930541772800'], 'steltje': ['1035421930541772800'], 'barbaren': ['1035421930541772800'], 'onze': ['1035421930541772800'], 'grondwettelijke': ['1035421930541772800'], 'rechten': ['1035421930541772800'], 'bedreigen': ['1035421930541772800'], '.': ['1035421930541772800'], 'Zouden': ['1035421930541772800'], 'we': ['1035421930541772800'], 'ook': ['1035421930541772800'] Expected output : {'RT': ['1035421930541772800', '1035421931321864192', '0'], '@AfshinEllian1': ['1035421930541772800', '1']
has answer: http://stackoverflow.com/a/52356816
accepted answer: http://stackoverflow.com/a/52356816
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/91657761
score: 0
has title: Appending new value to existing (reverse) dictionary in other for loop
tagged with: python
tagged with: merge
tagged with: dictionary
type: AnsweredQuestion

http://stackoverflow.com/q/52307730
tagged with: character-encoding
accepted answer: http://stackoverflow.com/a/52308708
type: Question
answer count: 2
has title: Opening a text file, and receiving a encoding error, tried multiple methods no hope
downvote count: 0
has comment: http://stackoverflow.com/comment/91564467
has body: I'm trying to open up a password database file (consists of a bunch of common passwords) and I'm getting the following error: Attempts so far.. Code: f = open("crackstation-human-only.txt", 'r') for i in f: print(i) Error Code: Traceback (most recent call last): File "C:\Users\David\eclipse-workspace\Kaplin\password_cracker.py", line 3, in &lt;module&gt; for i in f: File "C:\Users\David\AppData\Local\Programs\Python\Python37\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 753: character maps to &lt;undefined&gt; After doing some research I was told to attempt encoding = 'utf-8' which I later discovered was basically guessing and hoping that the file would show all the outputs Code: f = open("crackstation-human-only.txt", 'r', encoding = 'utf-8') for i in f: print(i) Error: Traceback (most recent call last): File "C:\Users\David\eclipse-workspace\Kaplin\password_cracker.py", line 3, in &lt;module&gt; for i in f: File "C:\Users\David\AppData\Local\Programs\Python\Python37\lib\codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe4 in position 5884: invalid continuation byte After receiving this error message, I was recommended to attempt to download a text editor like 'Sublime Text 3', and to open the console end enter the command 'Encoding()', but unfortunately it wasn't able to detect the encoding. My professor was able to use bash to 'grep cat' the lines in the file (I honestly know very little about bash so if anyone else knows those terms i'm not sure if that will help them out) If anyone has any suggestions on what I can do in order to get this to work out I would greatly appreciate it. I will post the link to the text document if anyone is interested in seeing what types of characters are within the file. Link to the file, it's a .…
has comment: http://stackoverflow.com/comment/91562849
tagged with: python
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52307988
has comment: http://stackoverflow.com/comment/91563620
upvote count: 1
possible better answer: http://stackoverflow.com/a/52307988
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52308708
score: 1
has comment: http://stackoverflow.com/comment/91562744

http://stackoverflow.com/comment/91627505
has text: can you ditch your IDE and run this as a Python script and post a new imgur link? It's an interesting question.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52340088

cryptography
tag name: cryptography
tags question: http://stackoverflow.com/q/52313499
type: Tag
tags question: http://stackoverflow.com/q/52386059
tags question: http://stackoverflow.com/q/52343418

http://stackoverflow.com/q/52393979
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52402392
downvote count: 0
answer count: 1
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/52402392
favorite count: 0
tagged with: python-3.x
tagged with: python
has body: I am trying to apply kNN classifer with squared inverse weights using sklearn.neighbors.KNeighborsClassifier package. According to the documentation we can define a function for the weights. I defined the follwing function to obtain the squareed inverse of the distances as the weights: import numpy as np def isd(): w= [] for i in range(len(x_train)): # first we compute the euclidean distance distance = np.sqrt(np.sum(np.square(x_test x_train[i,:]))) # add it to list of distances w.append([1/(np.square(distance)), i]) return w and then I used the KNeighborsClassifier as follow: neighbors = list(range(1,11)) #making an empty vector to store accuracy scores ac_scores3= [] # fitting the model for K in neighbors: K_value = K+1 knn3= KNeighborsClassifier(K_value,weights=isd()) knn3.fit(x_train,y_train.values.ravel()) y_pred3=knn3.predict(x_test) ac_scores3.append(accuracy_score(y_test,y_pred3)) # finding test error by subtracting ac from 1 TE3 = [1 - x for x in ac_scores3] I am getting the following error: ValueError: weights not recognized: should be 'uniform', 'distance', or a callable function by the way I am using usps data set, Any help would be greatly appreciated?
has title: Knn Classifier with squared iverse weights in python( weight is a callable function)
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/52426885
has body: I have created an Artificial Neural Network with 4 features. I am at the point where I want to test the model with a live sample of a malicious file path/exe using: new_prediction = classifier.predict(sc.transform(np.array([[]]))) I know that if I use the same File path like "C:\Program Files (x86\Wireless AutoSwitch" I could use "0" and so on for each of the categorical features that have already gone through onehot and label encoding. How do you deal with a new categorical feature that is not in the array of the training set? Lets say the new feature that I want to test is: ParentPath ParentExe ChildPath ChildExe 0 C:\Windows\Malicious badscipt.exe C:\Windows\System cmd.exe This training dataset looks like the following: ParentPath ParentExe 0 C:\Program Files (x86)\Wireless AutoSwitch wrlssw.exe 1 C:\Program Files (x86)\Wireless AutoSwitch WrlsAutoSW.exs 2 C:\Program Files (x86)\Wireless AutoSwitch WrlsAutoSW.exs 3 C:\Windows\System32 svchost.exe 4 C:\Program Files (x86)\Wireless AutoSwitch WrlsAutoSW.exs ChildPath ChildExe C:\Windows\System32 conhost.exe C:\Program Files (x86)\Wireless AutoSwitch wrlssw.exe C:\Program Files (x86)\Wireless AutoSwitch wrlssw.exe C:\Program Files\Common Files OfficeC2RClient.exe C:\Program Files (x86)\Wireless AutoSwitch wrlssw.exe C:\Program Files (x86)\Wireless AutoSwitch wrlssw.exe The code: #Libraries import pandas as pd import numpy as np import hashlib import matplotlib.pyplot as plt import timeit #################### GOOD ################### #Read in csv to df DF = pd.read_csv('/home/gpubetterwork/Documents/Good-Merged-TAGS_8-23- 2018_060000-95959_TAG_Parent_Child.csv') #Select 2 columns DF1 = DF'filePath', 'destinationProcessName' #Rename columns DF1.columns = ['ParentPathExe', 'ChildPathExe'] #Replace all NaN with Unknown DF1['ParentPathExe'] = DF1['ParentPathExe'].replace(np.nan, 'UNKNOWN') DF1['ChildPathExe'] = DF1['ChildPathExe'].replace(np.nan, 'UNKNOWN') #Split ParentPathExe into path and exe columns DParent = DF1…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52786891
type: Question
tagged with: numpy
answer count: 1
tagged with: neural-network
tagged with: keras
score: 0
accepted answer: http://stackoverflow.com/a/52786891
tagged with: python
has title: Python - Having issues with selecting new prediction using new categorical variables for numpy array

http://stackoverflow.com/a/52388713
has body: example is replaced with wrapper; the decoration is equivalent to def example(self, examplearg=1): """Docstring""" pass example = my_decorator(example) so you need to set wrapper.__doc__, not func.__doc__. def my_decorator(func): def wrapper(self, *args, **kwargs): return func(self, *args, **kwargs) wrapper.__doc__ = "{} is new for the function {}".format( str(func.__doc__), func.__name__) return wrapper Note that at the time you call my_decorator, you don't have any information about what class the decorated function/method belongs to. You would have to pass its name explicitly: def my_decorator(cls_name): def _decorator(func): def wrapper(self, *args, **kwargs): return func(self, *args, **kwargs) wrapper.__doc__ = "{} is new for function {} in class {}".format( func.__doc__, func.__name__, cls_name) return wrapper return _decorator class Test(): @my_decorator("Test") def example(self, examplearg=1): """Docstring""" # or # def example(self, examplearg=1): # """Docstring""" # # example = my_decorator("Test")(example)
downvote count: 0
score: 2
has comment: http://stackoverflow.com/comment/91722585
has comment: http://stackoverflow.com/comment/91723894
upvote count: 2
answers question: http://stackoverflow.com/q/52388654
has comment: http://stackoverflow.com/comment/91723360
type: Answer

http://stackoverflow.com/q/52285345
has answer: http://stackoverflow.com/a/52307339
favorite count: 0
tagged with: python
type: AnsweredQuestion
has title: Mocking Class Functions
accepted answer: http://stackoverflow.com/a/52285432
possible better answer: http://stackoverflow.com/a/52307339
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52285432
tagged with: python-unittest
score: -1
has body: I'm trying to unittest a class which has a decently complicated __init__, one involving calls to servers and external components. I found that you can use the unittest MagicMock to fake an init. class my_class: def __init__(self, arg1, arg2): self.var = arg1 self.method1(arg2) def method1(self, arg): var = "Hello " + arg self.method2(var) def method2(self, var): print(var) SELF = MagicMock() my_calss.my_class.__init__(SELF, arg1, arg2) Which is awesome cause all the code which talks with a server is in other methods and I can make sure that the __init__ calls certain methods. The problem comes when I want test a method which calls another method. SELF = MagicMock() my_class.__init__(SELF, arg1, arg2) SELF.method2 = my_class.method2 my_class.method1(SELF, arg) I'd expect the self in method2 to be SELF but method2 never gets a self. Is there a way of insuring that method2 gets the mocked SELF? Or another method of testing class methods that doesn't involve a ton of patches?
answer count: 2
tagged with: mocking
upvote count: 0

http://stackoverflow.com/comment/91771307
comment on: http://stackoverflow.com/a/52413281
has text: it's because there's nothing to train. `a` and `b` are trainable but don't contribute to cost_function, and also `values_array` is untrainable. If you want to test it anyway, comment out `# _ = sess.run([optimizer])`
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91667913
comment on: http://stackoverflow.com/q/52361130
has text: @DimitrisKougioumtzis I have Added This on header Section of Postman . Still Shows This same error
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91520167
comment on: http://stackoverflow.com/q/52285839
score: 3
has text: It's saying you *should* use them - not that you *are* using them :)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52394754
has comment: http://stackoverflow.com/comment/91735961
downvote count: 1
answers question: http://stackoverflow.com/q/52394413
score: -1
upvote count: 0
has body: Nope, you need to set GOOGLE_APPLICATION_CREDENTIALS with a path to the JSON file instead. See https://cloud.google.com/docs/authentication/getting-started for more details.
type: Answer

http://stackoverflow.com/comment/91746258
comment on: http://stackoverflow.com/q/52400957
score: 0
has text: @mkrieger1 I have read the doc, you are quoting and actually my question was inspired by exactly this remark. Yes, I can look into sources and, but I thought maybe someone already knows the answer without looking into the code.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91686398
comment on: http://stackoverflow.com/q/52357417
type: Comment
type: QuestionComment
has text: i am able to change like this window.location="http://localhost:5000/chat" but no idea what wrong with this.
score: 0

http://stackoverflow.com/comment/91687918
has text: I meant, the output we are getting in list 'rept'. It further has duplication ('name' and 'weight' both of them twice). If I need to break it down to the list of just 'name' and 'weight' or break it down till the time there are lists of just one type of elements in it.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52370516

http://stackoverflow.com/q/52324480
has comment: http://stackoverflow.com/comment/91596133
favorite count: 0
tagged with: class
answer count: 3
has title: The data in my list is being overwritten by the new data that is being entered
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
downvote count: 1
tagged with: enums
tagged with: oop
score: -1
type: Question
has answer: http://stackoverflow.com/a/52324960
has answer: http://stackoverflow.com/a/52324651
upvote count: 0
has answer: http://stackoverflow.com/a/52324656
has body: Hey I'm new to Python just trying to learn and enhance my programming skills and I can't seem to understand why my output of the list is printing out wrong. It should print out: "Property Type: House" and "Purchase Type: purchase". Right after it should print out "Property Type: Apt" and "Purchase Type: rental" but it prints the the Apt and rental twice and ignores the first pair of info that was added. Can't seem to understand why it does that. If anyone can help, I would appreciate it. class Agent: def __init__(self): self.properties = [] def add_new_property(self, property_type, purchase_type): self.prop_type = property_type self.pur_type = purchase_type self.properties.append(self) def print_properties(self): for property in self.properties: print("Property Type: " + property.prop_type) print("Purchase Type: " + property.pur_type) a = Agent() a.add_new_property("house", "purchase") a.add_new_property("apt", "rental") a.print_properties()

http://stackoverflow.com/q/52417697
has comment: http://stackoverflow.com/comment/91778685
type: Question
score: 1
has comment: http://stackoverflow.com/comment/91778626
has comment: http://stackoverflow.com/comment/91778527
has comment: http://stackoverflow.com/comment/91779140
has comment: http://stackoverflow.com/comment/91778962
has comment: http://stackoverflow.com/comment/91784297
has comment: http://stackoverflow.com/comment/91779087
downvote count: 0
has comment: http://stackoverflow.com/comment/91779004
answer count: 1
has title: Serving mixed filenames with send_from_directory() errors out
has body: In an html form i have a user selecting a filename, which then i tried to send to his browser. Here is the code: filename = request.form.get('filename') filepath = '/home/nikos/wsgi/static/files/' return send_from_directory(filepath, filename) If the filename selected is in english characters it gets send the user, but, if it contained a mix of english + greek chars it gives a bad request i tried to encode `filename.encode("utf-8") but then NO files are being served.
favorite count: 0
has comment: http://stackoverflow.com/comment/91778933
has comment: http://stackoverflow.com/comment/91778485
tagged with: python
has comment: http://stackoverflow.com/comment/91778749
has comment: http://stackoverflow.com/comment/91778824
has comment: http://stackoverflow.com/comment/91779648
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/52421893

http://stackoverflow.com/comment/91765240
type: Comment
comment on: http://stackoverflow.com/q/52410714
has text: @Wen that's bad advice, it's open to SQL injection. You shouldn't use string interpolation for the whole query, `%s` here is a placeholder
score: 4
type: QuestionComment

http://stackoverflow.com/a/52411829
score: 16
upvote count: 16
has body: Here's a short but complete demo of your code using a ByteIO instead of StringIO. I've also added a function to do the reverse conversion. It runs correctly on Python 2.6 and 3.6. The only difference is that in Python 3 the Base64 output is a b string. from PIL import Image from io import BytesIO import base64 # Convert Image to Base64 def im_2_b64(image): buff = BytesIO() image.save(buff, format="JPEG") img_str = base64.b64encode(buff.getvalue()) return img_str # Convert Base64 to Image def b64_2_img(data): buff = BytesIO(base64.b64decode(data)) return Image.open(buff) # Test img = Image.new('RGB', (120, 90), 'red') img.show() img_b64 = im_2_b64(img) print(img_b64) new_img = b64_2_img(img_b64) new_img.show() Python 3 output b'[binary]'
answers question: http://stackoverflow.com/q/52411503
downvote count: 0
has comment: http://stackoverflow.com/comment/128693315
type: Answer

http://stackoverflow.com/q/52372760
has comment: http://stackoverflow.com/comment/91695877
tagged with: python
has comment: http://stackoverflow.com/comment/91691346
downvote count: 0
type: UnansweredQuestion
score: 1
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/91690539
type: Question
has comment: http://stackoverflow.com/comment/91690866
has title: Download latest version of file from website to specific location using Python
has comment: http://stackoverflow.com/comment/91693811
has answer: http://stackoverflow.com/a/52383500
has body: I am learning selenium and web-scraping in Python (V3.6.6, x64 version). I am trying to write a script that will, when executed, automatically download latest available win64 version of geckodriver (v0.22.0, at the time of posting this question) from the url https://github.com/mozilla/geckodriver/releases to a specific location on my windows PC. My problem is, when I look at the page source using Mozilla Firefox browser, the id and the class for the specific version I am trying to download is the same as all the other available versions. I am not able to filter out the specific section and get the href so that the file can be downloaded. I am surely missing something but inspite of several internet searches, I am not able to figure out what I am doing wrong. I request the experts in Stackoverflow to guide/correct me on the next steps. Below are the things I am trying to solve: 1) Download win64 version of latest geckodriver 2) File should be downloaded to C:\Python 3) How to understand program has downloaded file completely so that it can execute further? from urllib.request import urlopen, urlretrieve from bs4 import BeautifulSoup # Define page where geckodriver can be downloaded url = "https://github.com/mozilla/geckodriver/releases" try: # Query the website and return the html to the variable ‘page’ page = urlopen(url) except: # Thow message for any unexpected behaviour when loading page print("Unable to download geckodriver. Hit any key to exit program.") user_input = input() exit() # Parse the html using beautifulsoup and store in variable `soup` soup = BeautifulSoup(page, "html.parser") # Trying to search and filter latest win64 version result = soup.find_all('a', {'class': 'd-flex flex-items-center'})
has comment: http://stackoverflow.com/comment/91692718
upvote count: 1
answer count: 1
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/q/52391446
tagged with: tesseract
has comment: http://stackoverflow.com/comment/91728117
has body: So I was trying to run some code using pytesseract, and I got this error: raise TesseractNotFoundError() TesseractNotFoundError: tesseract is not installed or it's not in your path There was a post on this site that provided the solution, I added it to my code and it fixed things: pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe" However, I want to understand what exactly this line of code is doing as I don't understand? It looks like it is calling a method on the pytesseract library? I don't understand, is this a line of code that can work with any library? What does the "r" in front of the path of the program file do?
type: Question
score: 0
has title: This line of code fixed a pytesseract path issue I was having but I don't understand how it works, can someone explain how it works
tagged with: python
has comment: http://stackoverflow.com/comment/91728674
answer count: 0
type: UnansweredQuestion
tagged with: pytesser

http://stackoverflow.com/comment/91533041
type: AnswerComment
comment on: http://stackoverflow.com/a/52292652
type: Comment
has text: That said, Python is very hacky. Likely you could code something that does this, but I do not think it should be a part of any answer.
score: 1

http://stackoverflow.com/q/52315357
downvote count: 0
type: UnansweredQuestion
has title: Django : Direct assignment to the forward side of a many-to-many set is prohibited. Use user.set() instead
tagged with: django
has answer: http://stackoverflow.com/a/52315435
score: 10
has body: I am getting this error when I try to add the current logged in user into another relation as ManyToManyField. TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use user.set() instead. Here is my code: Views.py def add_to_cart(request , item): name = item size = request.POST.get("size") extras = request.POST.get("extras") c = Cart(item=name , size=size , extras=extras , user=request.user) c.save() return render(request , "orders/add_items.html" , {"message":f"{name} added to cart"}) Models.py class Cart(models.Model): item = models.CharField(max_length=64) size = models.DecimalField(max_digits=5,decimal_places=2) extras = models.CharField(max_length=64 , null=True, blank=True) user = models.ManyToManyField(User , related_name="member") def __str__(self): return f"{item} added by {user}"
type: Question
answer count: 1
linked to: http://stackoverflow.com/q/50015204
upvote count: 10
has comment: http://stackoverflow.com/comment/120759801
has comment: http://stackoverflow.com/comment/91578007
tagged with: python
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/52408949
upvote count: 11
type: AnsweredQuestion
tagged with: machine-learning
score: 11
has title: Cross-validation and parameters tuning with XGBoost and hyperopt
type: Question
has answer: http://stackoverflow.com/a/52411910
accepted answer: http://stackoverflow.com/a/52411910
tagged with: cross-validation
has body: One way to do nested cross-validation with a XGB model would be: from sklearn.model_selection import GridSearchCV, cross_val_score from xgboost import XGBClassifier # Let's assume that we have some data for a binary classification # problem : X (n_samples, n_features) and y (n_samples,)... gs = GridSearchCV(estimator=XGBClassifier(), param_grid={'max_depth': [3, 6, 9], 'learning_rate': [0.001, 0.01, 0.05]}, cv=2) scores = cross_val_score(gs, X, y, cv=2) However, regarding the tuning of XGB parameters, several tutorials (such as this one) take advantage of the Python hyperopt library. I would like to be able to do nested cross-validation (as above) using hyperopt to tune the XGB parameters. To do so, I wrote my own Scikit-Learn estimator: from hyperopt import fmin, tpe, hp, Trials, STATUS_OK from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.model_selection import train_test_split from sklearn.exceptions import NotFittedError from sklearn.metrics import roc_auc_score from xgboost import XGBClassifier def optimize_params(X, y, params_space, validation_split=0.2): """Estimate a set of 'best' model parameters.""" # Split X, y into train/validation X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=validation_split, stratify=y) # Estimate XGB params def objective(_params): _clf = XGBClassifier(n_estimators=10000, max_depth=int(_params['max_depth']), learning_rate=_params['learning_rate'], min_child_weight=_params['min_child_weight'], subsample=_params['subsample'], colsample_bytree=_params['colsample_bytree'], gamma=_params['gamma']) _clf.fit(X_train, y_train, eval_set=[(X_train, y_train), (X_val, y_val)], eval_metric='auc', early_stopping_rounds=30) y_pred_proba = _clf.predict_proba(X_val)[:, 1] roc_auc = roc_auc_score(y_true=y_val, y_score=y_pred_proba) return {'loss': 1. - roc_auc, 'status': STATUS_OK} trials = Trials() return fmin(fn=objective, space=params_space, algo=tpe.suggest, max_evals=100, trials=trials, verbose=0) class Optimi…
answer count: 1
downvote count: 0
tagged with: scikit-learn
tagged with: xgboost
favorite count: 0
linked to: http://stackoverflow.com/q/52138897
tagged with: python

http://stackoverflow.com/q/52279662
has answer: http://stackoverflow.com/a/52279861
possible better answer: http://stackoverflow.com/a/52279910
has answer: http://stackoverflow.com/a/52279910
upvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/91507748
downvote count: 0
accepted answer: http://stackoverflow.com/a/52279861
has body: I have a little mathematics-practicing application in which, to add new problems, I just define a new function which returns some dictionaries like this: def p4(): vertices = random.randrange(1, 8) num_trees = random.randrange(2, 4) format_dict = { 'vertices': vertices, 'num_trees': num_trees } answer_dict = { 'answer': vertices*num_trees, 'wrong_1': 0, 'wrong_2': 1, 'wrong_3': 'There do not exist any' } return {'question': format_dict, 'answers': answer_dict} Just for some context, this is a Django app. where the text of each problem is stored in a model, and, when the user looks at the problem on the webpage, the text of the model is formatted according to format_dict and the multiple-choice answers are generated according to answer_dict. Now, every problem, defined above, has the line return {'question': format_dict, 'answer': answer_dict}. Is there a way I can call a function like this, with these two dictionaries, and have the same functionality while omitting the return? I feel as if—if every function needs to have that line—then there's something I can do to generalize it (... A decorator, maybe? I've never used one, but now may be a good excuse). The model method which processes the dictionaries looks like this: def gen_QAPair(self): # The name/location of the problem's function is stored in 'module' module = importlib.import_module(self.QAModule) # This calls the function (p4, for example) and gets the dictionaries qaPair = getattr(module, self.QAFunction)() # This takes the unformatted text and formats it according to # the returned format dictionary formatted_text = self.unformatted_text.format(**qaPair['question']) return {'question': formatted_text, 'answers': qaPair['answers']} The only thing I could think of was combining answer_dict and format_dict into a dictionary of dictionaries, and returning that—but it wouldn't really save much code, it'd just move defining the keys outside of the return statement.
tagged with: python
favorite count: 0
score: 4
has comment: http://stackoverflow.com/comment/91507395
type: Question
has title: Means of generalizing similarly-structured return statement in many similarly-structured functions
type: AnsweredQuestion

http://stackoverflow.com/q/52354783
favorite count: 0
tagged with: python
upvote count: 0
type: UnansweredQuestion
has body: I have two lists of tuples and i want to merge them into one Ex : List1 = [(a, 1),(b,2)] List2 =[(a, 3),(b,4)] I want theresult to be Result = [(a, 1,3),(b,2,4)]
score: -2
has comment: http://stackoverflow.com/comment/91654212
has comment: http://stackoverflow.com/comment/91654189
type: Question
downvote count: 2
has title: Python - Merge two lists of tuples into one
answer count: 1
has answer: http://stackoverflow.com/a/52354810

http://stackoverflow.com/q/52339031
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/52339074
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52339076
tagged with: python
has body: Hi I am trying to split up a a large metadate file in Python. I started using pandas and wasn't able to figure it out. Right now it's a tab delimited file that looks something like: id count MD1_G1 k123 MD1_G2 k34 MD2_G3 k5678 MD2_G4 k50633 MD4_G5 k100 First I wanted to try and split that first column into two. This is what I have so far: df = pd.read_table('Table1.txt',names=["id","count"]) #This below was my attempt at trying to split that first column df_tmp = pd.DataFrame(df.id.str.split('_',1).tolist(),columns=['id','descriptor']) I managed to split that first column but I don't know how to do it while keeping the original count column. Once I split that column I wanted to try and iteratively go through and create a new tab delimited file for each unique ID. So in this example I want to get to a situation where I make 3 new files from the original that contain information only from the unique ID. So using the example, I want to get to a situation where I ultimately have 3 new files: file 1: MD1 G1 k123 MD1 G2 k34 file 2: MD2 G3 k5678 MD2 G4 k50633 file 3: MD4 G5 k100 If anyone has any ideas please let me know!
score: 2
upvote count: 2
type: Question
has title: Extracting multiple new tab delimited files from an existing one
answer count: 2

http://stackoverflow.com/a/52301403
score: 1
upvote count: 1
has body: This class is not designed to be created manually, you need to create a consumption client, which will have an attribute "usages" which will be the class in question (instanciated correctly). There is unfortunately no samples for consumption yet, but creating the client will be similar to creating any other client (see Network client creation for instance). For consumption, what might help is the tests, since they give some idea of scenarios: https://github.com/Azure/azure-sdk-for-python/blob/fd643a0/sdk/consumption/azure-mgmt-consumption/tests/test_mgmt_consumption.py If you're new to Azure and Python, you might want to do this quickstart: https://learn.microsoft.com/en-us/azure/python/python-sdk-azure-get-started Feel free to open an issue in the main Python repo, asking for more documentation about this client (this will help prioritize it): https://github.com/Azure/azure-sdk-for-python/issues (I'm working at Microsoft in the Python SDK team).
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52292879
type: Answer
answers question: http://stackoverflow.com/q/52292879
has comment: http://stackoverflow.com/comment/91564300

http://stackoverflow.com/comment/91756562
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52406267
score: 0
has text: you will probably want to use [dict.update](https://docs.python.org/3.7/library/stdtypes.html#dict.update) but note that you certainly can get the old quantity and the new one with one SQL query

http://stackoverflow.com/comment/91621762
comment on: http://stackoverflow.com/a/52336142
type: Comment
has text: I think this doesn't work, still... `d[key] = [value] if key not in d else d[key] + [value]` should work and cover both cases correctly.
score: 1
type: AnswerComment

http://stackoverflow.com/a/52312166
answers question: http://stackoverflow.com/q/52310905
has comment: http://stackoverflow.com/comment/91607763
has body: What happens if you initialize the two types to the exact same values? do they still learn different classifications? What loss function are you using on top of these classifiers? Is it the same loss function? In terms of computations, both types are performing the same: they multiply the input feature vector with n weight vectors. Thus, if the weight vectors have the same values, both types should output the same classifications. I suppose in terms of runtime and efficiency it is better to use one n dimensional classifier as oppose to n 1D: this way, I believe, allows for more hardware acceleration options.
has comment: http://stackoverflow.com/comment/91604664
score: 0
type: Answer

http://stackoverflow.com/q/52373683
type: Question
score: -2
possible better answer: http://stackoverflow.com/a/52373824
has answer: http://stackoverflow.com/a/74610017
has comment: http://stackoverflow.com/comment/91692134
has comment: http://stackoverflow.com/comment/91692173
has answer: http://stackoverflow.com/a/52373824
downvote count: 4
has title: Get only unique words from a sentence in Python
favorite count: 0
answer count: 5
has answer: http://stackoverflow.com/a/52373735
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52373726
has body: Let's say I have a string that says "mango mango peach". How can I print only the unique words in that string. The desired output for the above string would be [peach] as a list Thanks!!
upvote count: 2
accepted answer: http://stackoverflow.com/a/52373735
has answer: http://stackoverflow.com/a/52373794

http://stackoverflow.com/q/52378007
upvote count: 0
score: -1
has answer: http://stackoverflow.com/a/52378063
has title: Call external command in python, but stay in python
accepted answer: http://stackoverflow.com/a/52378063
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91703426
tagged with: python
linked to: http://stackoverflow.com/q/1196074
type: AnsweredQuestion
has body: I'm using python on a Raspberry Pi to display an image slideshow with the program fim. subprocess.call(["fim /home/pi/slates"], shell=True) Once fim has opened the focus stays on fim, not python. There are keyboard commands in python that no longer respond. How do I go back to python after fim has been opened? Is there a way to control fim through python if it's no longer in focus?
tagged with: subprocess
downvote count: 1
type: Question
tagged with: raspberry-pi

http://stackoverflow.com/comment/91600433
type: Comment
comment on: http://stackoverflow.com/q/52326709
score: 1
has text: `[list_of_words.index(word) for word in selected_words if word in list_of_words]`
type: QuestionComment

http://stackoverflow.com/q/52369174
tagged with: tensorflow
type: Question
score: 3
has title: Tensorflow adding floats gives additional digits
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52370423
tagged with: precision
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: So I was wondering why I do not get the sum of the two floats below, when adding them. Depending on the length of the float and whether there is a non zero digit before the point, the result has either an added or substracted additional digit or they just do not get added. The code below for example: import numpy as np import tensorflow as tf import matplotlib.pyplot as plt with tf.Graph().as_default(): a = tf.Variable(1, name="Var_a") dx = tf.Variable(1.33333, name='dx') dt = tf.Variable(5e-10, name='dt') dz = tf.Variable(1.0, name='dz') with tf.Session() as sess: sess.run(tf.global_variables_initializer()) a = dt+dx a = a-dz print dx.eval() print dt.eval() print (dt+dx).eval() print (dx+dt).eval() print a.eval() writer = tf.summary.FileWriter("/tmp/tensorlog") writer.add_graph(sess.graph) gives the following result: &gt;&gt;&gt;1.33333 &gt;&gt;&gt;5e-10 &gt;&gt;&gt;1.33333 &gt;&gt;&gt;1.33333 &gt;&gt;&gt;0.33333004 So the addition did not happen and the subtraction does not give a right result either. Thanks in advance for any ideas on this.
upvote count: 3

http://stackoverflow.com/q/52416342
type: AnsweredQuestion
has body: How would I do the following in javascript? &gt;&gt;&gt; import socket &gt;&gt;&gt; socket.gethostname() 'LA-DEV-IM-MM' I am using a gulp command and I'd like to do something like: if (socket_name in [ip1, ip2, ip3]) { mode = dev; } else { mode = prod; }
has title: How to get socket name in javascript
type: Question
linked to: http://stackoverflow.com/q/922476
tagged with: javascript
accepted answer: http://stackoverflow.com/a/52416544
score: 0
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52416544

http://stackoverflow.com/a/52379824
has comment: http://stackoverflow.com/comment/91704573
accepted answer of: http://stackoverflow.com/q/52378927
type: Answer
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/91704194
has comment: http://stackoverflow.com/comment/91704073
upvote count: 3
has body: The way the vdso works is, among other things, mapping process-specific variables into userspace that the vdso functions know how to read. One of them is the current process ID, so gettimeofday doesn't need to make a syscall to access that information. Now, specifically for getpid, it's not actually a VDSO call. In glibc before 2.25, the library would cache calls, and since part of the Python runtime calls getpid, there wouldn't be calls to it after the first. From 2.25 onward, the library doesn't cache the process ID, and so every getpid call results in a syscall.
has comment: http://stackoverflow.com/comment/91704660
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52378927

http://stackoverflow.com/a/52418340
has body: I'm not able to replicate using nearly identical code in virtual environments running both Python 2 and 3 and PyYAML==3.13. &gt;&gt;&gt; import yaml &gt;&gt;&gt; with open('sample.yaml', 'r') as infile: ... db_cfg = yaml.safe_load(infile) ... &gt;&gt;&gt; db_cfg {'database_info': {'username': 'edamame', 'password': 'mypassword', 'host': '1.2.3.4', 'port': 3306, 'database': 'mydb'}} Are you getting this error using the same exact input as the sample? Otherwise, make sure your inputs are properly formatted. Is there a space after each colon? Are things indented properly?
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52414636
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91711355
comment on: http://stackoverflow.com/q/52383495
score: 0
has text: @kapil Yes, but it doesn't work.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/54994772
answers question: http://stackoverflow.com/q/52420385
score: 0
has body: Maybe you have no cudnn.Remeber to install the right Version! Secondly,the version of CUDA may be different from the one needed by pytorch. I got the same Error, now it goes right. Good luck!
type: Answer

http://stackoverflow.com/comment/91577978
type: QuestionComment
comment on: http://stackoverflow.com/q/52313851
score: 0
has text: @Teoretic I can certainly use the logging module (I considered that solution also), but I don't want to clutter the log file- the log file should only be for logging, not to serve as a dump for something I am later going to machine-parse for a specific debugging task... I think. In other words, it seems to be a multiple use for the log file, which makes me uncomfortable. Of course I could create multiple loggers to multiple files- but I want to avoid passing them deep into functions.
type: Comment

http://stackoverflow.com/comment/133398504
has text: @zero: If I understood it correctly, you need to select the code you want to run (possibly the whole script, at first), and use shift+enter again. You can then code line by line, and you see the results directly in IPython.
type: Comment
comment on: http://stackoverflow.com/a/54564892
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91646385
comment on: http://stackoverflow.com/a/52350376
type: AnswerComment
score: 0
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/180132/discussion-between-modelmat-and-epo).
type: Comment

http://stackoverflow.com/comment/91849650
type: Comment
has text: It's something like this: DATABASE_URL: mysql2://root:xxx@localhost
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52385990

http://stackoverflow.com/q/52320053
has comment: http://stackoverflow.com/comment/91756677
has comment: http://stackoverflow.com/comment/91762410
has comment: http://stackoverflow.com/comment/91587955
tagged with: dataframe
type: Question
linked to: http://stackoverflow.com/q/52245145
has title: Pandas DF arrange cells and add prefix
score: 0
has comment: http://stackoverflow.com/comment/91744668
tagged with: pandas
has comment: http://stackoverflow.com/comment/91639154
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91590368
has body: Dataframe example - result of a previously cleaned pandas.read_excel: import pandas as pd import numpy as np raw_data = {'ref': ['409075', '405168', '035751', '039374', '331949', '331951', '307128'], 'description': ['Product 7 (12X)', 'Product 6 (8X)', 'Product 2', 'Product 1', 'Product 2', 'Product 3', 'Product 3'], 'maker': [np.nan, np.nan, 'Companyname1', 'Comp.2', 'Company3', 'Company name 4', 'Maker 5'], 'type': [np.nan, np.nan, 'Rev. 0', np.nan, np.nan, np.nan, 'Type 5'], 'qty': [6, 4, 4, 2, 12, 12, 12], 'val': [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan], 'serial': [np.nan, np.nan, np.nan, 58690, 900078, 69402, 900078]} df = pd.DataFrame(raw_data, columns = ['ref_maker', 'description', 'serial', 'maker', 'type', 'val, ''qty']) Below is the desired output (in columns): ref a) description + b)maker + c) type + d) val + e) serial qty condition: resulting, concatenated description-column must not have more than 30 characters and shouldn't cut imported cells. (Partially covered in: Prepare Pandas DataFrame for excel write) | ref | description (max 30 ch.) | qty | |-------- |---------------------------- |----- | | 409075 | Product 7 (12X) | 6 | | 405168 | Product 6 (8X) | 4 | | 35751 | Product 2 | 4 | | | MKR: Companyname1 | | | | Type: Rev. 0 | | | 39374 | Product 1 | 2 | | | MKR: Comp.2; SRL: 58690 | | | 331949 | Product 2 | 12 | | | MKR: Company3; SRL: 900078 | | | 331951 | Product 3 | 12 | | | MKR: Company name 4 | | | | SRL: 69402 | | | 307128 | Product 3 | 12 | | | MKR: Maker 5; Type: Type 5 | | | | SRL: 900078 | | I have tried to find solutions, but I did not have success changing them to my needs due to not understanding them (properly). Hope to meet the requirements. Thankful for any help and hints.
has comment: http://stackoverflow.com/comment/91612808
tagged with: python

http://stackoverflow.com/q/52368514
linked to: http://stackoverflow.com/q/18902608
downvote count: 0
has comment: http://stackoverflow.com/comment/91681336
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91681515
has comment: http://stackoverflow.com/comment/91681557
type: UnansweredQuestion
tagged with: python
tagged with: regex
has body: I have done good analysis on SO and other forums and I have seen solutions on how to handle plurals but here it is the case of handling if the words are passed from excel. I have a long list of keywords and I am passing that list to my regex like below: df = pd.read_excel('\\Keywords.xlsx', sheet_name=0) keyword_list = df['Keyword_List'].tolist() keywords_regex =(r'(({0})\b)'.format('|'.join(keyword_list))) I have to keep \b in the end because I have words like "Meet" and don't want words like "Meeting" to be matched. I have a huge text paragraph and I want to check how many of the words in my keyword list occurs including the plurals. So, if the paragraph contains a word like "Boy" and "Boys" both I want both. Currently the below code is working only for singular: matches = re.findall(keywords_regex, text, re.IGNORECASE) ## text is the long paragraph I can always write plural forms of words in the excel to get the match but I am looking of there is any we can handle at regex or python level only
has comment: http://stackoverflow.com/comment/91681970
answer count: 0
score: 1
upvote count: 1
has title: Python::Handling Plurals in regex when keywords are passed through Excel
has comment: http://stackoverflow.com/comment/91681665
type: Question
has comment: http://stackoverflow.com/comment/91681345

http://stackoverflow.com/q/52360482
accepted answer: http://stackoverflow.com/a/52360716
answer count: 1
downvote count: 0
score: 1
tagged with: amazon-web-services
has body: I'm trying to deploy my Django app in eb. I've created the environment on eb and even though all things seems good internal server error happens. I was just following the tutorial on official site. I already committed my requirements.txt and .ebextensions to my git. I set the environement variables on eb configuration. But there's an internal server error. And also eb open doesn't work. .ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: config/wsgi.py settings.py ALLOWED_HOSTS = ["*"] I'm still using sqlite3 on local. error.log is like this [Mon Sep 17 03:26:31.366607 2018] [mpm_prefork:notice] [pid 10621] AH00169: caught SIGTERM, shutting down [Mon Sep 17 03:26:32.520377 2018] [suexec:notice] [pid 11711] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Mon Sep 17 03:26:32.536121 2018] [so:warn] [pid 11711] AH01574: module wsgi_module is already loaded, skipping [Mon Sep 17 03:26:32.538258 2018] [http2:warn] [pid 11711] 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. [Mon Sep 17 03:26:32.538272 2018] [http2:warn] [pid 11711] AH02951: mod_ssl does not seem to be enabled [Mon Sep 17 03:26:32.538809 2018] [lbmethod_heartbeat:notice] [pid 11711] AH02282: No slotmem from mod_heartmonitor [Mon Sep 17 03:26:32.538869 2018] [:warn] [pid 11711] mod_wsgi: Compiled for Python/3.6.2. [Mon Sep 17 03:26:32.538875 2018] [:warn] [pid 11711] mod_wsgi: Runtime using Python/3.6.5. [Mon Sep 17 03:26:32.541103 2018] [mpm_prefork:notice] [pid 11711] AH00163: Apache/2.4.33 (Amazon) mod_wsgi/3.5 Python/3.6.5 configured -- resuming normal operations [Mon Sep 17 03:26:32.541124 2018] [core:notice] [pid 11711] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [Mon…
has comment: http://stackoverflow.com/comment/91665719
tagged with: python
tagged with: amazon-elastic-beanstalk
favorite count: 0
has answer: http://stackoverflow.com/a/52360716
upvote count: 1
tagged with: django
type: AnsweredQuestion
has title: Django and ElasticBeanstalk: Internal server error, HTTP/2 protocol will be inactive
type: Question

http://stackoverflow.com/comment/91721628
has text: Sure. I get `♫ When the spacing is tight / And the difference is slight / That's a moiré ♫`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52387450

http://stackoverflow.com/q/52345592
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/91637322
tagged with: django
has comment: http://stackoverflow.com/comment/91637711
answer count: 1
has title: Django - retrieve url from HttpResponse object?
upvote count: 3
has answer: http://stackoverflow.com/a/62088160
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91637748
score: 3
has body: In Django test cases, how do you get the url from a HttpResponse object? If I have the following Django app: urls.py from django.urls import path from . import views urlpatterns = [ path('httpresponse/', views.http_response, name='http_response'), ] views.py from django.shortcuts import render def http_response(request): return render(request, template_name='home.html') tests.py from django.test import TestCase from django.urls import reverse http_response = reverse('http_response') class TestTemplateResponse(TestCase): def test_http_response(self): response = self.client.get(http_response) self.assertEqual(response.url, http_response) The unit test fails with the following message: AttributeError: 'HttpResponse' object has no attribute 'url'. Is there any way to get the client to return a Response object, instead of HttpResponse?
tagged with: python
has comment: http://stackoverflow.com/comment/91637309

recaptcha
tag name: recaptcha
tags question: http://stackoverflow.com/q/52364135
type: Tag

http://stackoverflow.com/q/52403793
favorite count: 0
has title: Perimeter of a 2D convex hull in Python
tagged with: python
has answer: http://stackoverflow.com/a/52404024
accepted answer: http://stackoverflow.com/a/52404024
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/35664675
score: 1
tagged with: convex-hull
upvote count: 1
type: Question
has body: How can I calculate the perimeter of a convex hull in Python? I know SciPy has the area parameter for convex hulls; however, I need the perimeter.
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91751425

http://stackoverflow.com/comment/91722173
comment on: http://stackoverflow.com/q/52388583
has text: try `np.random.uniform(0,1,10).reshape(1,10)`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52343540
favorite count: 0
upvote count: 2
tagged with: classification
tagged with: predict
tagged with: python
downvote count: 1
type: AnsweredQuestion
has body: I am very new to DataScience/Pandas in general. I mainly followed this and could get it to work using different classifiers. import pandas as pd import src.helper as helper import time import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.ensemble import GradientBoostingClassifier # Headings headings = ['class', 'cap-shape', 'cap-surface', 'cap-color', 'bruises', 'odor', 'gill-attachment', 'gill-spacing', 'gill-size', 'gill-color', 'stalk-shape', 'stalk-root', 'stalk-surface-above-ring', 'stalk-surface-below-ring', 'stalk-color-above-ring', 'stalk-color-below-ring', 'veil-type', 'veil-color', 'ring-number', 'ring-type', 'spore-print-color', 'population', 'habitat'] # Load the data shrooms = pd.read_csv('data/shrooms_no_header.csv', names=headings, converters={"header": float}) # Replace the ? in 'stalk-root' with 0 shrooms.loc[shrooms['stalk-root'] == '?', 'stalk-root'] = np.nan shrooms.fillna(0, inplace=True) # Remove columns with only one unique value for col in shrooms.columns.values: if len(shrooms[col].unique()) &lt;= 1: print("Removing column {}, which only contains the value: {}".format(col, shrooms[col].unique()[0])) shrooms.drop(col, axis=1, inplace=True) # Col to predict later col_predict = 'class' # Binary Encoding all_cols = list(shrooms.columns.values) all_cols.remove(col_predict) helper.encode(shrooms, [col_predict]) # Expand Shrooms DataFrame to Binary Values helper.expand(shrooms, all_cols) # Remove the class we want to predict x_all = list(shrooms.columns.values) x_all.remove(col_predict) # Set Train/Test ratio ratio = 0.7 # Split the DF df_train, df_test, X_train, Y_train, X_test, Y_test = helper.split_df(shrooms, col_predict, x_all, ratio) # Try different classifier # TODO: Batch Use to compare classifier = GradientBoostingClassifier(n_estimators=1000) # TODO: Optimize Hyperparamter (where applicable) # Time the training timer_sta…
score: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91633298
has answer: http://stackoverflow.com/a/52343837
type: Question
has comment: http://stackoverflow.com/comment/91633384
answer count: 1
accepted answer: http://stackoverflow.com/a/52343837
has title: Make prediction from Pandas DataFrame
tagged with: pandas

axes
tag name: axes
type: Tag
tags question: http://stackoverflow.com/q/52350642

http://stackoverflow.com/comment/92067990
score: 0
type: AnswerComment
has text: @el_pup_le what exactly is unclear in my post? I suggest to check and fix the settings in PyCharm itself, not hunt files around the disk.
comment on: http://stackoverflow.com/a/52553043
type: Comment

http://stackoverflow.com/q/52279902
tagged with: machine-learning
downvote count: 1
has answer: http://stackoverflow.com/a/52280326
has answer: http://stackoverflow.com/a/52280138
type: Question
tagged with: categorical-data
answer count: 2
has body: I may be missing something but after following for quite a long time now the suggestion (of some senior data scientists) to LabelEncoder().fit only to training data and not also to test data then I start to think why is this really necessary. Specifically, at SkLearn if I want to LabelEncoder().fit only to training data then there are two different scenarios: The test set has some new labels in relation to the training set. For example, the test set has only the labels ['USA', 'UK'] while the test set has the labels ['USA', 'UK', 'France']. Then, as it has been reported elsewhere (e.g. Getting ValueError: y contains new labels when using scikit learn&#39;s LabelEncoder), you are getting an error if you try to transform the test set according to this LabelEncoder() because exactly it encounters a new label. The test set has the same labels as the training set. For example, both the training and the test set have the labels ['USA', 'UK', 'France']. However, then LabelEncoder().fit only to training data is essentially redundant since the test set have the same known values as the training set. Hence, what is the point of LabelEncoder().fit only to training data and then LabelEncoder().tranform both the training and the test data if at case (1) this throws an error and if at case (2) it is redundant? Let my clarify that the (pretty knowledgeable) senior data scientists whom I have seen to LabelEncoder().fit only to training data, they had justified this by saying that the test set should be entirely new to even the simplest model like an encoder and it should not be mixed at any fitting with the training data. They did not mention anything about any production or out-of-vocabulary purposes.
tagged with: scikit-learn
favorite count: 0
linked to: http://stackoverflow.com/q/46288517
type: UnansweredQuestion
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/112583217
upvote count: 3
has title: SkLearn - Why LabelEncoder().fit only to training data

http://stackoverflow.com/comment/91518174
comment on: http://stackoverflow.com/a/52284920
type: AnswerComment
has text: Would be good to mention that `update()` actually modifies the dictionary inside the list, so it will mutate the input.
score: 0
type: Comment

http://stackoverflow.com/a/52334104
has body: Autocommit should be disabled if multiple operations belong together logically to ensure that not only some of them are executed (atomicity). Additionally it should be disabled if multiple operations are done consecutively in a short period of time for performance reasons. For databases with concurrent access from different threads/processes additional consistency considerations apply but this usage is unlikely for Sqlite.
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/52333800
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52333800
type: Answer
score: 4

http://stackoverflow.com/a/52357972
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52357831
answers question: http://stackoverflow.com/q/52357831
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/91660509
has body: It is not clear for me what you want to get with this. you can use: sup = list(zip(lst,lst2)) It will return a list of tuples. After that you can compare using your list comprehension. I believe what you want is res = [j for i, j, k in zip(sup, sup[1:], sup[2:]) if i &lt; j and j &gt; k and j[0] &gt;= 60.0] This returned [(70,7), (80,17)]. Note that i, j and k are tuples! That's why I selected j[0] to check if it is >= 60

http://stackoverflow.com/comment/91606313
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/52329755
has text: what is `unknown`, which line in the error?
type: Comment

http://stackoverflow.com/comment/115903765
score: 7
comment on: http://stackoverflow.com/a/52351829
type: AnswerComment
type: Comment
has text: @JuliarNasution - every function has a "signature", a pattern of arguments. If you override `save` with a new definition that doesn't take any arguments (except the implicit `self`), you get the reported error when it is passed an argument it is expected to handle, e.g. `force_insert`. The `*args, **kwargs` syntax says, "collect all positional args in the `args` list and all keyword args in the `kwargs` dict". Tnen they can be passed along via the `super` call to do their work.

http://stackoverflow.com/comment/91682602
type: Comment
comment on: http://stackoverflow.com/a/52368651
type: AnswerComment
has text: i want to have a txt that will have the table results and above, the sentence that would explain the range of dates. Note: on txt it appears as intended but it looks unformatted.
score: 0

http://stackoverflow.com/q/52290984
has answer: http://stackoverflow.com/a/52291086
downvote count: 0
answer count: 1
favorite count: 0
tagged with: django
tagged with: python
has title: Django TestCase not destroying test data after tests finish running
accepted answer: http://stackoverflow.com/a/52291086
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: django-tests
type: Question
has body: I am currently trying to write my first Django specs for an application. However, everytime I run the tests I receive a IntegrityError: UNIQUE constraint failed: auth_user.username due to the user I created in the previous running of the test now existing in the database. I was under the impression that TestCase encloses the test code in a database transaction so that all data created during the test is rolled back on completion? What am I doing wrong here? from django.test import TestCase from django.contrib.auth.models import User from basic.models import SavedModels # Create your tests here. class SavedModelsTestCase(TestCase): User.objects.create(username="user_001", password="useruser", first_name="Test", last_name="User", email="test_user@test.com" ) user = User.objects.filter(username="user_001") saved_model = SavedModels.objects.create(name="Test Model", description="A model", user=user ) def test_saved_models(self): saved_model = create_saved_model() self.assertTrue(isinstance(saved_model, SavedModels)) self.assertEqual(saved_model.name, "Test Model") self.assertEqual(saved_model.description, "A model") self.assertEqual(saved_model.user, user)

http://stackoverflow.com/comment/91643400
type: Comment
comment on: http://stackoverflow.com/q/52348594
type: QuestionComment
has text: Did you activate the environment?
score: 0

http://stackoverflow.com/q/52326920
tagged with: postgresql
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91601382
has comment: http://stackoverflow.com/comment/91601488
answer count: 0
type: Question
has title: Inserting selective columns to postgres using pandas python
has comment: http://stackoverflow.com/comment/91601902
has comment: http://stackoverflow.com/comment/91603395
score: 0
tagged with: pandas
has body: Objective is to write excel column data into postgres table.But all the columns names in excel doesn't match with the table column. So what I am doing is trying to insert only the common columns. I am able to get the common data in the set. I am stuck as to how to insert the data in a single query. I am using pandas dataframe. #Getting table columns in a list conn = psycopg2.connect(dbname=dbname, host=host, port=port, user=user, password=pwd) print("Connecting to Database") cur = conn.cursor() cur.execute("SELECT * FROM " + table_name + " LIMIT 0") table_columns = [desc[0] for desc in cur.description] #print table_columns #Getting excel sheet columns in a list df = pd.read_excel('/Users/.../plans.xlsx', sheet_name='plans') engine = create_engine('postgresql://postgres:postgres@localhost:5432/test_db') column_list = df.columns.values.tolist() #print(column_list) s = set(column_list).intersection(set(table_columns)) for x in df['column_1'] : sql = "insert into test_table(column_1) values ('" + x + "')" cur.execute(sql) cur.execute("commit;") conn.close() update the code based on the answers but with this every time i run the program it inserts new records. Is there any option where I can just do the update. s = set(column_list).intersection(set(table_columns)) df1 = df[df.columns.intersection(table_columns)] #print df1 df1.to_sql('medical_plans', con=engine, if_exists='append', index=False, index_label=None)

http://stackoverflow.com/a/52424572
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/52424085
has body: You can reset the index and plot as follows. Here I am using the values of D column as x-values and the index (range of values) as the y-values. By using reset_index() you add a column of index which makes using y='index' straightforward for your plotting purpose. import pandas as pd data = pd.DataFrame(np.random.randint(0,100,size=(10, 4)), columns=list('ABCD')).reset_index() ax = data.plot(x='D', y='index', color='k', legend=False) data'A','B','C'.plot(kind='barh', stacked=True, ax=ax) Output
score: 2
answers question: http://stackoverflow.com/q/52424085
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52379882
upvote count: 1
has comment: http://stackoverflow.com/comment/91706460
answers question: http://stackoverflow.com/q/52371412
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52371412
downvote count: 0
type: Answer
has body: The answer posted by @AnthonyWinzlet has the downside that it needs to churn through all documents in the users collection and perform $lookups which is relatively costly. So depending on the size of your Users collection it may well be faster to do this: Put an index on users.pet and users.car: db.users.createIndex({pet: 1, car: 1}) Put an index on cars.model: db.cars.createIndex({model: 1}) Put an index on pets.name: db.pets.createIndex({name: 1}) Then you could simply do this: Get the list of all matching "Tesla" cars: db.cars.find({model: "Tesla"}) Get the list of all matching "Mickey" pets: db.pets.find({name: "Mickey"}) Find the users you are interested in: db.users.find({car: { $in: [&lt;ids from cars query&gt;] }, pet: { $in: [&lt;ids from pets query&gt;] }}) That is pretty easy to read and understand plus all three queries are fully covered by indexes so they can be expected to be as fast as things can get.
score: 1

http://stackoverflow.com/q/52368151
answer count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/52482108
favorite count: 0
has answer: http://stackoverflow.com/a/68296127
type: UnansweredQuestion
tagged with: python
score: 1
has body: I'm creating automated test scripts using the Python behave framework. I wanted to edit my behave configuration file (behave.ini), but I can't find it. Where is the file located? Do I need to create the file myself in the home directory?
type: Question
tagged with: python-behave
has title: Can't find Behave's configuration file
upvote count: 2

http://stackoverflow.com/comment/91724836
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/52386921
has text: Would you be able to give me an example of the api request being used within the dataflow template?

http://stackoverflow.com/comment/91771574
has text: Note that declaring `OneTypeSerializer` with `model = OneType` in its Meta does not automatically enable serialization of `OneType` with this serializer in all places.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52413802

http://stackoverflow.com/q/52404877
answer count: 1
tagged with: pandas
tagged with: datetime
has answer: http://stackoverflow.com/a/52405599
tagged with: python
favorite count: 0
type: UnansweredQuestion
downvote count: 1
type: Question
score: -1
has body: I downloaded a list of currencies from a website. All the prices start in 2018-01-01 except for one currency, which starts in 2015. How can I have that series starting in 2018 so I can chart them together from 2018. I've tried loc and datetime, and nothing works. code below. base_polo_url = 'https://poloniex.com/public?command=returnChartData&amp;currencyPair={}&amp;start={}&amp;end={}&amp;period={}' start_date = datetime.strptime('2018-01-01', '%Y-%m-%d') # get data from the start of 2018 end_date = datetime.now() # up until today period = 300 # pull daily data (300 seconds per day) def get_crypto_data(poloniex_pair): '''Retrieve cryptocurrency data from poloniex''' json_url = base_polo_url.format(poloniex_pair, start_date.timestamp(), end_date.timestamp(), period) data_df = get_json_data(json_url, poloniex_pair) data_df = data_df.set_index('date') return data_df altcoins = ['ETH','LTC','XRP','STR','DASH','SC','XMR','XEM','MAID'] altcoin_data = {} for altcoin in altcoins: coinpair = 'BTC_{}'.format(altcoin) crypto_price_df = get_crypto_data(coinpair) altcoin_data[altcoin] = crypto_price_df Any help will be appreciated
has title: Python 3 - series start date
upvote count: 0

http://stackoverflow.com/q/52371049
tagged with: python
has comment: http://stackoverflow.com/comment/91692153
has comment: http://stackoverflow.com/comment/91691940
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/91691418
type: UnansweredQuestion
has body: I have a model with two scalar cost functions C_1(p, t) and C_2(p, t). My objective is to simultaneously minimize C_1 with respect to p and C_2 with respect to t. In other words, choose p and t such that dC_1(p, t) / dp = 0 dC_2(p, t) / dt = 0 Notice that I don't want dC_1(p, t) / dt to be 0 or vice versa. In other words, this problem is not equivalent to minimizing some linear combination of C_1 and C_2. Currently, I'm doing this in by alternating between minimizing C_1 while passing p as the parameter list, then minimizing C_2 while passing t. However this is inefficient and causes problems with momentum-based optimizers. Is there a way to optimize both costs simultaneously in tensorflow without the gradients from C_1 being applied to t and vice versa? Edit: A quick example looks like this: import tensorflow as tf import numpy as np p = tf.Variable(np.random.random(size=(5, 5))) t = tf.Variable(np.random.random(size=(5, 5))) C_1 = tf.abs(p) / (1 + t**4) C_2 = tf.abs(t) / (1 + p**4) optimizer = tf.train.GradientDescentOptimizer(learning_rate=.05) step1 = optimizer.minimize(C_1, var_list=[p]) step2 = optimizer.minimize(C_2, var_list=[t]) sess = tf.Session() sess.run(tf.global_variables_initializer()) for i in range(20): for j in range(5): sess.run(step1) for j in range(5): sess.run(step2) I'm looking for a way to avoid having to alternate between C_1 and C_2, so that I can use momentum-based optimizers (and also because I suspect it will lead to better convergence).
tagged with: tensorflow
type: Question
score: 1
has comment: http://stackoverflow.com/comment/91687162
upvote count: 1
has comment: http://stackoverflow.com/comment/91696016
favorite count: 0
has title: Minimizing two cost functions simultaneously w.r.t. two different parameters

http://stackoverflow.com/comment/91689434
comment on: http://stackoverflow.com/a/52371452
type: AnswerComment
has text: Python is installed usb? If so, I highly suggest you to install it on your system drive or at least on an hdd, it seems that installing python on usb isn't a great idea ( you can google it up ) probably because of environment variables/paths and stuff. If you have no choice but to run it via usb, you could always dual boot on a linux machine via usb with persistence ? And if you're talking about matplotlib, I'm not even sure how you would install it on a usb. Just open up a cmd prompt and type in: `pip install --upgrade setuptools` and after type in: `py -m easy_install matplotlib`
score: 0
type: Comment

http://stackoverflow.com/a/52380149
has comment: http://stackoverflow.com/comment/91758602
answers question: http://stackoverflow.com/q/52371724
score: 0
has comment: http://stackoverflow.com/comment/91740183
has body: put below in your model which is related with Many2one _rec_name = 'field_you_want_to_show_in_dropdown'
type: Answer
has comment: http://stackoverflow.com/comment/91711145

http://stackoverflow.com/comment/91734420
score: 1
type: AnswerComment
has text: I knew there was a way to avoid `stack()` twice. Passed the list but was missing the `level` keyword. Much appreciated, edited my answer.
comment on: http://stackoverflow.com/a/52394497
type: Comment

http://stackoverflow.com/comment/91521048
type: Comment
type: QuestionComment
has text: oh, so it won't work by passing just the api_key?
score: 0
comment on: http://stackoverflow.com/q/52286294

http://stackoverflow.com/q/52378271
has answer: http://stackoverflow.com/a/52378849
has comment: http://stackoverflow.com/comment/91706663
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/c
score: -3
has title: pass parameters to function of dll in python leads to access violation writing 0x00000014
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/91706814
downvote count: 3
has body: win 7 python 2.7 In python, I call a function in dll using ctype to read flash value in a MCU. But I got the access violation writing 0x00000014 error. dll function: int get_flash_value(int addr, int readlen, char *data) { unsigned char read_data[4096]; int ret; int i; const unsigned int rlen = 4096; int restlen = 0; const unsigned int readtimes = (readlen / 4096); int writelen = 0; ret = bulk_read_cmd(addr, 32, data); if (ret) { TRACE("try to dump failure,addr is 0x%x.", addr); return -1; } for (i = 0; i &lt; readtimes; i++) { memset(data, 0x0, 4096); ret = bulk_read_cmd(addr + (rlen*i), rlen, data); if (ret) { TRACE("dump failure,addr is 0x%x.", addr + (rlen*i)); return -1; } ret = bulk_read_cmd(addr + (rlen*i), restlen, data); if (ret) { TRACE("dump failure,addr is 0x%x.", addr + (rlen*i)); return -1; } memcpy(data, read_data, readlen); return 0; } } int send_request(const unsigned char *buf, unsigned int len) { unsigned int send_cnt; int exitCode; EnterCriticalSection(&amp;csSend); send_cnt = send_req_cnt++; LeaveCriticalSection(&amp;csSend); //TRACE("[%u] Enter send_request", send_cnt); exitCode = push_send_queue(buf, len); if (exitCode) { TRACE("[%u] push_send_queue failed", send_cnt); } else { //TRACE("[%u] push_send_queue succeeded", send_cnt); } return exitCode; } I got the same error when I tried to use the function to read the flash in the MCU: Exception thrown at 0x7787EBCB (ntdll.dll) in transferdll.exe: 0xC0000005: Access violation writing location 0x00000014. error in vs when debug
answer count: 1
upvote count: 0

http://stackoverflow.com/comment/91799338
type: Comment
type: QuestionComment
has text: Put some print statements in your for loops to debug the output.
comment on: http://stackoverflow.com/q/52427926
score: 0

http://stackoverflow.com/comment/91636770
comment on: http://stackoverflow.com/a/52345073
type: AnswerComment
has text: @dntkald Please mark answers as correct to close this.
score: 0
type: Comment

http://stackoverflow.com/q/52430001
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52430119
answer count: 4
has answer: http://stackoverflow.com/a/52430030
has comment: http://stackoverflow.com/comment/91803604
has answer: http://stackoverflow.com/a/52430073
score: 1
upvote count: 1
type: Question
has title: Is it possible to put else inside a function if the if statment is outside it?
has comment: http://stackoverflow.com/comment/91804745
has comment: http://stackoverflow.com/comment/91804426
has body: So im trying to create a quiz for an assignment but i got tired writing if and else after every question to see if its right so i decided to try making a function. The thing is that the if statement can't go inside the function as it needs check the users answer. What i tried to do looks something like def result(): print("Correct") else: print("Wrong") I wanted to insert the function after an if statment but i just get a syntax error whenever I try to run it since there is no if statement to go before the else in the function. Is there any way to get around this?
has comment: http://stackoverflow.com/comment/91803878
has comment: http://stackoverflow.com/comment/91803527
has answer: http://stackoverflow.com/a/52430079

http://stackoverflow.com/comment/91738108
type: QuestionComment
has text: But I got what I need after execute script.
type: Comment
comment on: http://stackoverflow.com/q/52396055
score: 0

http://stackoverflow.com/comment/91737666
score: 0
has text: Thanks for the quick response, it appears as though the locations are not exactly the same! One is looking in a 3.5 file and the other is in a 3.6 file. How can I go about correcting this? Here is the output https://i.gyazo.com/a3a4ad5e11a8d3932c69a56679f6afba.png
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52396370

http://stackoverflow.com/comment/91739386
has text: eh, I've tried that way. These two expressions are almost the same under this circumstance.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52397248
type: QuestionComment

http://stackoverflow.com/q/52288382
type: Question
linked to: http://stackoverflow.com/q/21237678
has title: Connecting Ubuntu 16.04 to remote MSSQL server in the same domain
tagged with: odbc
has comment: http://stackoverflow.com/comment/91525916
has comment: http://stackoverflow.com/comment/91526312
tagged with: ubuntu
tagged with: sql-server
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91525273
has comment: http://stackoverflow.com/comment/91527345
answer count: 0
tagged with: freetds
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91642319
has body: I am having a lot of issues trying to connect to my mssql server. I have gone through what feels like hundreds of SO threads and articles over the last two days trying to connect these two. Here's what I can do. From Ubuntu, I can ping Window MSSQL Server I can successfully telnet 192.168.0.40 1433 I can even successfully connect using tsql -H sqlserver.domain.com.au -p 1433 -U nbar -P nb No I don't mind you seeing my passwords as they are demo user I created. I even get data with use database go select * from table But when I try the same using tsql -S Myserver -U nbar -P nb I get nothing! Only the counter. Eventually it times out. Here is my freetds.conf [MyServer] host = sqlserver.domain.com.au port = 1443 tds version = 7.3 For further information my eventual goal is to connect a flask app using pyodbc. I recently tried to configure my odbc.ini [MYSERVER] Description = "My Test Connection" Driver = FreeTDS ServerName = MyServer Server = 192.168.0.40 Port = 1433 Database = databaseName Any shoving in the right direction would be greatly appreciated. If you think I missed some information let me know and I will add via edits.

http://stackoverflow.com/comment/91649310
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52352118
has text: @Aran-Fey again. I understand that. I want to make two separated exceptions. Thous that will handle the requests.get(...) and thous that will handle the responsedata.raise_for_status(). The problem is that there is no list of execptions for each. This is why I'm asking here.

http://stackoverflow.com/comment/91664618
type: Comment
comment on: http://stackoverflow.com/a/52355332
score: 0
has text: I got the "中文名：柳公权". I guess the problem is due to decoding some Chinese text. I have similar issue if I run the code entirely within Jupyter notebook but no so if I ran it step-by-step or in dos prompt.
type: AnswerComment

http://stackoverflow.com/q/52345425
has comment: http://stackoverflow.com/comment/91636683
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91637256
type: Question
has comment: http://stackoverflow.com/comment/91636704
has comment: http://stackoverflow.com/comment/91637905
has title: How to access country restricted proxy website through urllib.request
tagged with: urllib3
upvote count: 1
tagged with: http-proxy
has comment: http://stackoverflow.com/comment/91636776
favorite count: 0
has comment: http://stackoverflow.com/comment/91637893
tagged with: selenium-chromedriver
has comment: http://stackoverflow.com/comment/91637929
linked to: http://stackoverflow.com/q/34222412
type: UnansweredQuestion
has body: I am trying to build a selenium scraper that rotate its IP address after every n request, for this i need to access a free proxy website in order to construct a list of IP:port addresses, the problem is that i am executing my code from a country that bans proxy websites, thus the code can't access the proxy website and is returning me this error: raise URLError(err) urllib.error.URLError: urlopen error [Errno 104] Connection reset by peer Here is my part of code that try to access https://www.sslproxies.org/ website: ua = UserAgent() # From here we generate a random user agent proxies = [] # Will contain proxies [ip, port] proxies_req = Request('https://www.sslproxies.org/') proxies_req.add_header('User-Agent', ua.random) proxies_doc = urlopen(proxies_req).read().decode('utf8') soup = BeautifulSoup(proxies_doc, 'html.parser') proxies_table = soup.find(id='proxylisttable') The error is occuring from the fifth line : proxies_doc = urlopen(proxies_req).read().decode('utf8') any suggestions?
tagged with: python
tagged with: python-requests
has comment: http://stackoverflow.com/comment/91637697
has comment: http://stackoverflow.com/comment/91637878

http://stackoverflow.com/a/52356860
has body: You've misspelled __init__ in your Rect class. pygame.draw.rect takes a surface, a color and a rect-style object which can be a pygame.Rect, a list or a tuple with four elements. Your custom Rect class won't work, but you could pass a tuple: rect = Rect(light_red, random.randrange(0,150), 150, 300, 50, 5) rect1n = pygame.draw.rect(display, rect.color, (rect.x, rect.y, rect.l, rect.h)) The arguments should not be strings: Rect(light_red, random.randrange(0,150), 150, 300, 50, 5) You could just give your Rect a draw method in which you call pygame.draw.rect (also give it a self.rect attribute instead of the separate self.x, etc. attributes): class Rect: def __init__(self,color,x,y,l,h,th): self.color = color self.th = th # Just create a pygame.Rect object to store the attributes. self.rect = pygame.Rect(x, y, l, h) def draw(self, surface): pygame.draw.rect(display, self.color, self.rect) rect = Rect(light_red, random.randrange(0,150), 150, 300, 50, 5) # Then draw it like this in the while loop. rect.draw(display) I recommend checking out how pygame sprites and sprite groups work and then turn your platform class into a pygame.sprite.Sprite subclass. If you want to see a simple platformer example with sprites and groups, take a look at this answer. Also, better choose another name for your Rect class, since there's already the pygame.Rect class.
score: 0
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/91671936
accepted answer of: http://stackoverflow.com/q/52354695
answers question: http://stackoverflow.com/q/52354695

http://stackoverflow.com/q/52383288
has answer: http://stackoverflow.com/a/52383512
possible better answer: http://stackoverflow.com/a/52383509
has comment: http://stackoverflow.com/comment/91710765
has comment: http://stackoverflow.com/comment/91710720
score: 0
has answer: http://stackoverflow.com/a/52383509
answer count: 3
has title: I want to split file’s extension by using regular expression
accepted answer: http://stackoverflow.com/a/52383512
tagged with: python
type: AnsweredQuestion
type: Question
has body: item is a string like "./test/test1.csv" . I want to change item into "test1". I wrote code, item=re.search('./*.csv',item) But,"1.csv" is item.I really cannot understand why such a thing happens.What should I do to do my ideal thing?
has answer: http://stackoverflow.com/a/52383343

http://stackoverflow.com/a/52429814
answers question: http://stackoverflow.com/q/52429613
upvote count: 1
has body: Using a Global variable A variable which is defined inside a function is local to that function. However, if you declare it as a global variable, it becomes accessible outside the function. item = input("What food???") def itemcheck(): global cereal if item == "chex": cereal = "Yummy" else: cereal = "Yuck!" itemcheck() print(cereal) . Using a return statement You could make a return statement, which specifies the value to be passed back to the code that called the function. item = input("What food???") def itemcheck(): if item == "chex": return "Yummy" else: return "Yuck!" print(itemcheck())
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91805268

http://stackoverflow.com/comment/91625125
comment on: http://stackoverflow.com/a/52335255
has text: Thanks man! I'll look into the code and play around it, that really helped!
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91644061
has text: @WarrenWeckesser Yeah, I just saw that. It must be the same as in the second example. Corrected it now.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52349191
score: 0

http://stackoverflow.com/a/52331437
has body: Using collections.Counter and itertools.groupby: from collections import Counter from itertools import groupby def in_out_flow(lst): in_flow = Counter(lst) out_flow = Counter(k for k, _ in groupby(lst)) out_flow[lst[-1]] -= 1 for k,v in in_flow.items(): print('key: {}, in flow: {}, out flow: {}'.format(k, v, out_flow[k])) Examples: in_out_flow(['a', 'a', 'a', 'b', 'b', 'a', 'c', 'c', 'b', 'a']) print('##') in_out_flow(['a', 'a', 'a', 'b', 'a', 'c', 'a', 'b']) Outputs: key: a, in flow: 5, out flow: 2 key: b, in flow: 3, out flow: 2 key: c, in flow: 2, out flow: 1 ## key: a, in flow: 5, out flow: 3 key: b, in flow: 2, out flow: 1 key: c, in flow: 1, out flow: 1
has comment: http://stackoverflow.com/comment/91610361
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/52331032
upvote count: 1

http://stackoverflow.com/comment/91726373
has text: Sounds like you've got duplicate owners, probably
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52389380
type: AnswerComment

http://stackoverflow.com/comment/91544536
has text: Thank you very much! :)
comment on: http://stackoverflow.com/a/52287392
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/91737550
has text: See also this: https://stackoverflow.com/questions/37084812/how-to-remove-decimal-points-in-pandas/37084889#37084889
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52396368

http://stackoverflow.com/comment/91542580
has text: @ksmukta: Yup, that would do it. `vim` uses the write-to-temp, atomic rename approach; you kept the handle to the original file (which continues to exist until the last handle is closed, but without a name on the file system). If you want to test, make some other file, and just append it to the open file with `cat otherfile >> openfilename`.
comment on: http://stackoverflow.com/q/52296885
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/52275553
score: 2
answers question: http://stackoverflow.com/q/52275496
downvote count: 0
has body: use join: d = ["Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width"] x = '+'.join(d) print(x) output: Sepal.Length+Sepal.Width+Petal.Length+Petal.Width
accepted answer of: http://stackoverflow.com/q/52275496
type: AcceptedAnswer
upvote count: 2
type: Answer

http://stackoverflow.com/comment/91696020
type: Comment
type: QuestionComment
score: 0
has text: This should probably be filed as an issue on github
comment on: http://stackoverflow.com/q/52297864

http://stackoverflow.com/comment/91630572
comment on: http://stackoverflow.com/q/52341976
score: 0
has text: `Counter` subclasses `dict` so looking at the c code for `dict` might give you some insights.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91549380
type: Comment
score: 2
has text: `s = df.groupby(df.msg.eq('phone').cumsum())`, I'll find a dupe for you
type: QuestionComment
comment on: http://stackoverflow.com/q/52300777

http://stackoverflow.com/comment/91741003
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52398066
has text: Point your `AUTH_USER_MODEL` from `settings.py` to your `app.CustomUserModel`

http://stackoverflow.com/comment/91676833
type: AnswerComment
score: 0
type: Comment
has text: @DanielF Sure! We could have a SO wiki answer post probably on it.
comment on: http://stackoverflow.com/a/52364284

http://stackoverflow.com/comment/91588489
type: Comment
comment on: http://stackoverflow.com/a/52320300
has text: of course it closes the CMD. But after performing the job. let me edit.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91729886
score: 0
type: AnswerComment
type: Comment
has text: Forgive my prejudice, but ***"With a minor change, we can turn our function into a generator"*** (as well as the education about Cartesian products) smacks of someone fresh from college and desperate for points. There is no call for an iterator here: it will always be called to exhaustion and may as well be delivered as a simple list. Let's not turn acrobatic tricks to solve ordinary problems.
comment on: http://stackoverflow.com/a/52383460

http://stackoverflow.com/comment/91807032
type: Comment
has text: You wouldn't happen to know of a tutorial with CustomJS and multiselect would you?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52416676

http://stackoverflow.com/q/52273358
tagged with: forms
has title: 'CreateForm' object has no attribute 'user' on form validation
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91494015
answer count: 1
has body: I'm trying to create a view in order to add data to my database through a FormView. However I'm getting this no attribute 'user' error. I found how to get rid of it with a function-based view here : MyModelForm' object has no attribute 'user using django , however I still don't get how to do the same with my class-based view. Here are my files : views.py : class CreateView(FormView): template_name = 'restaurant/create.html' form_class = CreateForm success_url = '' @method_decorator(login_required) def form_valid(self, form): obj = form.save(commit=False) obj.owner = self.request.user obj.save() return super().form_valid(form) forms.py : class CreateForm(forms.Form): name = forms.CharField() category = forms.CharField() capacity = forms.IntegerField() description = forms.CharField(widget=forms.Textarea) models.py : from django.contrib.auth.models import User class Restaurant(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) category = models.CharField(max_length=200) description = models.TextField() capacity = models.IntegerField(default=0) traceback : http://dpaste.com/2NTFS8H Thanks in advance !
has comment: http://stackoverflow.com/comment/91494211
tagged with: python
tagged with: django
linked to: http://stackoverflow.com/q/43459000
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52273511
accepted answer: http://stackoverflow.com/a/52273511
has comment: http://stackoverflow.com/comment/91494241

http://stackoverflow.com/a/52350398
type: Answer
has comment: http://stackoverflow.com/comment/91646249
score: 1
accepted answer of: http://stackoverflow.com/q/52350352
upvote count: 1
has body: Try this print tree.item(curitem)['values'][0] The data is in json format, you could use python dictionary to access it.
answers question: http://stackoverflow.com/q/52350352
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52390715
type: Answer
answers question: http://stackoverflow.com/q/52390195
downvote count: 1
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/91727442
has body: You may make a for loop to scan all tabs (every few seconds) and store the modifiedTime for all of them in a table. Program the loop to compare the current modifiedTime for each tab with the value you have from the last scan. When there is a mismatch, that's mean the current tab is modified. Just an idea.
has comment: http://stackoverflow.com/comment/91727699

http://stackoverflow.com/comment/128299291
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52434908
has text: Doesn't that model in the code for CI have to be initialized every time?

http://stackoverflow.com/q/52381020
upvote count: 2
tagged with: decoding
has comment: http://stackoverflow.com/comment/91706370
has comment: http://stackoverflow.com/comment/91707552
type: Question
has title: Using the right encoding for csv file in Python 3
has body: I wrote a function that takes one variable, file, which is a big .csv document. I get the following error immediately after calling the function for one specific file (the file is in German): UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe4 in position 4: invalid continuation byte The system's default encoding is utf-8, but if I open('C:/Users/me/Desktop/data/myfile.csv'), the output is: &lt;_io.TextIOWrapper name='C:/Users/me/Desktop/data/myfile.csv' mode='r' encoding='cp1252'&gt;. Using file.decode('cp1252').encode('utf8') doesn't work since 'str' object has no attribute 'decode', so I tried: for decodedLine in open('C:/Users/me/Desktop/data/myfile.csv', 'r', encoding='cp1252'): line = decodedLine.split('\t') but line is a list object and I can't .encode() it. How can I make .csv files that have a different encoding readable?
has comment: http://stackoverflow.com/comment/91706975
has comment: http://stackoverflow.com/comment/91708056
has answer: http://stackoverflow.com/a/52381651
has comment: http://stackoverflow.com/comment/91706889
answer count: 2
tagged with: encoding
has comment: http://stackoverflow.com/comment/91707962
downvote count: 0
has answer: http://stackoverflow.com/a/52381597
favorite count: 0
has comment: http://stackoverflow.com/comment/91706408
accepted answer: http://stackoverflow.com/a/52381651
tagged with: http://stackoverflow.com/tag/csv
possible better answer: http://stackoverflow.com/a/52381597
has comment: http://stackoverflow.com/comment/91706548
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/91707009
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91707331

http://stackoverflow.com/a/52346714
has comment: http://stackoverflow.com/comment/91639165
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52346653
answers question: http://stackoverflow.com/q/52346653
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91639219
type: Answer
has comment: http://stackoverflow.com/comment/91639199
has comment: http://stackoverflow.com/comment/91639334
has body: write doesn't append a newline like print does, so you should take care of it yourself. Also, note that there's no reason to open and close the file on each iteration. Just leave it open as long as you need it: with open('MyServices.txt', 'w') as f: for (short_name, desc, status) in statuses: f.write(str(statuses)) f.write(os.linesep) #Print output and append 'Running' at the end of each line print(desc, status, '----------&gt; Running')

http://stackoverflow.com/comment/91691666
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52373383
has text: @SuperStew I think that's a bit sweeping. Why would they bother to go to the effort of implementing it as a guarantee in the standard library if it's an antipattern? I suspect the motivation was the same as for JSON Lines. In my last company, we used it to feed dictionaries of information into a simulation in a fixed order, now we could have just used a regular dict.
score: 0

http://stackoverflow.com/q/52357513
tagged with: web-services
has comment: http://stackoverflow.com/comment/91660406
type: Question
has title: Raspberry Pi web server that controls hardware
score: 0
has answer: http://stackoverflow.com/a/52357666
answer count: 1
tagged with: raspberry-pi3
has body: First, thank you all for your useful posts. I can usually find what I need from SE without needing to make a post. I'm hoping to make a timer/sensor device that I can control from a web browser. I'm planning to hook up a set of sensors by USB or pinouts to a Raspberry pi, then having the Pi host a web server. I have experience writing web servers from scratch in python, so I intend to use python as my programming language for this application as well. I want to be able to visit the server from another device that will run at a time-keeper's station. By selecting options on the web site, you could control the display portion of the timer or the values of variables (timer reset) also the sensors could trigger update events to show information on the web page. My primary obstacle in this case is the hardware interface. I imagine I would need to look up how sites like OMSI allow users to control the motors that move their webcam, or other online control of hardware. What should my search terms be, or do you know of any libraries for python to read and write to external (adafruit-style) sensors? Thanks! Anthony (https://i.stack.imgur./RzWIl.png)
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52370360
tagged with: python
tagged with: append
type: UnansweredQuestion
upvote count: 1
tagged with: excel
type: Question
score: 1
tagged with: rows
has body: What is working now In the code below, the first 100 rows are getting downloaded to Futures.xlsx from the website. The website updates every 15 minutes refreshing new values just like a company stock. Total rows are 100. How can I modify my code such as every time a website updates or through some counter continue adding 100 more updated values to Futures.xlsx file. So I would say over one hour there would be 400 Rows. I have included first four lines of the code output. Output Contracts Markets Open High Low Last Pct Time 0 Oct 2018 (E) NG.F27.E 2.777 2.785 2.774 2.782 +0.36% 20:00 1 Nov 2018 (E) NG.F27.E 2.793 2.800 2.792 2.800 +0.32% 19:51 2 Dec 2018 (E) NG.F27.E 2.887 2.893 2.886 2.891 +0.21% 19:52 3 Jan 2019 (E) NG.F27.E 2.977 2.984 2.975 2.980 +0.20% 19:52 Code urllib.request import urlopen from bs4 import BeautifulSoup import requests import pandas as pd from pandas import ExcelWriter from pandas import ExcelFile import os url = "https://quotes.ino.com/exchanges/contracts.html?r=NYMEX_NG" res = requests.get(url) soup = BeautifulSoup(res.text, 'lxml') Markets = [] Contracts =[] Opens =[] Highs =[] Lows =[] Lasts=[] Changes=[] Pcts=[] data_rows = soup.findAll('tr')[3:] for td in data_rows[:100]: Market = td.findAll ('td')[0].text Markets.append(Market) Contract = td.findAll('td')[1].text Contracts.append(Contract) Open = td.findAll('td')[2].text Opens.append(Open) High = td.findAll('td')[3].text Highs.append(High) Low = td.findAll('td')[4].text Lows.append(Low) Last = td.findAll('td')[5].text Lasts.append(Last) Change = td.findAll('td')[6].text Changes.append(Change) Pct = td.findAll('td')[7].text Pcts.append(Pct) Time = td.findAll('td')[8].text df = pd.DataFrame({'Contracts' :Contracts, Markets':Market,'Open':Opens, 'High':Highs, 'Low':Lows,'Last':Lasts,'Pct':Pcts}) out_path = "C:\Sid\Futures.xls" writer = pd.ExcelWriter(out_path , engine='xlsxwriter') df.to_excel(writer,'Sheet2',index=False) writer.save()
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52370426
favorite count: 0
has title: Python : Appending values to existing spreadsheet from updated values

http://stackoverflow.com/a/52336008
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52333812
answers question: http://stackoverflow.com/q/52333812
has comment: http://stackoverflow.com/comment/91621706
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: AS user @dirkgroten pointed out in a comment to the question, the following line looks strange: queryset=ModelA.objects.values_list('b__name', flat=True) This way the widget has no way of knowing the pk of each element of the list (since it only return the names). That might couse that the view cannot save a selected ModelB instance, since it does not know the selected pk. Ah, you might also want to use ModelB instead of ModelA Try changing it to something like this queryset=ModelB.objects.values('pk', 'b__name') or even this queryset=ModelB.objects.all() and let us know if that works.

http://stackoverflow.com/a/52407194
answers question: http://stackoverflow.com/q/52407063
accepted answer of: http://stackoverflow.com/q/52407063
type: Answer
downvote count: 1
has body: Replace alpha='0.5' by alpha=0.5 in all your six plt.fill_between and plt.plot commands. The transparency alpha has to be a float. You are using a string and hence you are getting the error a float is required. More information on this official page where the Description of each argument is provided.
has comment: http://stackoverflow.com/comment/91758867
score: 1
upvote count: 2
has comment: http://stackoverflow.com/comment/91758207
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91758916

http://stackoverflow.com/a/52317212
downvote count: 2
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52317125
has body: {str(k): [str(x) for x in v] for k, v in array.items()} Result &gt;&gt;&gt; {str(k) : [str(x) for x in v] for k, v in a.items()} {'1': ['1', '2', '3'], '2': ['1', '2']}
upvote count: 2

http://stackoverflow.com/comment/91778287
has text: pd.read_csv has a parameter named skipinitialspace : boolean, default False Skip spaces after delimiter. If this was set to True, it would have worked
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52417458

http://stackoverflow.com/a/52365594
has body: db_cur has local scope in db_login. This means that it cannot be accessed outside db_login. A better way of doing this would be to return the object and use the returned object in script 2. For example, file1.py: import psycopg2 def db_login(): global dwh_connection global dwh_cur try: dwh_connection = psycopg2.connect(db_details) db_cur = dwh_connection.cursor() return db_cur except: print("Conn failed") return None print('Connection Success') file2.py from file1 import db_login def rep1(): db_cur = db_login() if db_cur is not None: db_cur.execute("""SQL statement""") dwh_connection.commit() dwh_connection.close() print('Task Completed')
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52365527

http://stackoverflow.com/a/52370538
score: 0
answers question: http://stackoverflow.com/q/52369089
type: Answer
has body: If you just want to print: first = input() for i in first.split()[::-1]: print(i, end=' ') doegarryjohn(xenial)vash@localhost:~/python/stack_overflow$ python3.7 reverse.py john garry doe doe garry john If you would like to store it as a variable: first = input() f_reverse = '' for i in first.split()[::-1]: f_reverse += (i + ' ') print(f_reverse)

http://stackoverflow.com/q/52333864
has title: Pickle breaking change in Python 3.7
score: 7
has answer: http://stackoverflow.com/a/52334850
has comment: http://stackoverflow.com/comment/91615724
has comment: http://stackoverflow.com/comment/91615087
type: Question
has comment: http://stackoverflow.com/comment/91615630
has comment: http://stackoverflow.com/comment/91614980
has comment: http://stackoverflow.com/comment/91616057
has body: I have custom list and dictionary classes that no longer work while unpickling in Python 3.7. import pickle class A(dict): pass class MyList(list): def __init__(self, iterable=None, option=A): self.option=option if iterable: for x in iterable: self.append(x) def append(self, obj): if isinstance(obj, dict): obj = self.option(obj) super(MyList, self).append(obj) def extend(self, iterable): for item in iterable: self.append(item) if __name__ == '__main__': pickle_file = 'test_pickle' my_list = MyList([{'a': 1}]) pickle.dump(my_list, open(pickle_file, 'wb')) loaded = pickle.load(open(pickle_file, 'rb')) print(isinstance(loaded[0], A)) Works fine on Python 2.6 through 3.6: "C:\Program Files\Python36\python.exe" issue.py True But is no longer setting the self.option properly in 3.7. "C:\Program Files\Python37\python.exe" issue.py Traceback (most recent call last): File "issue.py", line 28, in &lt;module&gt; loaded = pickle.load(open(pickle_file, 'rb')) File "issue.py", line 21, in extend self.append(item) File "issue.py", line 16, in append obj = self.option(obj) AttributeError: 'MyList' object has no attribute 'option' If I were to remove the extend function, it works as expected though. I have tried adding __setstate__ as well, but it is not called before extend so the option is still undefined at that point. I do have to inherit directly from dict and list, and I do need to overwrite both the append and extend function in my code. Is there a way to set option beforehand or another fix? Is this change in behavior documented and the rational for it? Thank you for your time
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52334850
tagged with: python
tagged with: python-3.x
tagged with: pickle
upvote count: 7
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91616440

http://stackoverflow.com/comment/91693874
type: Comment
comment on: http://stackoverflow.com/q/52373206
score: 0
type: QuestionComment
has text: @tripleee The user in this case has not idea what to do, besides clicking buttons in a UI. That is why I am focusing the question on integration and not friendliness

http://stackoverflow.com/q/52364815
upvote count: 9
has answer: http://stackoverflow.com/a/52365202
tagged with: python
has title: Any way to change color bar (cbar) in seaborn to a legend (for a binary heatmap)?
downvote count: 0
tagged with: seaborn
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91674270
linked to: http://stackoverflow.com/q/38836154
tagged with: matplotlib
type: Question
score: 9
has body: I'm using the heatmap in seaborn (sns.heatmap) to show a matrix of binary values true/false. It works just fine but the color bar as expected is showing a range of values from 0-1 (when in reality there are only two colors). Is there any way to change this to a legend showing the true/false colors? I couldn't find anything in the documentation https://seaborn.pydata.org/generated/seaborn.heatmap.html Example: import matplotlib.pyplot as plt import seaborn as sns import pandas as pd df = pd.DataFrame({'a':[False,True,False,True,True,True], 'b':[False,False,False,False,True,False], 'c':[False,True,True,False,True,True], 'd':[False,True,False,True,True,True], 'e':[False,True,True,False,False,True], 'f':[False,True,False,False,True,True]}) # Set up the matplotlib figure f, ax = plt.subplots(figsize=(13, 13)) # Generate a custom diverging colormap cmap = sns.diverging_palette(300, 180, as_cmap=True) # Draw the heatmap with the mask and correct aspect ratio _ = sns.heatmap(df, cmap=cmap, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5})
answer count: 1
accepted answer: http://stackoverflow.com/a/52365202
favorite count: 0

http://stackoverflow.com/a/52392393
type: Answer
answers question: http://stackoverflow.com/q/52392245
score: 1
upvote count: 1
has body: I don't know what exactly you want but this might work def swap_halves (s): '''Returns a new string in which the two halves of the spring have swapped''' i = int(len(s)/2) print(s[i:] + s[:i] ) swap_halves("good day sunshine ")
has comment: http://stackoverflow.com/comment/91730009
downvote count: 0
has comment: http://stackoverflow.com/comment/91730605

http://stackoverflow.com/q/52338706
has answer: http://stackoverflow.com/a/52338850
answer count: 3
downvote count: 1
tagged with: load
favorite count: 0
has comment: http://stackoverflow.com/comment/91625497
score: 38
type: UnansweredQuestion
tagged with: python
upvote count: 39
has answer: http://stackoverflow.com/a/55845426
has body: I already split the data into test and training set into the different folder. Now I need to load the patient data. Each patient has 8 images. def load_dataset(root_dir, split): """ load the data set numpy arrays saved by the preprocessing script :param root_dir: path to input data :param split: defines whether to load the training or test set :return: data: dictionary containing one dictionary ({'data', 'seg', 'pid'}) per patient """ in_dir = os.path.join(root_dir, split) data_paths = [os.path.join(in_dir, f) for f in os.listdir(in_dir)] data_and_seg_arr = [np.load(ii, mmap_mode='r') for ii in data_paths] pids = [ii.split('/')[-1].split('.')[0] for ii in data_paths] data = OrderedDict() for ix, pid in enumerate(pids): data[pid] = {'data': data_and_seg_arr[ix][..., 0], 'seg': data_and_seg_arr[ix][..., 1], 'pid': pid} return data But, the error said: File "/home/zhe/Research/Seg/heart_seg/data_loader.py", line 61, in load_dataset data_and_seg_arr = [np.load(ii, mmap_mode='r') for ii in data_paths] File "/home/zhe/Research/Seg/heart_seg/data_loader.py", line 61, in <listcomp> data_and_seg_arr = [np.load(ii, mmap_mode='r') for ii in data_paths] File "/home/zhe/anaconda3/envs/tf_env/lib/python3.6/site-packages/numpy/lib/npyio.py", line 372, in load fid = open(file, "rb") IsADirectoryError: [Errno 21] Is a directory: './data/preprocessed_data/train/Patient009969' It is already a file name, not a directory. Thanks!
has answer: http://stackoverflow.com/a/52338847
has title: "IsADirectoryError: [Errno 21] Is a directory: " It is a file
type: Question
tagged with: numpy

http://stackoverflow.com/comment/110054481
type: AnswerComment
type: Comment
has text: I noticed today that this is happening in my code too; based on how Linux multi-processes I'm guessing that this is happening because the RNG seed is copied over to all child processes as is. But, here's what I don't know: *when* is the RNG getting initialized? Is it right when we import sklearn?
comment on: http://stackoverflow.com/a/52315513
score: 0

http://stackoverflow.com/q/52386964
tagged with: python
type: UnansweredQuestion
tagged with: django
upvote count: 1
has title: Django Foreign key in another schema
type: Question
has answer: http://stackoverflow.com/a/52388040
has body: I have a MySQL database with 2 shemas (A &amp; B). My django app can read &amp; write into A. It can just read from B. My app managed all the tables in A. B already contains some data in a table (b). I want to add a one to one field between A and B. Something like this : class SchemaBTableB(models.Model): class Meta: managed = False db_schema = 'B' db_table = 'b' [...] class SchemaATableA(models.Model): class Meta: db_schema = 'A' db_table = 'a' id = models.OneToOneField( SchemaBTableB, on_delete=models.DO_NOTHING, primary_key=True ) [...] Unfortunately, db_schema does not exist. Does someone know a solution ?
tagged with: django-models
tagged with: mysql
has comment: http://stackoverflow.com/comment/91721652
has answer: http://stackoverflow.com/a/52390045
answer count: 2
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91721964
favorite count: 0

http://stackoverflow.com/q/52306061
has answer: http://stackoverflow.com/a/52308585
has comment: http://stackoverflow.com/comment/91559436
tagged with: pandas
has title: Python Sorting Pandas dataframe results in random results
type: Question
tagged with: python
has body: I am observing some random sort results for a dataframe that I intend to sort by dates in ascending order. For multiple runs, most of the runs returns the correct results but for a small number of runs, it returns an incorrect results. records_df = records_df.groupby(['YEAR','QUARTER','SUPPLIER_ID']).TRANSACTION_DATES.agg({'TRANSACTION_DATES' : lambda x: list(x.unique())}).reset_index() # This now sorts in date order records_df.sort_values(by=['TRANSACTION_DATES']) For most runs: TRANSACTION_DATES: [05-Sep-17, 06-Sep-17, 07-Sep-17] For some runs: Incorrect results is seen: TRANSACTION_DATES: [06-Sep-17, 07-Sep-17, 05-Sep-17] Why is that so since I am already enforcing a sort using sort_values?
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91563361
tagged with: dataframe
type: UnansweredQuestion

http://stackoverflow.com/a/52309622
answers question: http://stackoverflow.com/q/52309339
accepted answer of: http://stackoverflow.com/q/52309339
upvote count: 1
downvote count: 0
type: AcceptedAnswer
score: 1
has body: Use nested list comprehension: n = 1000 d = df['desc'].to_dict() In [117]: %timeit df['matches1'] = [[k for k, v in d.items() if x in v] for x in df.mfr] 80.8 ms ± 2.81 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) In [118]: %timeit df['matches'] = df.mfr.map(lambda x: df.index[df.desc.str.contains(x)].tolist()) 877 ms ± 27.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
type: Answer

http://stackoverflow.com/comment/91635876
score: 2
comment on: http://stackoverflow.com/q/52344942
has text: @YanivK. To add a bit to what Jon said: List comprehensions are basically an efficient and clean way to build new lists. While I understand the fact that you're wary of one-line solutions - and rightfully so, people often do overuse them - your case is an example where a one-line solution is not only okay but the best option.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91741278
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52380041
has text: Thank You @Simon for the help and information, however I am getting error while running this, I tried to run in the same way as you have mentioned: I am getting this error " AttributeError: 'Features' object has no attribute 'get_result'" .
type: AnswerComment

http://stackoverflow.com/q/52411503
has comment: http://stackoverflow.com/comment/91766982
has title: Convert image to base64 using python PIL
has comment: http://stackoverflow.com/comment/91766894
has comment: http://stackoverflow.com/comment/91767310
tagged with: python
has comment: http://stackoverflow.com/comment/91766931
has comment: http://stackoverflow.com/comment/91767389
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/91766874
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/76446531
upvote count: 5
answer count: 2
score: 5
has body: the following code is throwing an error Error with file: string argument expected, got 'bytes' I also tried using BytesIO but it threw an error about needed a format of string and not bytes. Very confusing. def im_2_b64(image): buffer = StringIO() image.save(buffer, format="JPEG") img_str = base64.b64encode(buffer.getvalue()) return img_str How can I convert an image to base64 using python 2.7? UPDATE Error with file: Object of type bytes is not JSON serializable Error with file: single positional indexer is out-of-bounds using BytesIO
has comment: http://stackoverflow.com/comment/91767426
has comment: http://stackoverflow.com/comment/91767167
downvote count: 0
has answer: http://stackoverflow.com/a/52411829
favorite count: 0

http://stackoverflow.com/a/52367142
downvote count: 1
has body: another way is... sorted([(x,len(x)) for x in c],key= lambda x: x[1])[-1][0]
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/52366997
type: Answer

http://stackoverflow.com/comment/91833706
type: AnswerComment
comment on: http://stackoverflow.com/a/52427847
has text: No problem! If you have any more questions about Featuretools, don't hesitate to ask. Me or another member of the team are always happy to answer questions.
type: Comment
score: 1

http://stackoverflow.com/q/52376698
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91698242
has answer: http://stackoverflow.com/a/52376842
tagged with: python
accepted answer: http://stackoverflow.com/a/52376842
has title: grouping a list to dictionary
downvote count: 2
type: Question
type: AnsweredQuestion
tagged with: python-2.7
has body: Version: python 2.7 Given list looks like this: [ ['a', '1'], ['b','2'], ['c','3'], ['a', '11'], ['b','2'], ['c','31'], ['a', '1'], ['b','22'], ['c','3d'] ] output should be in json format as follows: [{ "a": "1", "b": "2", "c": "3" }, { "a": "11", "b": "2", "c": "31" }, { "a": "1", "b": "22", "c": "3d" }] I tried lambdas, list( map(str.strip(), line.split(':') for line in liness) I was wondering how to get it grouped to get the above json format?
upvote count: 0
score: -2

http://stackoverflow.com/q/52346320
tagged with: django
tagged with: python
tagged with: celery
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52347083
type: Question
has title: Celery periodic task not accessing module variables
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52347083
has body: I have a celery well configured and working with django. On post_save signal, I send a new record to a set using a task and using another periodic task, I m trying to consume that set. from __future__ import absolute_import, unicode_literals from celery import shared_task class Data(): def __init__(self): self.slotshandler = set() global data data = Data() @shared_task def ProcessMailSending(): #This is a periodic task, running every 30 seconds global data #This variable is always empty here while slotshandler: slot_instance = slotshandler.pop() print("sending mail for slot } to {} by mail {}".format(slot_instance .id,slot_instance .user,slot_instance .user_mail)) @shared_task def UpdateSlotHandler(new_slot): #This is called by save_post django signal global data data.slotshandler.add(new_slot) #filling the set at each new record The problem is that this task doesn't see my newly added time slots. note that this django app is run on a micro service for sending reminder mails to users.
has comment: http://stackoverflow.com/comment/91639481

http://stackoverflow.com/comment/91725767
comment on: http://stackoverflow.com/a/52390226
type: AnswerComment
score: 0
type: Comment
has text: That way you find out that a solution exists but by using hashed pair-sums you won't find the items that actually comprise the solution.

http://stackoverflow.com/a/52421265
has comment: http://stackoverflow.com/comment/91786985
type: Answer
has comment: http://stackoverflow.com/comment/91787306
score: 3
answers question: http://stackoverflow.com/q/52421166
downvote count: 0
has body: The most basic answer for that would be: def commend1(): print "hi" def commend2(): print "hello" def cmd12(): commend1() commend2() #TKinter button = Button(root, command=cmd12)
has comment: http://stackoverflow.com/comment/91789861
upvote count: 3

http://stackoverflow.com/comment/91724397
type: Comment
score: 2
has text: You should avoid the for loop altogether, just use `data_cube = np.random.rand(10, 100, 100)`
type: AnswerComment
comment on: http://stackoverflow.com/a/52389576

series
tag name: series
tags question: http://stackoverflow.com/q/52324706
type: Tag
tags question: http://stackoverflow.com/q/52300258
tags question: http://stackoverflow.com/q/52328693
tags question: http://stackoverflow.com/q/52291519
tags question: http://stackoverflow.com/q/52297308
tags question: http://stackoverflow.com/q/52329220
tags question: http://stackoverflow.com/q/52357618
tags question: http://stackoverflow.com/q/52316689
tags question: http://stackoverflow.com/q/52421932
tags question: http://stackoverflow.com/q/52383122

http://stackoverflow.com/comment/91652724
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52352876
has text: Panasonic makes quite a few different models of cameras with varying features. Do you have some specific one in mind? Please, elaborate, details matter.
score: 0

http://stackoverflow.com/q/52368382
tagged with: pip
has title: No module named livelossplot
has comment: http://stackoverflow.com/comment/91685318
type: Question
score: 3
has comment: http://stackoverflow.com/comment/91683646
has comment: http://stackoverflow.com/comment/91681393
has comment: http://stackoverflow.com/comment/91686660
upvote count: 3
answer count: 2
has comment: http://stackoverflow.com/comment/91681539
favorite count: 0
type: UnansweredQuestion
has body: I have recently tried to make some realtime plots for my Ml models. I have installed livelossplot through this command: pip install livelossplot But, when trying to import the module in Jupyter, it returns error: ModuleNotFoundError: No module named 'livelossplot' Please, can someone help me?
tagged with: python
has comment: http://stackoverflow.com/comment/91680948
has answer: http://stackoverflow.com/a/52370132
has answer: http://stackoverflow.com/a/52370362
downvote count: 0

http://stackoverflow.com/comment/91790325
comment on: http://stackoverflow.com/q/52422865
type: Comment
type: QuestionComment
score: 0
has text: Please don't forget to mark any answer which solved your problem as an accepted. It'll help other people looking for a solution to find the answer.

http://stackoverflow.com/q/52362504
has answer: http://stackoverflow.com/a/52362793
type: Question
score: 0
tagged with: pandas
tagged with: axis
answer count: 1
has comment: http://stackoverflow.com/comment/91669419
has body: There are plethora of different solutions, mostly outdated, to address the addition of axis in matplotlib object, haven't got any of them working yet. I want to get date labels (either Months or Years) on the x axis. How to add the date annotations on the axis in Python with Pandas and Matplotlib? MWE import pandas as pd from matplotlib.pyplot import savefig a=pd.read_csv("test.csv") a.pivot(index='date', columns='group').plot() savefig("plot3.png") test.csv date,group,myval 2018-07-01,test1,999 2018-07-01,test2,523 2018-07-02,test1,3305 2018-07-02,test2,1290 2018-07-03,test1,9399 2018-07-03,test2,1827 2018-07-04,test1,6982 2018-07-04,test2,2391 2018-07-05,test1,4100 2018-07-05,test2,2081 2018-07-06,test1,0268 2018-07-06,test2,4834 2018-07-07,test1,9571 2018-07-07,test2,6369 2018-07-08,test1,3943 2018-07-08,test2,6483 where the time annotations are missing.
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52362793
tagged with: python
has title: Python: year or month on x axis with pyplot, pandas and matplotlib?
type: AnsweredQuestion
tagged with: matplotlib

http://stackoverflow.com/comment/91512989
type: Comment
type: QuestionComment
has text: @ShadowRanger I failed to pass python3 twice, Thank you very much.
score: 1
comment on: http://stackoverflow.com/q/52282245

http://stackoverflow.com/a/52329509
type: Answer
score: 2
downvote count: 0
has body: There are multiple issues here. Firstly, as Ninad points out, once your function hits the first return statement, it returns, and so it will never hit the rest of the code. It sounds like the thing you actually want to return is the work, not the force, so remove that first return statement: def get_work(mass, acceleration, distance): force = mass * acceleration work = force * distance return work Secondly, you're printing the result of calling the function, rather than assigning it to the Y variable. The thing you do assign is a reference to the function itself, not the return value. Remove that first print statement and assign instead: Y = get_work(train_mass, train_acceleration, train_distance) Finally, it seems that your print statement are in the wrong order. You want to print Y in the place of the work, and train_distance in the other place: print("The GE train does " + str(Y) + "Joules of work over" + str(train_distance) + "metres.") Note, that would be better done using format with placeholders: print("The GE train does {} Joules of work over {} metres.".format(Y, train_distance))
upvote count: 2
answers question: http://stackoverflow.com/q/52329458

http://stackoverflow.com/a/52423519
has body: Are you sure you're using the same Database / Collection source? Seems that you're saving results on another collection. I've tried to reproduce your problem and it works on my mongodb ( note that I'm using v4) EDIT: Would be nice to have the piece of code where you're defining "collection"
answers question: http://stackoverflow.com/q/52423426
score: 0
type: Answer

http://stackoverflow.com/comment/112081649
type: Comment
comment on: http://stackoverflow.com/a/52394612
has text: This also works for Ubuntu 20.04. Don't ask me how either.
type: AnswerComment
score: 0

http://stackoverflow.com/q/52405340
has comment: http://stackoverflow.com/comment/91754438
has answer: http://stackoverflow.com/a/52405433
accepted answer: http://stackoverflow.com/a/52405433
has title: Why doesn't python reclaim dangling threads?
tagged with: python
has comment: http://stackoverflow.com/comment/91765464
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91754556
tagged with: multithreading
tagged with: multiprocessing
type: Question
tagged with: threadpool
has comment: http://stackoverflow.com/comment/91757677
score: 0
has comment: http://stackoverflow.com/comment/91754525
answer count: 1
has body: Here is a snippet code of Python. As the stdout shows, active threads keep increasing until os complains that you have too much threads. Why doesn't python reclaim threads in thread_pool after all tasks are done? from multiprocessing.dummy import Pool as ThreadPool import threading count = 0 def fun(i): pass while True: count += 1 data = list(range(1, 100)) thread_pool = ThreadPool(30) thread_pool.map(fun, enumerate(data)) print(count, 'end', threading.active_count())

http://stackoverflow.com/a/52349897
type: Answer
has body: You're not returning anything in your else clause. You also don't need to pass split_order into your function: def split(data): if data: head, *tail = data # This is a nicer way of doing head, tail = data[0], data[1:] return {head: split(tail)} else: return {}
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/52349884
downvote count: 0

http://stackoverflow.com/comment/91535217
score: 1
type: AnswerComment
has text: @jezrael OK, added back in!
type: Comment
comment on: http://stackoverflow.com/a/52293506

http://stackoverflow.com/comment/91768469
type: QuestionComment
has text: @DeepSpace don't you think the regex you gave will consume all the other dates in between, ie in the example given, it will just match once, while in real sense there are to blocks of date-] to be matched?
comment on: http://stackoverflow.com/q/52412177
score: 0
type: Comment

http://stackoverflow.com/comment/91524767
score: 0
comment on: http://stackoverflow.com/q/52288408
has text: i wonder if you have some examples...are you suggesting to pull the override method mycallback out of the class?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52351100
type: AcceptedAnswer
score: 0
has body: The problem appears to be np.transpose(q,hess) instead of np.dot(np.transpose(q),hess), since the former is meaningless. I also suggest breaking up the htemp terms into different variables (like T1 = hess, T2= 1+q^T H q/p^Tq , so on) and then sum them up, so the code will more trackable.
answers question: http://stackoverflow.com/q/52351006
accepted answer of: http://stackoverflow.com/q/52351006
type: Answer

http://stackoverflow.com/comment/91569729
comment on: http://stackoverflow.com/q/52309430
type: QuestionComment
type: Comment
has text: @brunodesthuilliers Yes, I'm aware of that. But I rarely saw a 9-x difference in execution times within the same time complexity.
score: 3

python-import
tags question: http://stackoverflow.com/q/52311738
tag name: python-import
tags question: http://stackoverflow.com/q/52362195
tags question: http://stackoverflow.com/q/52422660
tags question: http://stackoverflow.com/q/52289683
tags question: http://stackoverflow.com/q/52334477
type: Tag
tags question: http://stackoverflow.com/q/52414566
tags question: http://stackoverflow.com/q/52314545
tags question: http://stackoverflow.com/q/52377223
tags question: http://stackoverflow.com/q/52309125
tags question: http://stackoverflow.com/q/52415373

http://stackoverflow.com/comment/91598893
score: 0
has text: @Rafalon it says 2
comment on: http://stackoverflow.com/q/52325941
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52419896
answer count: 2
has answer: http://stackoverflow.com/a/52434063
has comment: http://stackoverflow.com/comment/91791863
possible better answer: http://stackoverflow.com/a/52434063
has answer: http://stackoverflow.com/a/54645215
has title: How to clean packages compatible Python 2.7 + 3 to make them only Python 3.6 compatible?
favorite count: 0
has comment: http://stackoverflow.com/comment/91823037
upvote count: 3
downvote count: 2
tagged with: python
has body: For some projects, I'd like to stop supporting Python 2.7 (see http://python3statement.org/) to use only Python > 3.6 (or rather 3.5 + f-string, like Pypy v6.0). A first step could be to modify the setup.py file to get an explicit error if one try to use the package with a Python version without f-string. But then there is a lot of work to switch to pure Python 3.6 syntax and remove all the from __future__ import ..., try related to Python 2.7 support, future and/or six code and to replace in many places class MyClass(object) -> class MyClass: super(MyClass, self) -> super() "{}".format(foo) -> f"{foo}" I did this work for a code basically manually (actually I also automate some steps by processing the code with a Python script) and I really see the difference. The code is much less verbose now and globally much nicer. I'm sure that I forget many other nice simplifications that could be done, for example I now use a lot from pathlib import Path but these changes are much less direct. How would you transform a Python 2.7/3.6 compatible code to a clean Python 3.6 code? How can you avoid to do this boring work manually? Edit after the first answer I think a hypothetical internalization (which in many cases won't append) should not stop us from using f-strings, which are just cleaner (and slightly faster). I still think the modifications that I mentioned are reasonable.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91790908
has comment: http://stackoverflow.com/comment/91794847
accepted answer: http://stackoverflow.com/a/54645215
tagged with: f-string
score: 1
type: Question

http://stackoverflow.com/q/52406587
tagged with: python
has comment: http://stackoverflow.com/comment/91757903
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/52406671
type: Question
has comment: http://stackoverflow.com/comment/91756993
type: AnsweredQuestion
has body: I have a DataFrame like this: I want to split the note column and create 3 new columns that consist of the name, country and digit. The format of the note is the same just that there can be either first name or the full name there. I was trying to split and start from the right. Take in the digit, then the country and whatever is left should enter the "name" column. New DataFrame is meant to look like this:
has title: How to create new columns with custom split on python
accepted answer: http://stackoverflow.com/a/52406671
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91757090
linked to: http://stackoverflow.com/q/48352488
favorite count: 0
duplicate of: http://stackoverflow.com/q/48352488
tagged with: pandas

http://stackoverflow.com/comment/91790061
score: 0
type: Comment
type: QuestionComment
has text: Could you post minimal input dataframe and expected output dataframe, it would be easier to analyze. Please read [MCVE](https://stackoverflow.com/help/mcve).
comment on: http://stackoverflow.com/q/52417197

http://stackoverflow.com/a/52362890
has comment: http://stackoverflow.com/comment/91672545
has comment: http://stackoverflow.com/comment/102259369
type: Answer
has comment: http://stackoverflow.com/comment/91673719
has body: Edited after question's edit Will tf.train.get_global_step() increment global_step at every training step? No. The optimizer will take care of the increment, tf.train.get_global_step() only gets you the current variable defined to store the global step (if any was already defined). and affect the learning_rate accordingly? Yes, the learning rate schedule will internally get the value of the current global step and adjust the LR accordingly. Update: some clarification In TF there's a key difference between "variables" as are commonly intended in python (not tf.Variable()) and tensors (tf.Variable is a tensor). When you call global_step = tf.train.get_global_step() (assuming a global step was prevously defined somewhere) you get a Tensor object back, not an integer. The underlying idea is to separate the construction phase of the computation, where you describe the operations applied to the data, from the actual execution, where you feed the data and get results. This often causes confusion at first, but it's a key point of TF's programming model (at least until TF 2.0). If you want to get the current value of global_step, you need to evaluate the graph. Assuming you already have a tf.Session() defined, you either: step_value = sess.run(global_step) or alternatively: step_value = global_step.eval(session=sess) This is done internally from the LR schedule. At each step, it will get the current value of the global step and calculate the LR from it with the given parameters. Similarly, the optimizer internally will take care of updating the current global step value at each step, so unless you need the value for logging/debugging, you normally wouldn't explicitly evaluate global_step yourself.
accepted answer of: http://stackoverflow.com/q/52362797
has comment: http://stackoverflow.com/comment/91673828
answers question: http://stackoverflow.com/q/52362797
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91673203
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91672311

http://stackoverflow.com/comment/91616918
has text: Alternatively, make sure S3 sets the caching properties to short period of time (e.g. 10 min) so browsers fetch the newest version at least within this time. This goes at the expense of loading time, since users staying longer on your website will reload existing assets.
score: 0
comment on: http://stackoverflow.com/q/52331396
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52401450
type: UnansweredQuestion
has body: Is there a way to handle table name and field name at run time ? I have found references to an insert method that takes a dict as argument But assuming rd is a dict with 10 entries, key = name of the field, value = value to be inserted, the following code will fail db.OrdersFull.insert(rd) With error :TypeError: insert() takes exactly 1 argument (2 given) 1)any clue? 2)with this solution, the table name (OrdersFull) must still be known at development time, any way to insert into a table whose name is known at run time only ? 3)Is there a place where one can found reference information for available web2py API calls ?
downvote count: 0
score: 1
type: Question
tagged with: python
tagged with: web2py
favorite count: 0
has title: web2py insert with variable table and field name e.g. with dict
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/52409991

http://stackoverflow.com/comment/91727085
type: AnswerComment
score: 0
type: Comment
has text: @pault I'm creating a solution relative to OP level, im assuming using an import and map is out of the context of what someone with 70 rep understand and deploy immediately
comment on: http://stackoverflow.com/a/52390893

http://stackoverflow.com/comment/91659801
score: 1
comment on: http://stackoverflow.com/q/52357594
type: Comment
type: QuestionComment
has text: Sorry for forgetting mentioned that m is a global variable. @yar

http://stackoverflow.com/q/52409529
answer count: 0
downvote count: 0
has body: I'm trying to replace empty cells by certain count for each group in the data. Say data looks like the table below. In the first group, length of strings is 5 and hence row 3 should be filled with "NEW_STRING" across all 5 columns. However for group 2, length of strings is 3 and row 7 should be filled with "NEW_STRING" across the first 3 columns. GROUP | col_1 | col_2 | col_3 | col_4 | col_5 ------------------------------------------------ GROUP_1 | STR_1 | STR_2 | STR_3 | STR_4 | STR_5 GROUP_1 | STR_1 | STR_2 | STR_3 | STR_4 | STR_5 GROUP_1 | | | | | GROUP_1 | STR_1 | STR_2 | STR_3 | STR_4 | STR_5 GROUP_2 | STR_1 | STR_2 | STR_3 | | GROUP_2 | STR_1 | STR_2 | STR_3 | | GROUP_2 | | | | | Output should be like, GROUP | col_1 | col_2 | col_3 | col_4 | col_5 ------------------------------------------------- GROUP_1 | STR_1 | STR_2 | STR_3 | STR_4 | STR_5 GROUP_1 | STR_1 | STR_2 | STR_3 | STR_4 | STR_5 GROUP_1 | NEW_STR|NEW_STR|NEW_STR|NEW_STR|NEW_STR GROUP_1 | STR_1 | STR_2 | STR_3 | STR_4 | STR_5 GROUP_2 | STR_1 | STR_2 | STR_3 | | GROUP_2 | STR_1 | STR_2 | STR_3 | | GROUP_2 | NEW_STR|NEW_STR|NEW_STR| | Kind help is greatly appreciated!!!
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91826403
type: Question
has title: replace empty cells by specific length in Python Pandas
upvote count: 1
favorite count: 0
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/91653935
has text: So, would it be a list of arrays that have different sizes?
comment on: http://stackoverflow.com/q/52354593
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/52324651
type: Answer
answers question: http://stackoverflow.com/q/52324480
has body: As I commented above, you will realize that you are appending the object to itself, thus we need to append the copy of the object and not itself. This ensures the pointers to the object and its copy are different. Hence after updating the object, we still maintain its previous copy class Agent: def __init__(self): self.properties = [] def add_new_property(self, property_type, purchase_type): from copy import copy self.prop_type = property_type self.pur_type = purchase_type self.properties.append(copy(self)) def print_properties(self): for property in self.properties: print("Property Type: " + property.prop_type, end = '\t\t') print("Purchase Type: " + property.pur_type) a = Agent() a.add_new_property("house", "purchase") a.add_new_property("apt", "rental") a.print_properties() Property Type: house Purchase Type: purchase Property Type: apt Purchase Type: rental
score: 0

http://stackoverflow.com/q/52391631
score: 0
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/41836011
tagged with: python
accepted answer: http://stackoverflow.com/a/52391742
type: AnsweredQuestion
has body: I am trying to loop through my json and only getting the feature array of objects and getting all the objects but I can't seem to understand where I doing wrong in my python code. Here is my code: I have looked at these questions for advice but it doesn't seem to work. TypeError: string indices must be integers error when parsing Json with Python jsonData = operationalLayers = None #for testing purposes, parse from a json file if Web_Map_as_JSON != '': jsonData = json.loads(Web_Map_as_JSON) operationalLayers = jsonData["operationalLayers"] arcpy.AddMessage("We have valid json data") else: with open('json/WLA-FRI-AY-14-subset.json') as data: jsonData = json.load(data) operationalLayers = jsonData["operationalLayers"] print "We parsed json data from a file" # looping thru only graphics-operation-layer and its sub layers # and add attributes for each features on the layout for ol in operationalLayers: #hard code the first feature layer if (ol["id"] == "ParcelRouteEditingTest_1259"): if (ol.has_key('featureCollection')): fcol = ol["featureCollection"] if (not fcol.has_key('layers')): continue lyrs = fcol["layers"] #loop through layer for i in lyrs: # feature set data on the graphic layer fs = i["featureSet"] # store attributes for easy access for featureData in fs: featureDataObj = featureData[1]["features"] print featureDataObj # queryURL = '{0}/query'.format(i['url']) # arcpy.AddMessage(queryURL) # getQuery = requests.get(queryURL) # if(getQuery.status_code == 200): # fs = getQuery.json() updateLayoutElementWithFeatureAttributes(feature_data_obj, None, pdfPaths) Here is the structure of the json data: Error: Traceback (most recent call last): File "C:\Workspace-TT\pythonprint\customPrint.py", line 299, in &lt;module&gt; featureDataObj = featureData[1]["features"] TypeError: string indices must be integers
upvote count: 2
tagged with: http://stackoverflow.com/tag/json
downvote count: 2
has comment: http://stackoverflow.com/comment/91728376
type: Question
tagged with: arcpy
has answer: http://stackoverflow.com/a/52391742
has title: TypeError: string must be indices on JSON looping through feature array of objects in arcpy

dm
tag name: dm
type: Tag
tags question: http://stackoverflow.com/q/52343245

http://stackoverflow.com/q/52398849
type: Question
upvote count: 2
tagged with: pipeline
tagged with: scikit-learn
has body: I try to use Scikit-Learn's Pipeline function to organize our transformers and estimator, and having problem with building a pipeline that combines one_hot_transformer with a LinearRegression() estimator. It is challenging to connect the following ones from sklearn.preprocessing import OneHotEncoder cat_feats = np.array([[1,10],[2,20],[3,10],[4,20],[3,10],[2,20],[1,10]]) OneHotEncoder(sparse=False).fit_transform(cat_feats) one_hot_transformer = OneHotEncoder(sparse=False).fit_transform(X,y) from sklearn.pipeline import Pipeline linear_est = Pipeline([one_hot_transformer], LinearRegression()) linear_est.fit(X,y) predicted = linear_est.predict(X) grader.score('intro_ml__linear_model', linear_est.predict)
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91742332
favorite count: 0
tagged with: jupyter-notebook
answer count: 0
type: UnansweredQuestion
has title: Using Scikit-Learn's pipelines to combine a transformers and estimator
score: 1

http://stackoverflow.com/q/52426982
type: Question
has answer: http://stackoverflow.com/a/52427485
has comment: http://stackoverflow.com/comment/91797690
score: 0
has answer: http://stackoverflow.com/a/52427543
has title: How to use Django imports in a django app without starting the app
answer count: 3
has comment: http://stackoverflow.com/comment/91797386
has comment: http://stackoverflow.com/comment/91797770
has answer: http://stackoverflow.com/a/52427140
has body: Let's say my main app structure is like App - - __init__.py - xyz.py API - - __init__.py - abc.py Custom- - __init__.py - s1.py - s2.py Normally when running django I can do from API.abc import function from s1.py file. However when I run s1 file separately it gives import errors. So how can I make existing imports work.
has comment: http://stackoverflow.com/comment/91797320
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91797254

http://stackoverflow.com/comment/91654240
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52354697
score: 1
has text: Good eye. This also doesn't take punctuation into account, but neither does the posters answer

http://stackoverflow.com/comment/91591471
comment on: http://stackoverflow.com/q/52304492
has text: Ok so if u need a deeper explanation then I will provide it. They own a premium account but as u mentioned custom launcher is a source of leakage and we also to want to use new nicknames as the accounts where bought 6 yrs ago. Furthermore it is going to be a modpack, so using a custom launcher will make it easier for me to send them updates (it's already built compares hashes and downloads outdated files). So pls stop posting trash in the comments because people like u make forums useless. It's my last reply to u, no more time wasted. Have a nice day!! ;))
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91625764
has text: As far as I know that's perfectly fine (and indeed something you see quite often). The key point is that you're not actually altering the content of `d.keys()`, which you are when you add or delete a key - and this is almost certainly what the warning in the docs is about.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52339204

http://stackoverflow.com/comment/91711453
score: 0
type: AnswerComment
has text: two improvements: link to python 3 classes, python 2 will be dropped by 2020 (and the Q is tagged with 3.x). I'd change to: "special chars 'might' cause trouble" since I've been using unicode variable names in python to write more illustrative examples. Maybe expand on why they cause trouble in some cases.
type: Comment
comment on: http://stackoverflow.com/a/52383182

http://stackoverflow.com/comment/91804750
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52429607
has text: Link the C code against `ncursesw`, and it'll work. (Although ncursesw adds new types and interfaces for wide characters, it also adds UTF-8 multibyte support to the standard ncurses functions.)

http://stackoverflow.com/comment/105656302
score: 1
comment on: http://stackoverflow.com/a/59485636
type: AnswerComment
type: Comment
has text: Thanks! Is there any way to automatically move the focus back to the editor after sending the text to IPython?

http://stackoverflow.com/q/52305670
has answer: http://stackoverflow.com/a/52306199
tagged with: indexing
type: AnsweredQuestion
has title: tensor extension of one-dimensional index into multi-dimensional index
type: Question
has body: I wanna make a function of a multi-dimensional array from one-dimensional index array with any dimension. For example, I have x=np.array([1,2,3]) def extend_array(x,d) If I put d=2, then the resulting array is [[1,1], [1,2], [1,3], [2,1], [2,2], [2,3], [3,1], [3,2], [3,3]] or input can be (n,d) instead of (x,d) so that n refers np.array(range(1,n+1)) I think there is a function for this, but I cannot find one. Would you please help me with this problem?
score: 0
has comment: http://stackoverflow.com/comment/91560987
answer count: 1
tagged with: arrays
accepted answer: http://stackoverflow.com/a/52306199
tagged with: python

http://stackoverflow.com/comment/91529061
comment on: http://stackoverflow.com/q/52290477
type: QuestionComment
has text: Can you install `conda` as a user then use `conda` environments to install `matplotlib`?
type: Comment
score: 0

http://stackoverflow.com/comment/91787306
comment on: http://stackoverflow.com/a/52421265
score: 1
type: AnswerComment
type: Comment
has text: Yup, thanks. edited!

http://stackoverflow.com/comment/91747497
comment on: http://stackoverflow.com/a/52401753
score: 0
type: AnswerComment
type: Comment
has text: Many thank, yes the answer's are very helpful. I know that python 3.x is really better than python 2.x. But I can at the moment not use an higher python version (because it is included in applications of dSPACE)

http://stackoverflow.com/q/52353383
tagged with: python
has body: Here's my code. import time import threading import multiprocessing num1 = 0 num2 = 0 def take_numbers(num1,num2): print('Enter the numbers:') for n in range(0,5): time.sleep(0.2) num1 = input('Enter first number') num2 = input('Enter second number') def add_num(num1,num2): for n in range(0,5): time.sleep(0.2) return num1+num2 t1 = threading.Thread(target=take_numbers, args=(num1,num2)) t2 = threading.Thread(target=add_num, args=(num1,num2)) t1.start() t2.start() t1.join() t2.join() I need an output where it should stop when time.sleep(0.2) is called and perform addition with existing number and then again go to take_numbers function and get new numbers. I am only able to input the numbers but not getting an output. note:there is no problem with indentation. Please help!! Thanks
has comment: http://stackoverflow.com/comment/91651884
score: -1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91651597
has comment: http://stackoverflow.com/comment/91652236
accepted answer: http://stackoverflow.com/a/52354378
downvote count: 1
linked to: http://stackoverflow.com/q/6893968
type: Question
has comment: http://stackoverflow.com/comment/91652268
has title: addition of two numbers to be done in parallel in python
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52354378
favorite count: 0

http://stackoverflow.com/q/52350165
has body: This code worked ok in Python 3.5.2. in the same machine. In Python 3.7.0 it hangs up when you try to get the Appointment Properties Start or End. It hangs up just with the first request for Start or End. No error message appears. Tested under Windows 10, both in Command Console and with Jupyter Notebook. Any advice or other libraries needed to include? import win32com.client import datetime outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") calendar = outlook.GetDefaultFolder(9) appointments = calendar.Items appointments.Sort("[Start]") appointments.IncludeRecurrences = "True" #This block restrict the time range. Doesn't change the hang up begin = datetime.date(2018, 9, 1) #year, month, day end = datetime.date(2018, 10, 1) print(f"Activities from: {begin}, to: {end}") restriction = "[Start] &gt;= '" + begin.strftime("%d/%m/%Y") + "' AND [End] &lt;= '" +end.strftime("%d/%m/%Y") + "'" print("restriction:", restriction) restrictedItems = appointments.Restrict(restriction) # The problem arise accessing as a unique item appointment = restrictedItems[1] print(appointment.Subject) print(appointment.Organizer) print(appointment.Start) print(appointment.End) # Also hangs up inside a loop of appointments for appointment in restrictedItems: print(appointment.Subject) print(appointment.Organizer) print(appointment.Start) print(appointment.End)
type: AnsweredQuestion
score: 2
has title: Python 3.7 hangs up getting Outlook Calendar Start or End Properties of an Appointment Item
accepted answer: http://stackoverflow.com/a/52593453
tagged with: calendar
has comment: http://stackoverflow.com/comment/101536456
type: Question
tagged with: outlook
has comment: http://stackoverflow.com/comment/91658596
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52593453
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python

http://stackoverflow.com/comment/91799278
comment on: http://stackoverflow.com/q/52427926
score: 0
has text: its giving n3 as last elements of both the list elements of the z list. it should give n3 as last element of first list and n4 as last element of second list of z list
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91637056
type: QuestionComment
comment on: http://stackoverflow.com/q/52345424
has text: Okay, good to know. Thanks for the tip. How would you do it instead?
score: 0
type: Comment

http://stackoverflow.com/q/52337779
has answer: http://stackoverflow.com/a/54138354
tagged with: python
downvote count: 0
tagged with: telethon
type: AnsweredQuestion
has title: Find session id with telethon and kill the session
score: 3
possible better answer: http://stackoverflow.com/a/69716400
has answer: http://stackoverflow.com/a/52347320
has answer: http://stackoverflow.com/a/69716400
type: Question
accepted answer: http://stackoverflow.com/a/54138354
favorite count: 0
has body: Before I ask this question I checked here. I want to kill all other sessions except the session with which I am connecting now. Based on the telethon api I used all_sessions = client(GetAuthorizationsRequest()).to_dict() and I get this result: { '_': 'Authorization', 'api_id': ..., 'app_name': '...', 'app_version': '4.1.4', 'country': 'Unknown', 'date_active': ..., 'date_created': ..., 'device_model': 'SamsungSM-G920F', 'flags': 0, 'hash': ..., 'ip': '...', 'platform': 'Android', 'region': '', 'system_version': 'SDK 23' } I want to kill this session but I dont know what is te session id mentioned in the linke above(telethon API docs). I tried with these to commands: client(DestroySessionRequest(api_id)) client(DestroySessionRequest(hash)) But not only no sessions remove but also no response from the apis and the commands waiting and waiting for the response with no error or no exceptions.How can I kill the session?
upvote count: 3
answer count: 3
tagged with: telegram

http://stackoverflow.com/comment/91581617
type: AnswerComment
has text: sorry, request take 60ms
type: Comment
comment on: http://stackoverflow.com/a/52294829
score: 0

http://stackoverflow.com/a/52304444
type: AcceptedAnswer
has body: Originally I htought I had Fixed this by adding the buffered parameter to the cursor. cursor = db.cursor(buffered=True) THIS IS NOT TRUE. I realised as I was debugging I had a watch variable on cursor.fetchall(). This was running the command ahead of when it being called in the code, meaning by the time it reached the code there we no results to be fetched. Solution: Do not have watch variables of cursor.fetchall()
answers question: http://stackoverflow.com/q/52293504
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52293504
upvote count: 1

http://stackoverflow.com/q/52345633
score: 0
has title: Why is the calculation from my code giving me different answers from calculators?
answer count: 1
has comment: http://stackoverflow.com/comment/91637131
has body: I am using Python 3.6.0. I noticed that the output from my code and giving answers different from calculators and I could not find out why. L = [5,5,2,3,4,5] for i in range(len(L)): L[i] *= 1000 for i in range(len(L)): if i == 0: L[i] = int(L[i]*0.6+L[i+1]*0.2) if i &lt; (len(L)-1) and i != 0: L[i] = int(L[i-1]*0.2+L[i]*0.6+L[i+1]*0.2) print(L) The output of the code is: [4000, 4200, 2640, 3128, 4025, 5000] However, there seems to be calculation problem when i is above 0. For example: When i is 2, L[2] = int(L[1]*0.2+L[2]*0.6+L[3]*0.2) = 2800 but the output from the program is 2640. Where is the source of error? I would greatly appreciate if anybody can assist me with this.
has comment: http://stackoverflow.com/comment/91637594
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52345732
accepted answer: http://stackoverflow.com/a/52345732
type: Question

http://stackoverflow.com/q/52366558
tagged with: pandas
favorite count: 0
has title: Natural sort a data frame column in pandas
has body: I would like to apply a natural sort order to a column in a pandas DataFrame. The columns that I would like to sort might contain duplicates. I have seen the related Naturally sorting Pandas DataFrame question, however it was concerning sorting the index, not any column. Example df = pd.DataFrame({'a': ['a22', 'a20', 'a1', 'a10', 'a3', 'a1', 'a11'], 'b': ['b5', 'b2', 'b11', 'b22', 'b4', 'b1', 'b12']}) a b 0 a22 b5 1 a20 b2 2 a1 b11 3 a10 b22 4 a3 b4 5 a1 b1 6 a11 b12 Natural sort column a: a b 0 a1 b11 1 a1 b1 2 a3 b4 3 a10 b22 4 a11 b12 5 a20 b2 6 a22 b5 Natural sort column b: a b 0 a1 b1 1 a20 b2 2 a3 b4 3 a22 b5 4 a1 b11 5 a11 b12 6 a10 b22
score: 6
tagged with: python
duplicate of: http://stackoverflow.com/q/29580978
type: AnsweredQuestion
downvote count: 0
tagged with: natural-sort
tagged with: dataframe
has answer: http://stackoverflow.com/a/52366799
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52366968
accepted answer: http://stackoverflow.com/a/52366968
upvote count: 6
linked to: http://stackoverflow.com/q/29580978
possible better answer: http://stackoverflow.com/a/52366799

http://stackoverflow.com/comment/91746086
score: 0
type: Comment
type: QuestionComment
has text: Thank you @rcgldr! I think my problem is even further upstream: don't know how to solve these memory errors. Do you have some code example in python I can use?
comment on: http://stackoverflow.com/q/52391412

http://stackoverflow.com/comment/91585931
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52319296
has text: You can't have duplicate keys in a dictionary. You probably want a dictionary of lists if you don't want to lose data
score: 3

http://stackoverflow.com/a/52281859
answers question: http://stackoverflow.com/q/52281671
has comment: http://stackoverflow.com/comment/112279510
type: AcceptedAnswer
upvote count: 29
type: Answer
has body: You could nest the dictionaries as follows: jsondata = {} agent={} content={} agent['agentid'] = 'john' content['eventType'] = 'view' content['othervar'] = "new" jsondata['agent'] = agent jsondata['content'] = content print(json.dumps(jsondata)) Output: print {"content": {"eventType": "view", "othervar": "new"}, "agent": {"agentid": "john"}}
downvote count: 0
score: 29
accepted answer of: http://stackoverflow.com/q/52281671

http://stackoverflow.com/comment/91692709
has text: I think we need more context on this. Presumably the attributes are immutable? What is `constant`?
type: QuestionComment
comment on: http://stackoverflow.com/q/52373984
score: 0
type: Comment

http://stackoverflow.com/q/52329755
upvote count: 0
answer count: 1
score: -1
has comment: http://stackoverflow.com/comment/91606493
has body: I am trying to return the value of the horizontal component of force based on the user's inputs, and I have this, but keep getting the same error message that I 'can't multiply sequence by non-int of type 'float'', and have run out of ideas as to what is wrong with it. from math import sin, cos, pi, sqrt, radians F = input('Enter your Force') theta = input('Enter your angle') F = float(F) theta = radians(float(theta)) def find_hforce(F, theta): if F != '' and theta != '': Fhorizontal = float(F*cos(theta)) equationFhorizontal = 'Fcos(',theta,')' else: Fhorizontal = '' return (equationFhorizontal, Fhorizontal) if unknown == 'horizontal force': equationFhorizontal, Fhorizontal = find_hforce(F, theta) if Fhorizontal != '': print ('The horizontal component of force is:', Fhorizontal, 'N') print ('The equation you needed to use is:', equationFhorizontal)
has answer: http://stackoverflow.com/a/52330285
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91606313
type: AnsweredQuestion
has title: Keep getting the same error message, can't multiply sequence by non-int of type float
accepted answer: http://stackoverflow.com/a/52330285
has comment: http://stackoverflow.com/comment/91606217
downvote count: 1
type: Question

http://stackoverflow.com/comment/91572796
has text: Is `score_c` also negative?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52311416

http://stackoverflow.com/q/52405594
type: UnansweredQuestion
has title: python socket protocol not support
score: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52437803
has comment: http://stackoverflow.com/comment/93892098
type: Question
tagged with: sockets
tagged with: can-bus
has comment: http://stackoverflow.com/comment/91795283
tagged with: python
has comment: http://stackoverflow.com/comment/91929623
upvote count: 2
has comment: http://stackoverflow.com/comment/91802748
answer count: 1
has comment: http://stackoverflow.com/comment/91755162
has comment: http://stackoverflow.com/comment/91795057
has body: I useed python-can-isotp on RaspberryPi3, and test it with example code, but I got an error. My simple code: import isotp s = isotp.socket() s2 = isotp.socket() # Configuring the sockets. s.set_fc_opts(stmin=5, bs=10) #s.set_general_opts(...) #s.set_ll_opts(...) s.bind("vcan0" rxid=0x123 txid=0x456) # We love named parameters! s2.bind("vcan0", rxid=0x456, txid=0x123) s2.send(b"Hello, this is a long payload sent in small chunks of 8 bytes.") print(s.recv()) ERROR: File "/usr/local/opt/python-3.7.0/lib/python3.7/socket.py", line 151, in __init__ _socket.socket.__init__(self, family, type, proto, fileno) OSError: [Errno 93] Protocol not supported Can someone please help me find the solution to the problem?

http://stackoverflow.com/comment/91758118
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52405498
type: AnswerComment
has text: Ok, I re-edited the message in order to have both answers :-)

http://stackoverflow.com/a/52325925
upvote count: 1
has body: Use merge with replace 0 by fillna, if necessary sort_index and trne transpose by set_index with T: #if need inner join df3 = dfa.merge(df2,on='SN').fillna(0).sort_index().set_index('SN').T #if need outer join df3 = dfa.merge(df2,on='SN', how='outer').fillna(0).sort_index().set_index('SN').T print (df3) SN 456123 789456 123789 A_x 10.0 15.0 16.0 B_x 23.0 45.0 62.0 C_x 48.0 98.0 55.0 A_y 10.0 15.0 68.0 B_y 19.0 45.0 77.0 C_y 48.0 0.0 55.0 Another solution with outer join with concat: df3 = (pd.concat([df1.set_index('SN'), df2.set_index('SN')], axis=1, keys=('x', 'y')).T.fillna(0)) #flatten MultiIndex df3.index = [f'{j}_{i}' for i, j in df3.index] print (df3) SN 456123 789456 123789 A_x 10.0 15.0 16.0 B_x 23.0 45.0 62.0 C_x 48.0 98.0 55.0 A_y 10.0 15.0 68.0 B_y 19.0 45.0 77.0 C_y 48.0 0.0 55.0
answers question: http://stackoverflow.com/q/52325851
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/91658325
comment on: http://stackoverflow.com/a/52352744
type: Comment
score: 0
type: AnswerComment
has text: Can I suggest you restructure your answer to put the end-of-subject-string information first, followed by the more general information about zero-width matches? I'll gladly accept your answer then. Personally, the part I'm still unclear on is the _design rationale_ for this behavior: when would it ever be _useful_ to report an empty match _after_ the input string has been fully matched? It seems to me that when you're looking for repeated, non-overlapping matches, the more sensible approach is to not even _attempt_ another match in that case.

http://stackoverflow.com/comment/91671584
comment on: http://stackoverflow.com/q/52358784
score: 0
has text: https://github.com/BVLC/caffe/blob/windows/README.md
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52391757
tagged with: neural-network
tagged with: keras
score: 0
has title: input_shape of an 8x8 board game to a Neural Network with Keras
answer count: 1
has comment: http://stackoverflow.com/comment/91731288
accepted answer: http://stackoverflow.com/a/52394041
tagged with: machine-learning
linked to: http://stackoverflow.com/q/52089601
tagged with: python
type: AnsweredQuestion
has body: I am very green behind the ears when it comes to creating a NN. Right now I am receiving the following error: ValueError: Error when checking : expected dense_1_input to have 3 dimensions, but got array with shape (8, 8) Background: I am using an 8x8 board this is how I am initializing it: self.state = np.zeros((LENGTH, LENGTH)) Here is the code where I build my Model: def build_model(self): #builds the NN for Deep-Q Model model = Sequential() model.add(Dense(24,input_shape = (LENGTH, LENGTH), activation='relu')) model.add(Flatten()) model.add(Dense(24, activation='relu')) model.add(Dense(self.action_size, activation = 'linear')) model.compile(loss='mse', optimizer='Adam') return model I figured since the shape of the board is (8,8) that the input_size should be the same. Not sure what I am doing wrong? Just in case this is helpful: The game I have made is super simple that involves 5 pieces on the board: player1 has 1 piece and can move forward and backward diagonally only 1 step player2 has 4 pieces and can only move forward from their position diagonally 1 step The objective for player1 is to get to the other side of the board The objective for player2 is to trap player 1 so he cannot move Any help would be greatly appreciated!
linked to: http://stackoverflow.com/q/44747343
has comment: http://stackoverflow.com/comment/91729272
type: Question
has comment: http://stackoverflow.com/comment/91732524
has answer: http://stackoverflow.com/a/52394041

http://stackoverflow.com/a/52433450
upvote count: 18
type: Answer
has body: A slightly better method, following the documentation: from matplotlib.font_manager import FontProperties for (row, col), cell in table.get_celld().items(): if (row == 0) or (col == -1): cell.set_text_props(fontproperties=FontProperties(weight='bold'))
answers question: http://stackoverflow.com/q/52429323
downvote count: 0
score: 18

http://stackoverflow.com/a/52281515
score: 4
type: AcceptedAnswer
has body: You may be searching for solutions to handle imbalanced data. Here are some of methods you can follow. Resampling: (Over sampling of minority class data points or Under sampling of majority class data points) In your case, class 1 is minority class Giving more weightage to minority class depending on the ratio of class imbalance Choose right performance metric. But still if you need 30k of class 1 &amp; class 0 data points, try this: X_train_sample_class_1 = X_train[X_train['third_column_name'] == 1][:30000] X_train_sample_class_0 = X_train[X_train['third_column_name'] == 0][:30000] Now you can combine X_train_sample_class_1 &amp; X_train_sample_class_0 to form a new dataset which has balanced dataset
type: Answer
accepted answer of: http://stackoverflow.com/q/52279834
upvote count: 4
answers question: http://stackoverflow.com/q/52279834
downvote count: 0

http://stackoverflow.com/q/52347490
has answer: http://stackoverflow.com/a/52347567
tagged with: python
tagged with: text
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/52347567
has comment: http://stackoverflow.com/comment/91640595
has title: How to use ".endswith" within a list of strings in Python?
downvote count: 1
has answer: http://stackoverflow.com/a/52347590
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/120858976
answer count: 2
has comment: http://stackoverflow.com/comment/91641066
has comment: http://stackoverflow.com/comment/91640391
accepted answer: http://stackoverflow.com/a/52347590
favorite count: 0
tagged with: character
has body: I'm struggling with this task that i've been given in Python, and it's about modifying text from a given text file (read mode, not write). Here's a piece of my code: file = open("fileName") suffix_list:[] for e in file: elements=e.split() result=elements.endswith("a") suffix_list.append(result) And then I want to print the length of the list with suffixes: print(len(suffix_list)) Instead i get this error: " 'list' object has no attribute 'endswith' " I'm really not sure whats wrong here, can someone please help?

http://stackoverflow.com/q/52422866
answer count: 3
possible better answer: http://stackoverflow.com/a/52423120
has title: How to find the maximum consecutive occurrences of a number in python
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91789389
accepted answer: http://stackoverflow.com/a/52422935
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52423120
has answer: http://stackoverflow.com/a/52422935
score: 1
has answer: http://stackoverflow.com/a/52422957
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/36441521
has body: I want to find out the maximum number of consecutive occurrences of a number in python. I am using the following code from stack overflow. from itertools import groupby b= [1,2,45,55,5,4,3,2,5,5,6,5456,5456,5456,7,67,6,6] print(b) def occurrence(): occurrence, num_times = 0, 0 for key, values in groupby(b, lambda x : x): val = len(list(values)) if val &gt;= occurrence: occurrence, num_times = key, val return occurrence, num_times occurrence, num_times = occurrence() print("%d occurred %d times" % (occurrence, num_times)) I get the following answer: 5 occurred 2 times The answer should be 5456 because it occurred 3 times. Can any body help me to resolve the issue?
has comment: http://stackoverflow.com/comment/115721745

http://stackoverflow.com/comment/91552479
score: 0
has text: What are you trying to do?
type: Comment
comment on: http://stackoverflow.com/a/52287784
type: AnswerComment

http://stackoverflow.com/q/52345792
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52347216
accepted answer: http://stackoverflow.com/a/52347216
tagged with: tkinter
type: AnsweredQuestion
score: 1
type: Question
upvote count: 2
has title: Why does this create 2 windows?
answer count: 1
downvote count: 1
has body: I have a program with a function that takes times from an API and returns those times if called. The following code should create a window with Tkinter and display the time resp() returns. As the times from API always change, it updates those times every 2 seconds. L=Label(text=resp(), font=("Arial Bold", 35)) L.grid(row=1, column=1) # Call this function where the value of your variable/number changes def ChangeValue(): y=resp() root.config(text=y) print("Value Changed") root.after(2000,lambda :ChangeValue()) root=Tk() root.update() root.after(2000,lambda :ChangeValue()) root.grid_rowconfigure(0, weight=1) root.grid_columnconfigure(0, weight=1) root.title("Abfahrt nächster Zug") root.geometry('1920x1080') root.mainloop() If I run this code, it creates a small window that contains resp - formatted like it is being told to in line 1. But that window isn't 1920x1080 like it should be. But it creates a second window that is 1920x1080 and doesn't contain any text. What I want is a 1920x1080 window that contains resp (font = arial, fontsize = 35)

http://stackoverflow.com/q/52334135
tagged with: anaconda
score: 0
answer count: 2
has title: Spyder not finding modules installed with anaconda
linked to: http://stackoverflow.com/q/29077826
type: UnansweredQuestion
tagged with: spyder
tagged with: python
has answer: http://stackoverflow.com/a/52334173
has body: I have a newly installed Anaconda and tried to run an old code that uses scipy, numpy and os using Spyder 3.2.6. and get an error. When trying to import numpy from the IPythoin console I get import numpy as np Traceback (most recent call last): File "&lt;ipython-input-4-0aa0b027fcb6&gt;", line 1, in &lt;module&gt; import numpy as np ModuleNotFoundError: No module named 'numpy' The os module however does get imported and works. I tried running python importing both scipy and numpy and I don't have any issue. I'm running just one Anaconda environment, so there's no mistake there.
has answer: http://stackoverflow.com/a/53723182
type: Question

http://stackoverflow.com/q/52287575
type: Question
has title: How can I get rid of this error based on list index out of range in python selenium
score: 0
has body: I am scraping data from amazon website.The aim is to get the product title and the correspnding ASIN(Amazon Standard Identification Number).Can someone please suggest me how to solve this error. Thanks in advance...!! from selenium import webdriver from selenium.webdriver.common.keys import Keys from time import sleep import bs4 from urllib.request import urlopen as url_req from bs4 import BeautifulSoup as soup driver = webdriver.Chrome(executable_path='C:\Webdrivers\chromedriver.exe') my_lists = ['nike','addias'] for list in my_lists: url1= "https://www.amazon.in/s/ref=nb_sb_noss_2?url=search-alias%3Daps&amp;field-keywords=" url2 = "&amp;rh=i%3Aaps%2Ck%3A" driver.get(url1 + str(list) + url2) new_url = driver.current_url uclient= url_req(new_url) page_html = uclient.read() uclient.close() #html parser page_soup = soup(page_html, "html.parser") try: title = page_soup.findAll("li", {"class": "s-result-item s-result-card-for-container a-declarative celwidget"}) print(title[0].textstrong text) except Exception as e: print("Exceptions_Found",format(e)) sleep(5) print ("Query link: ",driver.current_url) driver.back() sleep(1) driver.quit()
has answer: http://stackoverflow.com/a/52289103
answer count: 1
has comment: http://stackoverflow.com/comment/91522998
favorite count: 0
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52289103
tagged with: selenium
tagged with: web-scraping
upvote count: 1
has comment: http://stackoverflow.com/comment/91523054
downvote count: 1

http://stackoverflow.com/q/52390042
has comment: http://stackoverflow.com/comment/91727907
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: text
tagged with: camera
score: 1
has comment: http://stackoverflow.com/comment/91766674
tagged with: image
type: Question
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/91726356
has body: So, im basically looking for a fast method of filtering images of a single black letter from a white Background on a Raspberry Pi. The images would be scaled slightly different and may be taken from a different angle, but the letter would almost certainly be like a quarter of the picture. The image has to be taken and instantly looked at and categorized. Lets say we have the letters A, B and C. The task would be to take the photo (by an extra camera module directly on the Raspberry PI) and then return the output(the letter, at best saved in an extra variable) to another program. The whole process should be as fast as possible and it should be executed on command for a rate of maybe once every 2-10 seconds (based on situation) I had the idead of using PyTesseract but I saw lots of evidence, that tesseract takes a lot of time (or is it just for larger images/text?)
downvote count: 0
has title: Image Filtering/Categorization/Recognition
has comment: http://stackoverflow.com/comment/91757057
has comment: http://stackoverflow.com/comment/91734441
has comment: http://stackoverflow.com/comment/91728318
favorite count: 0

http://stackoverflow.com/a/52301882
has body: Assuming that this data is valid JSON, you can convert it to a dictionary and then use robot's extended variable syntax Example: ${result}= evaluate json.loads($string) json should be equal ${result["data"]["id"]} ${NONE} should be equal ${result["data"]["type"]} token should be equal ${result["data"]["secret"]} &lt;SecretID&gt; should be equal ${result["data"]["token"]} &lt;TokenID&gt;
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52301003

http://stackoverflow.com/q/52293809
has answer: http://stackoverflow.com/a/52294933
downvote count: 1
favorite count: 0
has body: import random string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for x in range(16): a = print(random.choice(string)) How to print these randomly generated letters in the form of a 4*4 matrix in python ?
tagged with: matrix
tagged with: python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/91535387
type: Question
has title: how to print a given randomly generated letters into the form of a matrix in python
possible better answer: http://stackoverflow.com/a/52293917
has answer: http://stackoverflow.com/a/52293912
accepted answer: http://stackoverflow.com/a/52293912
has answer: http://stackoverflow.com/a/52293917
upvote count: 3
answer count: 3

http://stackoverflow.com/a/52355887
type: Answer
has comment: http://stackoverflow.com/comment/91657160
has body: a = 7 b = "" while a &lt;= 20: b += (str(a) + ", ") a = a + 3 ANSWER = f'"{b}"' print(ANSWER) (xenial)vash@localhost:~/python/stack_overflow$ python3.7 letters_dict.py "7, 10, 13, 16, 19, "
has comment: http://stackoverflow.com/comment/91657237
has comment: http://stackoverflow.com/comment/91657205
answers question: http://stackoverflow.com/q/52355710
score: 0

http://stackoverflow.com/q/52378522
tagged with: date
score: 0
answer count: 1
has title: DateRangeSlider Bokeh Widget Error, Cannot convert string to timestampdate
has body: I am trying to implement the DateRangeSlider Widget into my bokeh project. I am using the widget to adjust the amount of stock date present over a range that I have accumulated in the csv file. Whenever I move the slider widget it gives me an error. I am assuming that the datatypes used are incorrect. The issue lies in my update function. How can I resolve this ? from math import pi import pandas as pd import numpy as np import datetime import time from datetime import date from bokeh.layouts import row, widgetbox, column from bokeh.models import ColumnDataSource, PrintfTickFormatter, CDSView,BooleanFilter from bokeh.models.widgets import PreText, Select, DateRangeSlider, Button, DataTable, TableColumn, NumberFormatter from bokeh.io import curdoc, show, reset_output from bokeh.plotting import figure, output_file DEFAULT_TICKERS = ['AAPL','GOOG','NFLX', 'TSLA'] ticker1 = Select(value='AAPL', options = DEFAULT_TICKERS) range_slider1 = DateRangeSlider(start=date(2014,1,1) , end=date(2017,1,1), value=(date(2014,2,1),date(2016,3,1)), step=1) def load_ticker(ticker): fname = ( '%s.csv' % ticker.lower()) data = pd.read_csv( fname, header = None, parse_dates = ['Date'], names =['Date','Open','High','Low','Close','AdjClose','Volume']) return data def get_data(t1): data = load_ticker(t1) return data def ticker1_change(attrname, old, new): update() def range_slider_change(attrname, old, new): update() def update(selected=None): t1 = ticker1.value sd = str(range_slider1.value[0]) ed = str(range_slider1.value[1]) start_date = sd end_date = ed datarange = get_data(t1) datarange['Date'] = pd.to_datetime(datarange['Date']) mask = (datarange['Date'] &gt; start_date) &amp; (datarange['Date'] &lt;= end_date) data = datarange.loc[mask] source.data = source.from_df(data) p.title.text = t1 data = get_data(ticker1.value) source = ColumnDataSource(data) p = figure(plot_width=900, plot_height=400, x_axis_type='datetime') p.grid.grid_line_alpha = 0.3 p.line('Date', 'Close', source=source) ti…
tagged with: python
has comment: http://stackoverflow.com/comment/91702784
has answer: http://stackoverflow.com/a/52379281
tagged with: timestamp
has comment: http://stackoverflow.com/comment/91737574
type: AnsweredQuestion
tagged with: widget
accepted answer: http://stackoverflow.com/a/52379281
tagged with: bokeh
type: Question

http://stackoverflow.com/q/52318594
has answer: http://stackoverflow.com/a/52318743
tagged with: django-templates
has body: I have a django form generated by a model. class Manager(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) gender = models.CharField(max_length=50) birth_date = models.DateField() phone_number = models.CharField(max_length=10) region_of_residence = models.CharField(max_length=50) city_of_residence = models.CharField(max_length=50) common_of_redidence = models.CharField(max_length=50) address_of_residence = models.CharField(max_length=50) zip_of_residence = models.CharField(max_length=50) username = models.CharField(max_length=20) email = models.CharField(max_length=200) password = models.CharField(max_length=100) def __str__(self): return self.username i've created a form to overwrite some fields and add other one in this way: class ManagerForm(forms.ModelForm): gender = forms.ChoiceField(choices=GENDER_CHOICES) password = forms.CharField(widget=forms.PasswordInput()) verify_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = Manager fields = ('first_name', 'last_name', 'gender', 'birth_date', 'phone_number', 'region_of_residence', 'city_of_residence', 'common_of_redidence', 'address_of_residence', 'zip_of_residence', 'username', 'email', 'password',) def clean(self): cleaned_data = super(ManagerForm, self).clean() password = cleaned_data.get("password") verify_password = cleaned_data.get("verify_password") if password != verify_password: raise forms.ValidationError( "password and verify_password does not match" ) I've put my choice into an external file and they are: GENDER_CHOICES = [ _('Non specificato'), _('Uomo'), _('Donna') ] now i've would like to render my form with a simple for statement {% for field in form %}{% render_field field class="form-control" %}. But i receive the follow error: ValueError: too many values to unpack (expected 2) how can i render correctly these fields?
has comment: http://stackoverflow.com/comment/91584663
type: Question
has answer: http://stackoverflow.com/a/52318711
score: 0
answer count: 2
has title: rendere form with select django
has comment: http://stackoverflow.com/comment/91584587
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/a/52419726
score: 4
accepted answer of: http://stackoverflow.com/q/52419675
upvote count: 4
has comment: http://stackoverflow.com/comment/91782626
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91782616
answers question: http://stackoverflow.com/q/52419675
has body: You already exhaust the iterator neighbor when you use it in the list constructor for printing, so it becomes empty in the list comprehension in the next line. Store the converted list in a variable so you can both print it and use it in the list comprehension: queue = [1] neighbor = T.neighbors(1) #neighbor is a &lt;dict_keyiterator at 0x16843d03368&gt; neighbors = list(neighbor) print(neighbors) #Output: [2, 3] queue.extend([n for n in neighbors]) print(queue)
type: Answer

http://stackoverflow.com/comment/91611123
comment on: http://stackoverflow.com/q/52310130
has text: Thanks. I registered with quandl and received my API key. It's working now.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/91526729
comment on: http://stackoverflow.com/a/52289418
type: Comment
score: 1
has text: @Shiva - Yes, `glob` return all filepaths, so it is necessary.
type: AnswerComment

http://stackoverflow.com/q/52397999
downvote count: 0
tagged with: raspberry-pi3
tagged with: terminal
tagged with: bash
has title: RPI open a terminal on boot and auto-run a looping python script
tagged with: python
has body: When my RPI3 is booted, I would like it to automatically have the terminal open with my python script already running. Note that it loops endlessly. I want to open the terminal so I check the logs my script produces. I have searched ways that auto-runs python scripts on boots. I have tried putting python /home/pi/Desktop/pythonfile.py $ on /etc/rc.local but it just runs in the background and doesn't open a terminal. What I also tried to do was use lxterminal. In /etc/rc.local, I put sudo /home/pi/Desktop/bashfile.sh &amp;. Then the contents of bashfile.sh were: #!bin/bash/ lxterminal --command="/bin/bash -c '/home/pi/Desktop/pythonfile.py; /bin/bash'" When I try to manually run the bashfile.sh, the lxterminal opens and run the python script. However, when I rebooted, it doesn't open a terminal. Any suggestions to this? Thanks.
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91743180
score: 2
has comment: http://stackoverflow.com/comment/91740331
type: Question
tagged with: raspberry-pi

http://stackoverflow.com/q/52355596
type: AnsweredQuestion
tagged with: web-scraping
type: Question
answer count: 1
has body: Currently, I am trying to gather data from my realtor from the listings she sends me. It always comes through a link from the main site "http://v3.torontomls.net" I think only realtors can go into this site and filter on houses, but when she sends it to me I can see a list of houses. I am wondering if it is possible to create a python script that:) 1) opens Gmail 2) filter's on her emails 3) opens one of her emails 4) clicks on the link 5) Scrapes the house data into a CSV format I am not sure about the feasibility of this, I have never used python to scrape web pages. I can see step 5 is doable, but how do I go about step 1 to 4?
has answer: http://stackoverflow.com/a/52355661
accepted answer: http://stackoverflow.com/a/52355661
has title: email scraper using python beautiful soup or html module
score: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: gmail

http://stackoverflow.com/a/52882823
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52411350
answers question: http://stackoverflow.com/q/52411350
downvote count: 0
score: 1
has body: To answer your question, you can use a schema validator with the @validates_schema decorator. It has a pass_original parameter. @validates_schema(pass_original=True) def validate_name(self, data, input_data): existing_item = ItemModel.name_exists(data['name']) if existing_item and existing_item._id != input_data['_id']: raise ValidationError('Item already exists.') But frankly, I think your use case is wrong. If it is an item creation (POST), just check whether the name already exists. If it is an item modification (PUT), you know the ID from the request path. And you should be able to access it from your object. Also, if I may suggest, you could use webargs (maintained by marshmallow maintainers) to parse request with marshmallow easily.

http://stackoverflow.com/q/52298957
tagged with: ipython
has body: I'm attempting to run a simple while loop with an input() to stop the flow periodically, as shown below: Python 3.6.3 |Anaconda, Inc.| (default, Oct 15 2017, 03:27:45) [MSC v.1900 64 bit (AMD64)] Type "copyright", "credits" or "license" for more information. IPython 6.1.0 -- An enhanced Interactive Python. In [1]: while True: ...: print("Hello") ...: x = input("enter a num") ...: if x == 1: ...: print("ok") ...: Hello enter a num1 Hello enter a num1 Hello enter a num1 However, it seems like after a couple passes, I can no longer hit enter and I can't even stop the execution of the code using a hotkey. Does anyone know if this is an issue with Spyder's IPython console or a local error?
type: Question
downvote count: 0
has title: spyder IPython console input() fails
has comment: http://stackoverflow.com/comment/91589520
tagged with: console
tagged with: spyder
favorite count: 0
has comment: http://stackoverflow.com/comment/91555800
has comment: http://stackoverflow.com/comment/91568749
type: UnansweredQuestion
tagged with: input
tagged with: python
score: 3
has comment: http://stackoverflow.com/comment/91546955
answer count: 0
upvote count: 3

http://stackoverflow.com/comment/91508600
score: 0
has text: Looks like you have a string representation of a list. Try using `ast.literal_eval(x)` first. Do it on the entire column to make this easier: `df.segment = df.segment.apply(ast.literal_eval)`
comment on: http://stackoverflow.com/q/52280146
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91796181
comment on: http://stackoverflow.com/a/52425811
has text: I'm not sure what you mean @nagaKiran. The expected output for 1/31/2016 is 5000 for example. In your answer your output for the same row is 3033
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91563574
comment on: http://stackoverflow.com/q/52308132
has text: is it the simplest method?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91691500
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52372933
has text: If you want the placeid of a location, try nearbysearch (with the location)
score: 0

http://stackoverflow.com/comment/91592876
has text: thanks... it helped to detect the files. I did not think about that :D. Clever way
comment on: http://stackoverflow.com/a/52303870
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91673340
comment on: http://stackoverflow.com/q/52362710
has text: Sorry, i was not clear on that: I want to write python code that mimics MS Access for data entry and connect the resulting table with other tables. Basically i want to write a python version of MS Access. Thanks for your reply.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91687086
comment on: http://stackoverflow.com/q/52370911
type: Comment
type: QuestionComment
has text: @CrisLuengo Sorry, forgot to mention it. I tried detecting the boxes too, but they are not consistent, because of the low resolution and since the boxes might have tick marks on it too. I get 2-3 boxes for both, but that is not enough to tell me the difference
score: 1

http://stackoverflow.com/comment/91591579
type: Comment
type: AnswerComment
has text: anyway thanks, maybe someone with more experience can help me. thanks again.
score: 0
comment on: http://stackoverflow.com/a/52321429

http://stackoverflow.com/q/52319756
has comment: http://stackoverflow.com/comment/91586872
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52319883
tagged with: nested
has comment: http://stackoverflow.com/comment/91586889
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/52319883
score: 0
answer count: 2
has body: As the title suggest, i'm getting a nested list from splitting twice. " ".join didn't help with this problem. I also can't figure out how to print position of a word in the list. The goal is to split id user text words on tab(which works) and print the words with their position in a list. import sys def main(): olist = [] for line in sys.stdin: i,u,t,w = line.split('\t') olist.append(w.split()) print(olist) for num,name in enumerate(olist): print(num, name) output print(olist): 'RT', '@AfshinEllian1', ':', 'Kennelijk', 'vinden', 'ze', 'daar', 'aan', 'die', 'gezellige', 'tafel', 'normaal', 'dat', 'steltje', 'barbaren', 'onze', 'grondwettelijke', 'rechten', 'bedreigen', '.', 'Zouden', 'we', 'ook', 'voor', 'andere', 'buitenwettelijke', 'dreigingen', 'moeten', 'capituleren', '?', 'Wat', 'een', 'door', 'ons', 'gesubsidieerde', 'domheid', '!', '#laatop1', '#cartoonwedstrijd' output print(num, name): 0 ['RT', '@AfshinEllian1', ':', 'Kennelijk', 'vinden', 'ze', 'daar', 'aan', 'die', 'gezellige', 'tafel', 'normaal', 'dat', 'steltje', 'barbaren', 'onze', 'grondwettelijke', 'rechten', 'bedreigen', '.', 'Zouden', 'we', 'ook', 'voor', 'andere', 'buitenwettelijke', 'dreigingen', 'moeten', 'capituleren', '?', 'Wat', 'een', 'door', 'ons', 'gesubsidieerde', 'domheid', '!', '#laatop1', '#cartoonwedstrijd'] Desired output = RT [0] @AfshinEllian1 [1] : [2] Kennelijk [3] etc
possible better answer: http://stackoverflow.com/a/52319887
has comment: http://stackoverflow.com/comment/91586946
has answer: http://stackoverflow.com/a/52319887
tagged with: indexing
has title: Python3 preventing nested list and show position/index of values in list

http://stackoverflow.com/comment/91653990
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/52354695
has text: Please include the full traceback
type: Comment

http://stackoverflow.com/a/52371111
downvote count: 0
has comment: http://stackoverflow.com/comment/91711393
has comment: http://stackoverflow.com/comment/91687097
type: Answer
has body: This should help you https://www.pyimagesearch.com/2016/02/08/opencv-shape-detection/ Essentially it boils down to finding the contours in the image then using cv2.approxPolyDP to figure out how many sides there are to the shape. Then just check for how many 4 sided shapes you have. You will probably get one for the outer box, but you can just check for boxes with no other boxes inside of them to isolate your checkboxes.
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52370911

http://stackoverflow.com/q/52339402
linked to: http://stackoverflow.com/q/3323001
tagged with: stack
tagged with: stack-trace
has answer: http://stackoverflow.com/a/52339498
type: Question
has body: I'm doing my best to not be vague here and this all could be solved with a while loop, but as an exercise I've gone against the best practice of using a while loop in hopes to learn something new. I'm re-learning some basics of CPU architecture, and thought it'd be a fun project to implement CPU emulation with "actual" JMP logic, or as close to it as possible in software. However, I'm getting stuck on a rendering process of said logic. The code is (according to my best judgement) irrelevant to the problem but to avoid a back and fourth, the logic is as follows: .LDA 0220 .ASL .BCC FA All this does it check a register, executes a bit shift to the left and jumps to memory address FA if a status flag is set correctly, if not it will jump back to .LDA and check the registers again. The implementation in python does the same with a recursive function of each step in the code. Needless to say, this is beyond best practices but I thought it'd be a fun experiment in recursion and call-order. If my math checks out, I end up with 16 280 recursive calls before python simply halts, and after 3 seconds or so just quits back out to the command prompt. I've done sys.setrecursionlimit(self.dotcount*self.linecount) in a dirty attempt to increase the recursionlimit, and the goal here was to be able to execute 81 600 recursions (340x240 pixels, one recursive call per pixel rougly). according to What is the maximum recursion depth in Python, and how to increase it? this is a bad idea, since the frames are pretty big, so my attempt to remedy this was: for tb in inspect.stack(): tb.frame.clear() I've also tried (to no prevail) to use traceback.clear_frames(tb). The dead end hits me with RuntimeError: cannot clear an executing frame. My last resort/question is: Is it possible to reduce the executing frame to allow for more recursive calls that I know have a happy ending? I can't see that I'm even close to running out of RAM and the application isn't running even close to noticeably slow (…
has title: Reduce stacktrace of executing frame
score: 0
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52307347
upvote count: 1
favorite count: 0
has body: I'm a new data science student and I am trying to understand what exactly is happening inside the insertion sort algorithm. Can anyone tell me what's happening step by step? It would be most appreciated. Below is a code I wrote with some verbose so I could hopefully understand what was happening a little better but to no avail. A = [4, 1, 7, 52, 10, 12] B = [4, 1, 7, 52, 10, 12] def InsertionSort(A): for j in range(1, len(A)): print("***************** LOOP", j, "*********************\n") key = A[j] i = j - 1 print("i:", i, " | A[i]:", A[i], " | key:", key, "\n") print("IS i:", i, "&gt;= 0 and", A[i], "&gt;", key, "?", "\n") while i &gt;= 0 and A[i] &gt; key: print("TRUE:", i, "&gt;= 0 and", A[i], "&gt;", key, "\n") A[i + 1] = A[i] # left cell switches places with right cell i = i - 1 A[i + 1] = key print("\n\n") print("=================== END =====================") InsertionSort(A) print("A (not-sorted): ", B) print("A (sorted): ", A) I don't understand how it switches the numbers.
answer count: 3
has answer: http://stackoverflow.com/a/52307514
has answer: http://stackoverflow.com/a/52307916
tagged with: python
tagged with: insertion-sort
accepted answer: http://stackoverflow.com/a/52307493
type: AnsweredQuestion
tagged with: algorithm
has title: The Insertion Sort algorithm. What's happening step by step?
has comment: http://stackoverflow.com/comment/91562173
possible better answer: http://stackoverflow.com/a/52307916
score: -1
has answer: http://stackoverflow.com/a/52307493
type: Question
downvote count: 2

keylogger
tags question: http://stackoverflow.com/q/52403967
type: Tag
tag name: keylogger

http://stackoverflow.com/q/52339903
tagged with: python
tagged with: jupyter
has answer: http://stackoverflow.com/a/59359619
tagged with: jupyter-notebook
has body: I am trying to plot timeseries data and would like the x axis to just be Month and Day. Plotly requires format to be yyyy-mm-dd, but I have daily averages from a data set over a few years, so I just want to plot mm-dd on the x axis. When I send a datetime that is just mm-dd it assumes the mm to be the year. Can I get it to bypass the year and only take mm-dd? df_en_ave1.index = df_en_ave1.index.strftime('%m-%d') #convert my index to month and day datetime trace1=go.Scatter(x=df_en_ave1.index, y=df_en_ave1.evap) #need to bypass year in date here somehow data = [trace1] plotly.offline.iplot(data)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91652034
type: Question
tagged with: plotly
score: 10
linked to: http://stackoverflow.com/q/51889943
upvote count: 10
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91639655
has title: Plotly: How to plot just month and day on x axis? (Ignore year)
favorite count: 0
has answer: http://stackoverflow.com/a/57910442
has comment: http://stackoverflow.com/comment/91632363

http://stackoverflow.com/comment/91659061
comment on: http://stackoverflow.com/a/52357253
score: 2
has text: Don't name your variable `sum`... for reasons that should be obvious.
type: AnswerComment
type: Comment

cors
type: Tag
tag name: cors
tags question: http://stackoverflow.com/q/52318228
tags question: http://stackoverflow.com/q/52279068
tags question: http://stackoverflow.com/q/52309527

http://stackoverflow.com/comment/91692080
type: QuestionComment
comment on: http://stackoverflow.com/q/52373652
has text: What do you expect to be the result? `cycle` represents an infinite number of items repeating over and over.
score: 0
type: Comment

http://stackoverflow.com/q/52355347
tagged with: python
has comment: http://stackoverflow.com/comment/91940554
tagged with: tkinter
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/91668559
has title: Button background color configuration is not applied in some cases
has comment: http://stackoverflow.com/comment/91668962
score: 0
has comment: http://stackoverflow.com/comment/91686577
has body: I have a certain GUI which includes a button. This button is disabled until some condition is met. When the user clicks this button, I call a function onBurnClick which does some actions and when it finishes it verifies something in the background. If the verification is positive I color button2 background in green and if it is negative I color this button's background in red. This function is also bound to the &lt;Return&gt; key. But for some reason only when I click the button the background coloring, at the end of the process, is visible. Pressing the &lt;Return&gt; key does all the rest except for the button background coloring. By the way, I had to set the focus on button2 in order to make the binding successful. I set the focus at the same conditions that I make button2 active. class Second_Screen(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self,parent) self.button2 = tk.Button(self.main_frame, text="Burn", command=lambda: self.onBurnClick(), font=self.Button_Font_Style1, bd=5) self.button2.grid(row=3, columnspan=2, pady=(20,0)) self.button2.bind("&lt;Return&gt;", self.onBurnClick) def onBurnClick(self, event=None): if some_conditions: self.button2.config(bg='springgreen2') self.after(3000, self.return2default) else: self.button2.config(bg='red2') def return2default(self): self.button2.config(bg='SystemButtonFace') What do I need to do in order to have the same background coloring on the &lt;Return&gt; key press event too ?
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/q/52366207
tagged with: pyserial
answer count: 1
has comment: http://stackoverflow.com/comment/91677814
has comment: http://stackoverflow.com/comment/91677714
has answer: http://stackoverflow.com/a/52367018
has comment: http://stackoverflow.com/comment/91677629
type: UnansweredQuestion
tagged with: python
has title: Problem loading color detected for arduino
has body: I'm having a problem loading the information into Arduino via pyserial. I'm using a python and opencv script to do color detection via webcam. For every detected color I want to inform Arduino so it can make a decision. But I can not send the data to the Arduino. This is the program I'm using in python #importando módulos import cv2 import numpy as np import serial import time import os #COM 4 = porta serial que está ligada o arduino #115200 = baudrate ser = serial.Serial('COM3', 115200, timeout = .5) #capturando vídeo através da webcam cap = cv2.VideoCapture(1) while(1): _, imagem = cap.read() #quadro de conversão (imagem, ou seja, BGR) para HSV (valor de saturação de matiz) hsv = cv2.cvtColor(imagem, cv2.COLOR_BGR2HSV) #define a gama de cor vermelha red_lower = np.array([136, 87, 111], np.uint8) red_upper = np.array([180, 255, 255], np.uint8) #define a gama de cor azul blue_lower = np.array([99, 115, 150], np.uint8) blue_upper = np.array([110, 255, 255], np.uint8) #define a gama de cor verde green_lower = np.array([22, 60, 200], np.uint8) green_upper = np.array([60, 255, 255], np.uint8) #encontrar o intervalo de cor vermelha, azul e amarela na imagem red = cv2.inRange(hsv, red_lower, red_upper) blue = cv2.inRange(hsv, blue_lower, blue_upper) green = cv2.inRange(hsv, green_lower, green_upper) #Transformação Morfológica, Dilatação kernal = np.ones((5 ,5), "uint8") red = cv2.dilate(red, kernal) res = cv2.bitwise_and(imagem, imagem, mask = red) blue = cv2.dilate(blue, kernal) res1 = cv2.bitwise_and(imagem, imagem, mask = blue) green = cv2.dilate(green, kernal) res2 = cv2.bitwise_and(imagem, imagem, mask = green) #Seguindo a cor vermelha (_, contours, hierarchy) = cv2.findContours(red, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for pic, contour in enumerate(contours): area = cv2.contourArea(contour) if (area &gt; 300): x, y, w, h = cv2.boundingRect(contour) imagem = cv2.rectangle(imagem,(x, y), (x+w, y+h), (0, 0, 255), 2) cv2.putText(imagem, "Vermelho",(x, y), cv2.FONT_HE…
tagged with: arduino
tagged with: image-processing
has comment: http://stackoverflow.com/comment/91685338
type: Question
tagged with: opencv
linked to: http://stackoverflow.com/q/51728813
has comment: http://stackoverflow.com/comment/91680810
has comment: http://stackoverflow.com/comment/91676904
score: 0

http://stackoverflow.com/comment/91555800
score: 0
comment on: http://stackoverflow.com/q/52298957
type: Comment
type: QuestionComment
has text: @CarlosCordoba Is there no apparent solution? It seems like it would be fairly important. Perhaps it is only an issue on my machine?

http://stackoverflow.com/a/52279043
downvote count: 0
score: 1
has body: dt_obj = datetime.datetime.strftime(dataHist['last_updated'], '%Y-%m-%d') This piece of your code above creates a string from datetime, so anyway you would have to add time first, then convert to string. For reverse you should use strptime() instead of strftime(), this way you'll get datetime from string.
answers question: http://stackoverflow.com/q/52278966
upvote count: 1
type: Answer

http://stackoverflow.com/a/52393782
answers question: http://stackoverflow.com/q/52316980
has body: This isn't an ideal solution but in order to keep from blocking indefinitely I've tapped into Python's threading module to take a screenshot like so: import threading t = threading.Thread(target=webdriver.get_screenshot_as_file, args=[fn]) t.start() t.join(10) assert not t.isAlive(), "Screenshot failed" If an exception occurs then I quit or terminate the browser process which results in the thread dying off as well.
type: Answer
score: 0

http://stackoverflow.com/comment/91560852
comment on: http://stackoverflow.com/a/52284520
type: Comment
has text: @ClaraDocej, it’s better to post another question with a sample of your code and the trace back. It’s easier to diagnose and answer.
score: 0
type: AnswerComment

http://stackoverflow.com/a/52404983
type: AcceptedAnswer
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/91756133
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52404849
has comment: http://stackoverflow.com/comment/91754002
answers question: http://stackoverflow.com/q/52404849
has body: You can do a split at ******************************************\n\n with record_list = file_Obj.read().split("******************************************\n\n") This will give you each independent record in a list. You might need to escape the backslash. You can take the last element of a list by slicing it. print(record_list[-1])

http://stackoverflow.com/comment/91596927
has text: I get response body perfectly but can't find the cookie anywhere. Even check in ```document.cookies``` using javascript.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52324921

http://stackoverflow.com/q/52331082
type: Question
has title: pandas filter by values in 2 columns, return entire row
tagged with: python
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/91608799
has comment: http://stackoverflow.com/comment/91609548
has comment: http://stackoverflow.com/comment/91609834
upvote count: 1
has comment: http://stackoverflow.com/comment/91609068
has answer: http://stackoverflow.com/a/52331344
has comment: http://stackoverflow.com/comment/91608752
linked to: http://stackoverflow.com/q/18171739
has comment: http://stackoverflow.com/comment/91609473
has comment: http://stackoverflow.com/comment/91609265
has comment: http://stackoverflow.com/comment/91609202
has body: I've looked around multiple questions on here and no solution works. I have a matrix, where I want to filter values in 2 columns and return the entire row where this filter applies. At the moment I have tried: mask = (data['sender'] == 'me') &amp; (data['status'] == 'done') data[mask] which makes all values become "NaN". When I try to apply the mask seperately, I get a DataFrame that contains the correct value in the location, but with all other columns as NaN. I had also tried a different approach, namely like so: data.loc[data['sender' == 'me'] which has the same result of turning every value in NaN except for the Row x Column where the value appears..
has comment: http://stackoverflow.com/comment/91609506
has comment: http://stackoverflow.com/comment/91609190
has comment: http://stackoverflow.com/comment/91609105
tagged with: pandas
has comment: http://stackoverflow.com/comment/91609408
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91609246
answer count: 1
accepted answer: http://stackoverflow.com/a/52331344
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/91777334
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52376056
score: 0
has text: @liberforce I use gnome-system-monitor's memory column but top's or ps' RES column also work fine.

http://stackoverflow.com/q/52417442
tagged with: bash
tagged with: operating-system
has answer: http://stackoverflow.com/a/52417474
tagged with: subprocess
type: UnansweredQuestion
tagged with: python
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91778019
answer count: 1
has title: Python subprocess gives OSError: [WinError 193] %1 is not a valid Win32 application
has comment: http://stackoverflow.com/comment/91788733
has body: I'm writing a python script that needs to call a bash script. The python script contains variables a1 and a2 that need to be passed as arguments to the bash script. I've imported subprocess and am running it like this: subprocess.check_call( ["./test.sh", a1, a2], shell=False) but I am getting an error from this line that OSError: [WinError 193] %1 is not a valid Win32 application. What should I be doing differently?

http://stackoverflow.com/q/52404857
has comment: http://stackoverflow.com/comment/91756620
tagged with: regression
has comment: http://stackoverflow.com/comment/91760358
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/56603605
has comment: http://stackoverflow.com/comment/91756965
tagged with: linear-regression
has comment: http://stackoverflow.com/comment/91799816
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91755664
type: Question
accepted answer: http://stackoverflow.com/a/52464283
score: 5
has answer: http://stackoverflow.com/a/65549840
upvote count: 6
has comment: http://stackoverflow.com/comment/91755715
has comment: http://stackoverflow.com/comment/91753598
possible better answer: http://stackoverflow.com/a/65549840
has answer: http://stackoverflow.com/a/52464283
answer count: 3
has title: How do I plot for Multiple Linear Regression Model using matplotlib
has body: I try to Fit Multiple Linear Regression Model Y= c + a1.X1 + a2.X2 + a3.X3 + a4.X4 +a5X5 +a6X6 Had my model had only 3 variable I would have used 3D plot to plot. How can I plot this . I basically want to see how the best fit line looks like or should I plot multiple scatter plot and see the effect of individual variable Y = a1X1 when all others are zero and see the best fit line. What is the best approach for these models. I know it is not possible to visualize higher dimensions want to know what should be the best approach. I am desperate to see the best fit line
downvote count: 1
has comment: http://stackoverflow.com/comment/91799766
has comment: http://stackoverflow.com/comment/91779768
favorite count: 0

http://stackoverflow.com/comment/91600684
comment on: http://stackoverflow.com/a/52326737
score: 0
type: AnswerComment
has text: @JonathanMarin But what would you want your output to be like then? :) have the numbers for both occurrences or just the first?
type: Comment

http://stackoverflow.com/comment/91730687
has text: Ok, that got a bit further before a similar error occured. Both the `MLP` and `RNN` classes are subclasses of `NeuralNetwork`, so both have `from NeuralNetwork import NeuralNetwork`. This now throws an error, how should this be fixed?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52392671
score: 0

http://stackoverflow.com/q/52327507
has comment: http://stackoverflow.com/comment/91602280
has comment: http://stackoverflow.com/comment/91601992
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52332692
tagged with: django-rest-framework
has title: How to display only specific data from the entire list storage on python django server (rest framework)
has answer: http://stackoverflow.com/a/52328360
tagged with: python
type: UnansweredQuestion
tagged with: django
tagged with: request
has body: I have to display (as in topic title) only specific data from the list which is storage on server (PYTHON/DJANGO/REST_FRAMEWORK). F.e. I want to choose data which has planted on the server with 'id=1', but I always get back all items. Can you explain how to correct this? 'urls' file (project level) : # URL routes - known as endpoints API urlpatterns = [ path('admin/', admin.site.urls), path('devices/', include('efota.api.urls')), ] 'urls' file (subordinate folder) : urlpatterns = [ url('', views.DeviceList.as_view()), url('&lt;int:pk&gt;/', views.DeviceDetail.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) 'views' file : class DeviceList(generics.ListAPIView): queryset = Device.objects.all() serializer_class = DeviceSerializer class DeviceDetail(generics.RetrieveAPIView): queryset = Device.objects.all() serializer_class = DeviceSerializer 'serializers' file: class DeviceSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') # the 'fields' controls which database attributes are available class Meta: model = Device fields = ( 'id', 'user', 'id_token', 'current_firmware', 'carrier_code', 'model_name', 'owner', ) read_only_fields = ['id'] def get_url(self, obj): request = self.context.get("request") return obj.get_api_url(request=request) 'models' file: class Device(models.Model): created = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey('auth.User', related_name='owner', on_delete=models.CASCADE) user = models.CharField(max_length=50, verbose_name='user') id_token = models.CharField(max_length=1000, verbose_name='id_token') current_firmware = models.CharField(max_length=41, verbose_name='current_firmware') carrier_code = models.CharField(max_length=5, verbose_name='carrier_code') model_name = models.CharField(max_length=10, verbose_name='model_name') class Meta: ordering = ('created', ) def __str__(self): return self.model_name 'admin' file: from django.contrib import admin from .models impo…
type: Question
tagged with: database

request
tags question: http://stackoverflow.com/q/52350801
tags question: http://stackoverflow.com/q/52307518
tags question: http://stackoverflow.com/q/52325534
tag name: request
type: Tag
tags question: http://stackoverflow.com/q/52332361
tags question: http://stackoverflow.com/q/52327507
tags question: http://stackoverflow.com/q/52321323
tags question: http://stackoverflow.com/q/52322923

http://stackoverflow.com/a/63407038
downvote count: 0
type: Answer
has body: The replace method doesn’t store the altered value in the same variable. You need to store it in another variable and print it. tm = tm.replace('\nis \n', '\nis not\n')
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52427538

http://stackoverflow.com/comment/91652594
type: Comment
has text: difficult to understand from the comment. But Like I said initially, seems looks like it's a dataframe of dataframes. What happens if you do type(BosCle[0]['MP']['MP']), or maybe even BosCle[0]['MP']['MP'].str.split(':')
score: 0
comment on: http://stackoverflow.com/a/52302016
type: AnswerComment

http://stackoverflow.com/a/52560197
type: Answer
answers question: http://stackoverflow.com/q/52376142
score: 0
has body: model.predict(test_x, batch_size=100) will output the probability of each of the classes model.predict_classes(test_x, batch_size=100) will output the most probable class/actual prediction So from your question it seems you want model.predict_classes. Run dir(model) to see all available functions. If you want to generate model.predict_classes output from model.predict output, do pred = model.predict() pred_classes_output = pred.argmax(axis=1) what this does is, it goes over every row for example below is output of model.predict which contains probability for class1, class2, class3 [[0.15, 0.73, 0.02], # note the sum of probabilities is = 1 [0.23, 0.33, 0.44]] it finds the index of the maximum probability i.e 0.73 has index 1, and it creates an array of that so the output will be [1, 2]. model.evaluate runs the check on model.predict_classes. Also I hope you understand that if your sample was inherenly biased, say you had 90 of class 1, 10 of class 2, then by just predicting 1 it will get 90% accuracy known as baseline accuracy.

http://stackoverflow.com/a/52385945
answers question: http://stackoverflow.com/q/52385893
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/91716296
score: 7
has comment: http://stackoverflow.com/comment/91716247
has body: While __init__ is an instance method, you're calling it on the class rather than on an instance. This invocation is called unbound, because it is not bound to an instance. Because of this, you need to explicitly pass self: class Executive(Employee): def __init__(self, name, dept, salary, hascar): Employee.__init__(self, name, dept, salary) # ^^^^ self.hascar = hascar The recommended way, however, is to use super: Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. With super your code would look like this: class Executive(Employee): def __init__(self, name, dept, salary, hascar): super(Executive, self).__init__(name, dept, salary) # ^^^^^^^^^^^^^^^^^^^^^^ self.hascar = hascar Python 3 adds some syntactic sugar to make this common parent class invocation simpler: class Executive(Employee): def __init__(self, name, dept, salary, hascar): super().__init__(name, dept, salary) # Py 3 # ^^^^^^^ self.hascar = hascar
upvote count: 7
has comment: http://stackoverflow.com/comment/91716431

http://stackoverflow.com/comment/91581183
type: Comment
has text: I don't think that first statement is correct. For example, if I wanted to convert the integer 42 to a string I simply need to do some math and a lookup of the ascii table to learn what ascii character represents the digit 4 and which represents the digit 2. The reverse is also possible. I can convert the string "42" to an integer by looking at each character and assigning a value to the character "4" and the character "2", and doing math based on the location of the character in the string.
comment on: http://stackoverflow.com/a/52316703
score: 0
type: AnswerComment

http://stackoverflow.com/a/60883925
upvote count: 1
has body: s1.tags, s2.tags, s3.tags = ['Foo'], ['Bar'], ['Arr'] # name your plots plots = [s1, s2, s3] labels = [(plots[i].tags[0]) for i in range(len(plots))] active = list(range(0, len(plots))) chkbx = CheckboxButtonGroup(labels=labels, active=active) callback = CustomJS(args=dict(plots=plots, chkbx=chkbx), code=""" for (let i = 0; i &lt; plots.length; i++){ plots[i].visible = chkbx.active.includes(i) } """) chkbx.js_on_click(callback) show(column([chkbx] + plots)) Thanks to @bigreddot and their answer for laying foundation for this solution.
downvote count: 0
answers question: http://stackoverflow.com/q/52415577
type: Answer
score: 1

http://stackoverflow.com/a/52344176
type: AcceptedAnswer
has body: One way would be to use shift df = df.loc[df.Label.shift(-1)==True] print(df) # Output 1_count 136088194_count 136088202_count Label 2 0.0 0.0 0.0 False 5 0.0 0.0 0.0 False
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52344070
answers question: http://stackoverflow.com/q/52344070
upvote count: 1

http://stackoverflow.com/comment/91695462
comment on: http://stackoverflow.com/a/52338435
has text: Hm... a workaround would be to clear the dict, like `Logger.instances.clear()` after changing the environment variable
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91820505
type: Comment
has text: If you have a new problem post a new question.
comment on: http://stackoverflow.com/q/52293174
score: 0
type: QuestionComment

http://stackoverflow.com/q/52402133
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91748327
has body: Can anyone explain this behaviour of python dictionaries? d = {} d[True] = 'Magic' d[1] = 'Cool' d[1.0] = 'Hello' print(d) # {True: 'Hello'} Why does it not print all the other (key, value) pairs? Why does True, 1 and 1.0 is evaluated to be the same?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52402198
has comment: http://stackoverflow.com/comment/91748451
duplicate of: http://stackoverflow.com/q/8169001
has comment: http://stackoverflow.com/comment/91748364
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/51505826
upvote count: 4
tagged with: boolean
has title: True and 1 and 1.0 evaluated to be same in python dictionaries
duplicate of: http://stackoverflow.com/q/51505826
has answer: http://stackoverflow.com/a/52402198
answer count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/22275027
score: 3

http://stackoverflow.com/q/52347906
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/91641757
tagged with: neural-network
has comment: http://stackoverflow.com/comment/91641903
has comment: http://stackoverflow.com/comment/91641978
score: 0
tagged with: keras
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91641820
has title: keras: Change dimension of Image object to feed into an ANN?
has comment: http://stackoverflow.com/comment/91641976
answer count: 0
has comment: http://stackoverflow.com/comment/91641923
has comment: http://stackoverflow.com/comment/91641680
has body: I'm trying to learn Neural Networks! I'm trying to compare Convolutional Neural Network and Dense Neural Network on OCR of 100 x 100 pixel character. I'm modifying David Shapiro's code on OCR to create an ANN to compare to his CNN model. https://github.com/daveshap/ocr_svc His random character image generator generates 100 x 100 (I modified it from 32x32 to 100x100 to really see the effect of overfitting - if it happens) def make_random_image(font_file, c, i): paper = 255 #white ink = random.randint(0, 90) font_size = random.randint(min_font, max_font) font = ImageFont.truetype(font_dir + font_file, font_size) string = c canvas = Image.new('RGBA', (base_size, base_size), (paper, paper, paper)) draw = ImageDraw.Draw(canvas) w, h = draw.textsize(text=string, font=font) w = round((base_size - w) / 2) h = round((base_size - h) / 2) draw.text((w, h), string, (ink, ink, ink), font=font) ImageDraw.Draw(canvas) canvas = Image.fromarray(np.uint8(canvas)) # save file filename = font_file.lower().replace('.ttf', '') + '_%s_%s_%s.png' % (charset.index(c), c, i) canvas.save(save_dir + filename) canvas = np.asarray(canvas) canvas = cv2.cvtColor(canvas, cv2.COLOR_RGB2GRAY) return canvas Then using Keras front-end and Tensorflow backend, I (atleast wanted to ) create an ANN: def instantiate_model(): print('COMPILING MODEL') model = Sequential() model.add(Dense(10000,input_shape=input_shape, activation='relu')) model.add(Dense(1000, activation='relu')) model.add(Dense(num_classes, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics= ['accuracy']) print(model.summary()) return model What should be the input shape and how can I change the 100x100 Image to the appropriate input shape? Also, any suggestion on the shape of this ANN? I'm expecting it to fail compared to CNN from what I read. I feel like the input shape should be 1 dimension 10,000 but I am not sure. EDIT========= David Shapiro prepares his training set by: def prepare_datasets(s…

http://stackoverflow.com/comment/91685651
type: QuestionComment
comment on: http://stackoverflow.com/q/52370310
has text: @Deep so to be clear- you want to construct 2 lists for the unique sublists and also one for duplicated elements
score: 0
type: Comment

http://stackoverflow.com/q/52350850
type: Question
tagged with: discord.py
accepted answer: http://stackoverflow.com/a/52353207
tagged with: python-3.6
score: 0
answer count: 1
has title: discord.py Bot not always deleting messages
favorite count: 0
has body: As a little test, I'm making a bot for discord that will take a message I send, delete it, and have the bot send the message. I've got some stuff working, but I have a couple of problems. First, the bot won't always delete messages. With this code if message.content.startswith("H"): print("test") print(message.author) msg=message.content await client.delete_message(message) await client.send_message(message.channel, msg) the bot will only sometimes delete my message. Any idea why? Second, I want it to only repeat my messages, but when I do this; if message.author=="Myusername#1234": print("test") print(message.author) msg=message.content await client.delete_message(message) await client.send_message(message.channel, msg) Nothing happens. No error, just nothing. Can anyone help? P.S: Myusername#1234 is just an example, and not what I'm putting in.
tagged with: python
has answer: http://stackoverflow.com/a/52353207
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91646931
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/52353021
downvote count: 2
has answer: http://stackoverflow.com/a/52356055
has body: i wrote this basic code. My goal is writing basic login system. I created two list: kullanici and sifre. Now, i want to compare items in kullanici and username entered by the user. I hope you understand, thx. kullanici=[] sifre=[] def girisekran(): print("Giriş sistemine hoşgeldiniz") print("Giriş yapmak için '1' tuşunu, kayıt olmak için '2' tuşuna basın") x= input() print("Giriş sistemine hoşgeldiniz") print("Giriş yapmak için '1' tuşunu, kayıt olmak için '2' tuşuna basın") x= input() if (x== "1"): print("Kullanıcı Adı: ") #username y= input() print("Şifre: ") #password z= input() if (x== "2"): print("Kaydolmak istediğiniz kullanıcı adı: ") k_adi= input() kullanici.append(k_adi) print("Kaydolmak istediğiniz şifre: ") s_adi= input() sifre.append(s_adi) print("Ana menüye yönlendiriliyorsunuz, lütfen bekleyiniz.") girisekran()
has comment: http://stackoverflow.com/comment/91650991
type: Question
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/91650973
has comment: http://stackoverflow.com/comment/91651599
answer count: 1
accepted answer: http://stackoverflow.com/a/52356055
has comment: http://stackoverflow.com/comment/91651320
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91651321
has comment: http://stackoverflow.com/comment/91651238
has title: How can i query item from list?
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91651406
has comment: http://stackoverflow.com/comment/91651635

http://stackoverflow.com/a/52336557
score: 0
has body: It's not a pure python problem, but covers Windows API. Look at the documentation of CONSOLE_FONT_INFOEX structure. There is a COORD member on it for width and height of each character. To change console font size, you can give these attributes as a proper value: font.dwFontSize.X = 11 font.dwFontSize.Y = 18 Reference: Change console font in Windows
type: Answer
answers question: http://stackoverflow.com/q/52336257

http://stackoverflow.com/comment/91637893
has text: `https://stackoverflow.com/questions/34222412/load-chrome-extension-using-selenium`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52345425

http://stackoverflow.com/comment/91769646
has text: Thank you for your help, I'll create another question and include the error.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52411968
score: 0

http://stackoverflow.com/q/52410696
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/91766670
has comment: http://stackoverflow.com/comment/91802012
downvote count: 0
score: 4
tagged with: type-conversion
has title: Can't convert dataframe column data types
tagged with: pandas
answer count: 1
has body: After processing a big data set using Pandas/Dask, I saved the resulting data frame to a csv file. When I try to read the output CSV using Dask, the data types are all objects by default. Whenever I try to convert them using conventional methods (e.g. defining data types while reading or reassigning them after reading) I keep getting errors regarding the conversion as seen below: # ATTEMPT 1 import dask.dataframe as dd header = ['colA', 'colB', ...] dtypes = {'colA' : 'float', ...} df = dd.read_csv('file.csv', names=header, dtype=types) &gt; TypeError: Cannot cast array from dtype('O') to dtype('float64') according to the rule 'safe' &gt; ... &gt; ValueError: could not convert string to float: 'colA' ----------------------------------------------------------------------------------- # ATTEMPT 2 import dask.dataframe as dd header = ['colA', 'colB', ...] df = dd.read_csv('file.csv', names=header) df['colA'] = df['colA'].astype(str).astype(float) &gt; ... &gt; File "/home/routar/anaconda3/lib/python3.6/site-packages/pandas/core/dtypes/cast.py", line 730, in astype_nansafe &gt; ValueError: could not convert string to float: 'colA' All the attributes in the original data frame (before converting to CSV) are ints/floats so the conversion is 100% possible. I'm also sure the values are valid. I'm guessing this has something to do with Python's safe policy regarding data conversions. Is there a workaround for this or any way to force the conversion?
accepted answer: http://stackoverflow.com/a/52410996
favorite count: 0
tagged with: dask
tagged with: python
type: AnsweredQuestion
tagged with: data-conversion
has answer: http://stackoverflow.com/a/52410996

http://stackoverflow.com/q/52421171
has comment: http://stackoverflow.com/comment/91787424
type: Question
tagged with: python-multiprocessing
downvote count: 0
answer count: 1
has title: slurm exceeded job memory limit with python multiprocessing
has comment: http://stackoverflow.com/comment/94596993
has comment: http://stackoverflow.com/comment/100420730
has answer: http://stackoverflow.com/a/59784359
has comment: http://stackoverflow.com/comment/92097417
favorite count: 0
tagged with: slurm
has comment: http://stackoverflow.com/comment/100350868
type: UnansweredQuestion
has body: I'm using slurm to manage some of our calculations but sometimes jobs are getting killed with an out-of-memory error even though this should not be the case. This strange issue has been with python jobs using multiprocessing in particular. Here's a minimal example to reproduce this behavior #!/usr/bin/python from time import sleep nmem = int(3e7) # this will amount to ~1GB of numbers nprocs = 200 # will create this many workers later nsleep = 5 # sleep seconds array = list(range(nmem)) # allocate some memory print("done allocating memory") sleep(nsleep) print("continuing with multiple processes (" + str(nprocs) + ")") from multiprocessing import Pool def f(i): sleep(nsleep) # this will create a pool of workers, each of which "seem" to use 1GB # even though the individual processes don't actually allocate any memory p = Pool(nprocs) p.map(f,list(range(nprocs))) print("finished successfully") Even though this may run fine locally, slurm memory acccounting seems to sum up the resident memory for each of these processes, leading to a memory use of nprocs x 1GB, rather than just 1 GB (the actual mem use). That's not what it should do I think and it's not what the OS is doing, it doesn't appear to be swapping or anything. Here's the output, if I run the code locally &gt; python test-slurm-mem.py done allocation memory continuing with multiple processes (0) finished successfully And a screenshot of htop And here's the output if I run the same command using slurm &gt; srun --nodelist=compute3 --mem=128G python test-slurm-mem.py srun: job 694697 queued and waiting for resources srun: job 694697 has been allocated resources done allocating memory continuing with multiple processes (200) slurmstepd: Step 694697.0 exceeded memory limit (193419088 &gt; 131968000), being killed srun: Exceeded job memory limit srun: Job step aborted: Waiting up to 32 seconds for job step to finish. slurmstepd: *** STEP 694697.0 ON compute3 CANCELLED AT 2018-09-20T10:22:53 *** srun: error: compute3…
has comment: http://stackoverflow.com/comment/91786213
tagged with: python
tagged with: memory-management
score: 1
upvote count: 1

http://stackoverflow.com/comment/91510202
score: 0
has text: It might be because your shape isnt closed. It doesn't know if it's convex or concave, so it can't really make a shape out of what you've given it. You might need to make sure it begins and ends at the same point.
comment on: http://stackoverflow.com/q/52281055
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91567362
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52309968
type: AnswerComment
has text: I think this is the most expressive way to do what is stated in the title. "Assign shorter to one and the longer to another". The mission here isn't to deal with more than 2 variables and it would make sense to do it in two steps.

http://stackoverflow.com/comment/91531155
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52288569
has text: Thanks for the reply. In this way, however, the sessions are used out of context. "RuntimeError: Working outside of request context. This typically means that you attempted to use that functionality an active HTTP request. Consult the documentation on testing for information about how to avoid this problem. " A possible solution could be to save the session in a database. Do you think it's the best thing to do? Or am I doing something wrong?

http://stackoverflow.com/comment/91491150
has text: `def loop_solution(*filenames):` ?
type: QuestionComment
comment on: http://stackoverflow.com/q/52272005
score: 4
type: Comment

http://stackoverflow.com/comment/91605725
has text: Once you use the return statement the function is terminated. You can only use one return. Make a list or dictionary if you want to return multiple values.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52329458
score: 0

modal-dialog
tag name: modal-dialog
type: Tag
tags question: http://stackoverflow.com/q/52318106

http://stackoverflow.com/comment/110738993
score: 0
type: Comment
has text: Just a quick question: How a window of shape (3 X emb_dim) gets dot product with a filter of same shape results in a single value (as per your second figure)? I mean how a `window 1` [dot] `filter 1` gives a scaler to put on 0,0 cell of your second figure? Could you please help me understand that?
comment on: http://stackoverflow.com/a/52353721
type: AnswerComment

http://stackoverflow.com/comment/91657936
type: Comment
comment on: http://stackoverflow.com/q/52355311
type: QuestionComment
has text: @Daniel Roseman here you go, hopefully you can help me now
score: 0

http://stackoverflow.com/q/52371167
score: -4
tagged with: python
has comment: http://stackoverflow.com/comment/91687149
type: Question
has answer: http://stackoverflow.com/a/52372387
has title: How to know the position of list?
tagged with: python-3.6
has body: example: newlist = ["a,b,c","d","e","f","g"] What is the position of b ? because normally we just input newlist[0][1] to find the elements of the list
answer count: 2
downvote count: 4
linked to: http://stackoverflow.com/q/2294493
upvote count: 0
favorite count: 0
duplicate of: http://stackoverflow.com/q/2294493
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52371610
type: UnansweredQuestion

http://stackoverflow.com/q/52361130
upvote count: 1
has comment: http://stackoverflow.com/comment/91666605
answer count: 0
downvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/16015548
score: 1
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/91666510
favorite count: 0
has title: "The submitted data was not a file. Check the encoding type on the form." Error In RestFramework
has comment: http://stackoverflow.com/comment/91667026
type: Question
tagged with: django
has body: I am making a student admission system for that i need to upload image ,When iam uploading image my models.py looks like this, models.py: def scramble_uploaded_filename(instance, filename): extension = filename.split(".")[-1] return "{}.{}".format(uuid.uuid4(), extension) class StudentAdmission(BaseModel): student = models.ForeignKey(Student,on_delete=models.CASCADE) admission_date = models.DateTimeField(auto_now_add=True) batch = models.IntegerField() course = models.ForeignKey(Course,on_delete=models.CASCADE) description = models.CharField(max_length=120) image = models.ImageField("Uploaded image", upload_to=scramble_uploaded_filename) And im using a planeSerializer imageField in serializers.py like this: serializers.py class StudentAdmissionBaseSerializer(serializers.Serializer): user = UserSerializer() user_detail = UserDetailSerializer() phone_detail = PhoneSerializer() address_detail = AddressSerializer() registration_no = serializers.IntegerField() batch = serializers.IntegerField() description = serializers.CharField(default='') image = serializers.ImageField() And My views.py looks like this: views.py: class StudentAdmissionViewSet(viewsets.ModelViewSet): queryset = StudentAdmission.objects.all() serializer_class = StudentAdmissionSerializer parser_classes = (NestedMultipartParser,) def get(self, request): return Response([]) def list(self, request): return Response([]) def create(self,request): print({**request.POST,**request.FILES}) serializer = self.get_serializer(data={**request.data,**request.FILES}) if serializer.is_valid(): data = serializer.data ud = data['user'] user,b = User.objects.get_or_create( email=ud['email'], defaults={ 'username':ud['email'], 'first_name':ud['first_name'], 'last_name':ud['last_name'], 'gender':ud['gender'], 'type':ud['type'] } ) if not b: raise serializers.ValidationError({ 'detail':["Email Already Exist"] }) c = ContentType.objects.get_for_model(user) Phone.objects.get_or_create(content_type=c, object_id=user.id, number=d…
tagged with: python
has comment: http://stackoverflow.com/comment/91668499
has comment: http://stackoverflow.com/comment/91667913
has comment: http://stackoverflow.com/comment/91671759

turtle-graphics
tags question: http://stackoverflow.com/q/52282607
tags question: http://stackoverflow.com/q/52305851
tags question: http://stackoverflow.com/q/52309102
tag name: turtle-graphics
type: Tag
tags question: http://stackoverflow.com/q/52361170
tags question: http://stackoverflow.com/q/52334538
tags question: http://stackoverflow.com/q/52280604
tags question: http://stackoverflow.com/q/52358371

http://stackoverflow.com/comment/139923448
comment on: http://stackoverflow.com/a/55579762
type: AnswerComment
score: 0
type: Comment
has text: As an aside for this, if we have a value (picking on C in the chart above), that was really really high e.g. 500, seaborne like to squish all the lower values into an almost single line. Is there any way to show this extreme while maintaining readability for variable C?

http://stackoverflow.com/q/52291519
has body: I have a pandas dataframe with column with dates (datetime64[ns] format) The dates are listed as yyyy-mm-dd (like 2018-09-12). I want to convert it to dd-mm-yyyy but what i try doesn't seem to works: pd.to_datetime(df['date'], format='%d-%m-%Y') 0 2018-09-12 1 2018-09-12 Edit: add example df df.head(3) date nr 0 2018-09-12 144 1 2018-09-12 37 2 2018-09-12 28 df.info() date datetime64[ns] nr int The 'date' doesn't contain any Nan's or Nat's
type: Question
has answer: http://stackoverflow.com/a/52291662
linked to: http://stackoverflow.com/q/49757871
has comment: http://stackoverflow.com/comment/91531083
possible better answer: http://stackoverflow.com/a/52291644
has comment: http://stackoverflow.com/comment/91531109
upvote count: 2
answer count: 2
tagged with: pandas
has title: Pandas: can't convert datetime YYYY-mm-dd to dd-mm-YYYY
downvote count: 0
tagged with: string
favorite count: 0
tagged with: series
has answer: http://stackoverflow.com/a/52291644
tagged with: datetime
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52291662
has comment: http://stackoverflow.com/comment/91530951

ado
tags question: http://stackoverflow.com/q/52298387
type: Tag
tag name: ado

http://stackoverflow.com/q/52289579
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/52293770
accepted answer: http://stackoverflow.com/a/52293770
tagged with: matplotlib
upvote count: 11
has body: Hi I am having trouble plotting a datetime with seaborn. I am trying to plot a categorical data with x as datatype datetime.time but I get these error: float() argument must be a string or a number, not 'datetime.time' This is my df: toronto_time description 0 00:00:50 STATS 1 00:01:55 STATS 2 00:02:18 ONLINE 3 00:05:24 STATS 4 00:05:34 STATS 5 00:06:33 OFFLINE This is my code: import matplotlib.pyplot as plt import seaborn as sns plt.style.use('seaborn-colorblind') plt.figure(figsize=(8,6)) sns.swarmplot('toronto_time', 'description', data=df); plt.show() UPDATE: dtype of 'toronto_time' is an object. When I used pd.to_datetime it converts to datetime however it adds a date.
tagged with: scatter-plot
has title: Plot datetime.time in seaborn
tagged with: pandas
linked to: http://stackoverflow.com/q/43206554
answer count: 1
favorite count: 0
tagged with: seaborn
tagged with: python
score: 11
has comment: http://stackoverflow.com/comment/116371498
type: AnsweredQuestion

http://stackoverflow.com/comment/91605286
comment on: http://stackoverflow.com/q/52329187
type: QuestionComment
score: 1
has text: This means your console (IDE, shell, whatever) does not support all the characters in the scraped data. Try writing to a file instead.
type: Comment

http://stackoverflow.com/q/52374807
has comment: http://stackoverflow.com/comment/91696273
possible better answer: http://stackoverflow.com/a/52375469
has comment: http://stackoverflow.com/comment/91695144
has comment: http://stackoverflow.com/comment/91694483
answer count: 3
accepted answer: http://stackoverflow.com/a/52374940
downvote count: 0
favorite count: 0
tagged with: python
has body: I'm having an issue creating a list of lists in python. Suppose I have the following list: fruitlist = [('Vendor A', 'Apples'), ('Vendor B', 'Apples'), ('Vendor C', 'Bananas'), ('Vendor A', 'Grapes'), ('Vendor A', 'Bananas'), ('Vendor B', 'Oranges')] What I want to do is create list like this : [[Vendor A, (Apples, Grapes, Bananas)], [Vendor B, (Apples, Oranges)], [Vendor C, (Bananas)]] So basically Vendor, and then their offerings. This is the code I currently have, it basically goes through and pulls out just a list of vendors, then loops through and snags each offering, however, the output is not quite I want. vendors = list(set([x[0] for x in fruitlist])) # this creates a list of just vendors: output = [[] for x in range (len(vendors))] #This creates a list with 3 empty lists inside (one for each vendor) where my output will be housed for x in range(0,len(vendors)): for y in range(0,len(fruitlist)): if fruitlist[y][0] == vendors[x]: output[x].append(fruitlist[y][1]) The output looks something like this: [['Apples', 'Oranges'], ['Apples', 'Grapes', 'Bananas'], ['Bananas']] So the output is now broken down by vendor, and each vendor's offering is now in its own list, but now I have to figure out how to insert the vendor names in there, and I simply can't. If I include the vendor name in the append portion of the for loop, output[x].append((fruitlist[y][0],fruitlist[y][1])) it repeats the vendor name for each fruit. If I use the insert method, it seems to create a brand new item, and increase the length of the list. I've tried a few things, I've tried googling around but I can't figure out the right phrasing. If anyone could point me to the right direction, I'd really appreciate it. Also can anyone explain why when I look up vendors: ['Vendor B', 'Vendor A', 'Vendor C'] It puts "B" ahead of "A"? In my original list A was first, does the set function randomly assign the order?
score: 2
has comment: http://stackoverflow.com/comment/91694626
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91694530
tagged with: list
upvote count: 2
has answer: http://stackoverflow.com/a/52375471
has answer: http://stackoverflow.com/a/52374940
has answer: http://stackoverflow.com/a/52375469
has title: Python creating list of lists where first item is of length one and the second item is of length n?
type: Question

http://stackoverflow.com/comment/114679282
score: 0
has text: @Chrisper you're correct that it is odd, but it is a characteristic of so-called "OO" languages that they inadequately deal with polymorphism and type inference. It gets even worse when you start dealing with "data wrangling" to get various "shapes" morphed properly, etc. This has to take up the majority of programmer hours.
type: AnswerComment
comment on: http://stackoverflow.com/a/52398943
type: Comment

http://stackoverflow.com/q/52355710
score: -1
has comment: http://stackoverflow.com/comment/91655991
answer count: 3
has comment: http://stackoverflow.com/comment/91656034
upvote count: 0
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/52355887
has answer: http://stackoverflow.com/a/52355747
tagged with: while-loop
tagged with: python
has title: Python - While loop should return string
has body: Again I'm somewhat stuck with a task. This time my while loop should return a string of comma separated numbers. I do get the comma separated numbers out when I print them but the whole thing should be inside a string, and that's where I fail. The code I use: a = 7 b = "" while a &lt;= 20: b += (str(a) + ", ") a = a + 3 ANSWER = b # Same result with str(b) This produce: 7, 10, 13, 16, 19, and not "7, 10, 13, 16, 19," I don't think I should hard code it in... Any pointers on this? Regards
possible better answer: http://stackoverflow.com/a/52355742
has answer: http://stackoverflow.com/a/52355742
accepted answer: http://stackoverflow.com/a/52355747
downvote count: 1
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/91774393
type: Comment
comment on: http://stackoverflow.com/q/52391030
score: 0
type: QuestionComment
has text: After the linear regression, one can test if the **coefficients** are equal to zero (Null hypothesis) with a statistical test which returns a p-value. There are no standard way to do it with the SVR : what would be the value you do a statistical test on? As for the r^2 and adjusted r^2, you can compute it easily with [these formulas](https://onlinecourses.science.psu.edu/stat501/node/255/) or use the [sklearn implementation](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.r2_score.html)

http://stackoverflow.com/comment/91647461
type: Comment
type: QuestionComment
has text: If you're receiving a python error, and NOT an error from jenkins, OSError is probably not the error that is being thrown. You could use a a plain except block as `except Exception as e:` and then print `e` to see exactly what error is being thrown and then catching only that.
score: 1
comment on: http://stackoverflow.com/q/52341272

http://stackoverflow.com/comment/91595536
score: 1
has text: @HamedMinaee: The path to your Python script is irrelevant, like I said. Each program has a working directory (usually based on the directory you were in when you launched it, which is sometimes, but not always, the same as where the script is). If you launch the script via an IDE, or a custom shortcut or the like, the working directory can be almost anything. Try printing `os.getcwd()`; that's your working directory. If you need it to be relative to the script, you'd need to construct that path explicitly, e.g. `os.makedirs(os.path.join(os.path.dirname(__file__), '..', '..', 'dist'))`
type: Comment
comment on: http://stackoverflow.com/q/52324156
type: QuestionComment

http://stackoverflow.com/a/52407269
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/91759561
has comment: http://stackoverflow.com/comment/91759878
score: 1
upvote count: 1
has body: def login(request): username = request.POST['username'] ... You get the error because your view always tries to get username from the POST data. However, for the initial GET request, request.POST will be empty. You shouldn't try to write your own login view like this. Django comes with authentication views. You should use them.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52407131
answers question: http://stackoverflow.com/q/52407131

http://stackoverflow.com/comment/91585909
comment on: http://stackoverflow.com/a/52315339
has text: It answers his question.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/62062067
score: 0
answers question: http://stackoverflow.com/q/52324921
type: Answer
has body: You can set the cookie in falcon like this... class Resource(object): def on_get(self, req, resp): # Set the 'max-age' of the cookie to 10 minutes (600 seconds) # and the cookies domain to "example.com" resp.set_cookie("my_cookie", "my cookie value", max_age=600, domain="example.com") And get the cookie like this... class Resource(object): def on_get(self, req, resp): cookies = req.cookies if "my_cookie" in cookies: my_cookie_value = cookies["my_cookie"] # .... For more information read falcon docs --> https://falcon.readthedocs.io/en/0.3.0.1/api/cookies.html

http://stackoverflow.com/q/52342573
type: UnansweredQuestion
tagged with: web-scraping
tagged with: python
has answer: http://stackoverflow.com/a/52344345
tagged with: selenium
type: Question
has title: Scraping reviews with selenium
score: 0
has body: I am using Pycharm and it's giving error :selenium.common.exceptions.WebDriverException: Message: unknown error: Element &lt;a I am trying to take out the Safety reviews by going to the href link in the class="quote" " from selenium import webdriver import pandas as pd import re import time driver = webdriver.Chrome("C:\\Users\\tanmay\\Downloads\\chromedriver.exe") driver.get("https://www.tripadvisor.in/Hotel_Review-g304551-d299120-Reviews-or10-The_Lalit_New_Delhi-New_Delhi_National_Capital_Territory_of_Delhi.html") print("Name :",driver.find_element_by_id("HEADING").text) driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") driver.find_element_by_xpath("//*[@id='TABS_REVIEWS']/span").click() Element = driver.find_element_by_class_name("query_elem") Element.send_keys("Safety") driver.find_element_by_css_selector('.ui_icon.search.search-icon').click() driver.execute_script("window.scrollTo(0,2050);") driver.implicitly_wait(0.1) time.sleep(0.1) div = driver.find_element_by_class_name("quote") div.find_element_by_css_selector('a').click()
answer count: 1

http://stackoverflow.com/q/52376233
has body: I am trying to call the following function from Matlab net = importKerasNetworkk('model.h5', 'OutputLayerType', 'classification'); and this outputs the following error: Layer names in layer array must be different from the names of layers in layer graph. I'm not able to find any information about how to deal with this error. It seems straight forward to just import the network, why is it insisting that the names be different? My keras architecture (from Kaggle) is : inputs = Input((IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS)) s = Lambda(lambda x: x / 255) (inputs) c1 = Conv2D(8, (3, 3), activation='relu', padding='same') (s) c1 = Conv2D(8, (3, 3), activation='relu', padding='same') (c1) p1 = MaxPooling2D((2, 2)) (c1) c2 = Conv2D(16, (3, 3), activation='relu', padding='same') (p1) c2 = Conv2D(16, (3, 3), activation='relu', padding='same') (c2) p2 = MaxPooling2D((2, 2)) (c2) c3 = Conv2D(32, (3, 3), activation='relu', padding='same') (p2) c3 = Conv2D(32, (3, 3), activation='relu', padding='same') (c3) p3 = MaxPooling2D((2, 2)) (c3) c4 = Conv2D(64, (3, 3), activation='relu', padding='same') (p3) c4 = Conv2D(64, (3, 3), activation='relu', padding='same') (c4) p4 = MaxPooling2D(pool_size=(2, 2)) (c4) c5 = Conv2D(128, (3, 3), activation='relu', padding='same') (p4) c5 = Conv2D(128, (3, 3), activation='relu', padding='same') (c5) u6 = Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same') (c5) u6 = concatenate([u6, c4]) c6 = Conv2D(64, (3, 3), activation='relu', padding='same') (u6) c6 = Conv2D(64, (3, 3), activation='relu', padding='same') (c6) u7 = Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same') (c6) u7 = concatenate([u7, c3]) c7 = Conv2D(32, (3, 3), activation='relu', padding='same') (u7) c7 = Conv2D(32, (3, 3), activation='relu', padding='same') (c7) u8 = Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same') (c7) u8 = concatenate([u8, c2]) c8 = Conv2D(16, (3, 3), activation='relu', padding='same') (u8) c8 = Conv2D(16, (3, 3), activation='relu', padding='…
has title: Unable to import keras model in Matlab
has comment: http://stackoverflow.com/comment/91708315
type: Question
upvote count: 2
tagged with: keras
has comment: http://stackoverflow.com/comment/91711971
favorite count: 0
has comment: http://stackoverflow.com/comment/91698094
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: matlab
score: 2
downvote count: 0

http://stackoverflow.com/a/52281703
has body: No such thing as a transaction in Elasticsearch. For more info, see here: https://www.elastic.co/guide/en/elasticsearch/guide/current/concurrency-solutions.html Specifically: The problem is that Elasticsearch does not support ACID transactions. Changes to individual documents are ACIDic, but not changes involving multiple documents.
has comment: http://stackoverflow.com/comment/91511609
answers question: http://stackoverflow.com/q/52281678
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/91511519
upvote count: 1
has comment: http://stackoverflow.com/comment/91512053
downvote count: 0

http://stackoverflow.com/comment/91793640
type: QuestionComment
has text: The date column on the left is the index. The Customer just refers to the label of the columns.
comment on: http://stackoverflow.com/q/52424954
score: 0
type: Comment

http://stackoverflow.com/comment/91761720
comment on: http://stackoverflow.com/a/52369031
type: AnswerComment
score: 0
type: Comment
has text: @ErikSteiner: it should have been `self.numl`. Fixed. But this is not what your first comment wants, so the code has been changed to ignore lines with too many delimiters.

http://stackoverflow.com/comment/91573967
comment on: http://stackoverflow.com/q/52313217
has text: Of what I see the lists seem to be hardcoded upon initialisation, you are never changing the lists within button(), you are only changing the variables *p1* and *p2*. Also, you might have a variable scope problem. You can read more about that in the docs https://docs.python.org/3.3/reference/executionmodel.html
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52395270
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52395312
tagged with: python
has body: So let me try this again. I created a pivot table with the following: df3.reset_index(inplace=True) surveys = df3.groupby(['cohort','nps']).agg({'id': pd.Series.nunique}) surveys['%'] = surveys['id'] / surveys.id.sum() which returned: cohort status count % --------------------------------- 2017-01 sad 188 0.009276 ok 53 0.002615 happy 253 0.012483 2017-02 sad 174 0.008585 ok 113 0.005575 happy 247 0.012187 2017-03 sad 221 0.010904 ok 60 0.002960 happy 299 0.014752 and so on. I am trying to figure out how I can get the percentages to add up specifically for their respective cohort. so ideally that would look like: 2017-01 sad 188 0.38 ok 53 0.11 happy 253 0.51 then I could unstack the nps and subtract the promoter from the detractor, ignoring the passive. Has anyone here ever done something like this?
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/52395467
upvote count: 1
has answer: http://stackoverflow.com/a/52395467
type: Question
has title: aggregation within a pivot table index
has answer: http://stackoverflow.com/a/52395312

http://stackoverflow.com/q/52346180
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/52346224
tagged with: python
has title: BeautifulSoup and scraping href's isn't working
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91640371
type: Question
answer count: 2
has body: Again I am having trouble scraping href's in BeautifulSoup. I have a list of pages that I am scraping and I have the data but I can't seem to get the hrefs even when I use various codes that work in other scripts. So here is the code and my data will be below that: import requests from bs4 import BeautifulSoup with open('states_names.csv', 'r') as reader: states = [states.strip().replace(' ', '-') for states in reader] url = 'https://www.hauntedplaces.org/state/alabama' for state in states: page = requests.get(url+state) soup = BeautifulSoup(page.text, 'html.parser') links = soup.findAll('div', class_='description') # When I try to add .get('href') I get a traceback error. Am I trying to scrape the href too early? h_page = soup.findAll('h3') Gaines Ridge Dinner Club Purifoy-Lipscomb House Kate Shepard House Bed and Breakfast Cedarhurst Mansion Crybaby Bridge Gaineswood Plantation Mountain View Hospital
has comment: http://stackoverflow.com/comment/91640428
has comment: http://stackoverflow.com/comment/91640321
has answer: http://stackoverflow.com/a/52347361
accepted answer: http://stackoverflow.com/a/52347361
score: 0
possible better answer: http://stackoverflow.com/a/52346224

http://stackoverflow.com/comment/91864042
has text: Yes, I did try local curl as well. Are you sure the php script you call is an infinite `while (true) {}`?
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52397563

http://stackoverflow.com/a/52399373
has comment: http://stackoverflow.com/comment/91777901
has body: Below are 2 snippets: As per description, which captures additional increases in A column between 1st and 2nd X As per example, capturing the last increase out of all 4 columns 1) As per description for col in 'ABCD': df[col+'_X']=0 df[col+'_Y']=0 for i1, i2 in zip(df[(df.Outcome=='X') | (df.Outcome=='Y') | (df.index==0)].index, df[(df.Outcome=='X') | (df.Outcome=='Y') | (df.index==0)].index[1::]): for col in 'ABCD': if df[col][i2]&gt;df[col][i1]: df.loc[i2::,col+'_'+df.Outcome[i2]]=df[col+'_'+df.Outcome[i2]][i2-1]+1 print(df) Outcome A B C D A_X A_Y B_X B_Y C_X C_Y D_X D_Y 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 2 X 0 0 0 2 0 0 0 0 0 0 1 0 3 1 1 1 2 0 0 0 0 0 0 1 0 4 1 1 2 2 0 0 0 0 0 0 1 0 5 X 1 1 3 2 1 0 1 0 1 0 1 0 6 2 1 3 2 1 0 1 0 1 0 1 0 7 Y 2 1 3 2 1 1 1 0 1 0 1 0 8 2 2 3 2 1 1 1 0 1 0 1 0 9 Y 2 2 3 2 1 1 1 1 1 0 1 0 2) As per example for col in 'ABCD': df[col+'_X']=0 df[col+'_Y']=0 for i1, i2 in zip(df[(df.Outcome=='X') | (df.Outcome=='Y') | (df.index==0)].index, df[(df.Outcome=='X') | (df.Outcome=='Y') | (df.index==0)].index[1::]): change_col = '' change_pos = -1 for col in 'ABCD': if df[col][i2]&gt;df[col][i1]: found_change_pos = df[df[col]==df[col][i2]-1].tail(1).index if found_change_pos &gt; change_pos: change_col = col change_pos = found_change_pos if change_pos &gt; -1: df.loc[i2::,change_col+'_'+df.Outcome[i2]]=df[change_col+'_'+df.Outcome[i2]][i2-1]+1 print(df) Outcome A B C D A_X A_Y B_X B_Y C_X C_Y D_X D_Y 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 2 X 0 0 0 2 0 0 0 0 0 0 1 0 3 1 1 1 2 0 0 0 0 0 0 1 0 4 1 1 2 2 0 0 0 0 0 0 1 0 5 X 1 1 3 2 0 0 0 0 1 0 1 0 6 2 1 3 2 0 0 0 0 1 0 1 0 7 Y 2 1 3 2 0 1 0 0 1 0 1 0 8 2 2 3 2 0 1 0 0 1 0 1 0 9 Y 2 2 3 2 0 1 0 1 1 0 1 0
has comment: http://stackoverflow.com/comment/91781412
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91779287
type: Answer
has comment: http://stackoverflow.com/comment/91788715
answers question: http://stackoverflow.com/q/52313480
accepted answer of: http://stackoverflow.com/q/52313480

arima
tag name: arima
tags question: http://stackoverflow.com/q/52304373
tags question: http://stackoverflow.com/q/52390421
type: Tag
tags question: http://stackoverflow.com/q/52407721

http://stackoverflow.com/q/52359607
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91671003
has title: I use Mac. my import numpy was working fine until I tried to install opencv on to my system
score: 0
has comment: http://stackoverflow.com/comment/91664444
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91687823
has body: while installing opencv in did that ln -s command and now numpy module is not working if i try to install numpy it shows this $ pip install numpy Requirement already satisfied: numpy in /Users/deepakpatel/miniconda3/lib/python3.6/site-packages (1.15.0) but when i try to import that module in python programs its not working it shows this import numpy Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'numpy' so i need some help with this guys if you need more info just comment down below

http://stackoverflow.com/comment/91800427
has text: @norok2 is your python version 2.7.10 ?
comment on: http://stackoverflow.com/q/52428354
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52390226
has body: We can have O(n^2) by hashing pair sums for A and B and checking if for any one of them, sum_AB[i] there might be an X - sum_AB[i] hashed in the pair sums of C and D. In some circumstances it could be more efficient to enumerate those sums by multiplying each pair of lists as counts of coefficients in polynomials, using a FFT for O(m log m) complexity, where m is the range.
score: 1
has comment: http://stackoverflow.com/comment/91726233
has comment: http://stackoverflow.com/comment/91725767
answers question: http://stackoverflow.com/q/52388992
upvote count: 1
has comment: http://stackoverflow.com/comment/91726607
has comment: http://stackoverflow.com/comment/91726474
has comment: http://stackoverflow.com/comment/91736652
has comment: http://stackoverflow.com/comment/91736672
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/91725681

http://stackoverflow.com/comment/91641958
comment on: http://stackoverflow.com/q/52348215
has text: Yes - sorry, I will update OP. data_dict is returned in a function and stored in variable called "data" which is returned in the "render_template" function.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91763596
comment on: http://stackoverflow.com/a/52409486
type: Comment
has text: @Charlotte `myDict` is a local variable in your function. You cannot use it outside! I updated my answer.
score: 0
type: AnswerComment

http://stackoverflow.com/a/52348929
has comment: http://stackoverflow.com/comment/91648288
has body: Here's a hideous monstrosity that does it: [x for i in range(3,5) for x in ([i*j if i%2 else i+j for j in range(2)] if i==3 else (i,))] I'm trying hard to make this readable: In [12]: result = [ ...: x ...: for i in range(3, 5) ...: for x in ((i*j if i%2 else i+j for j in range(2)) ...: if i ==3 else (i,)) ...: ] In [13]: print(result) [0, 3, 4] As pointed out in the comments, your looping shouldn't get this complex. You should use functions here to make your code more readable. It will also make the use of list-comprehensions less unwieldy. Your goal should not be "keep things on one line." Your goal should be "keep my code readable, maintainable, and simple, and honest". This list comprehension is none of those things. Note, I don't expect this to perform better. It requires creating extra anonymous containers or generators\list-comprehensions (which requires creating and calling a function object underneath the hood). Your goal in writing code shouldn't be "how do I learn to write increasingly complex list comprehensions", rather, it should be "how do I write and organize my code so I can make use of straightforward and readable list comprehensions".
has comment: http://stackoverflow.com/comment/91648213
answers question: http://stackoverflow.com/q/52348813
has comment: http://stackoverflow.com/comment/91648239
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/52554403
type: Answer
has body: Yes, You can query on your Token model using annotate function so you can produce column required 'phrases_with_freq_greater_than_100'. Following query will return you the query object with above column (variable): tokens = tokens.annotate(phrases_with_freq_greater_than_100=Count(phrases__frequency__gt=100)) Now, either you can iterate 'tokens' query object or to get direct list of dictionaries use values function in above query like: tokens.annotate(phrases_with_freq_greater_than_100=Count(phrases__frequency__gt=100)).values('name','phrases_with_freq_greater_than_100')
answers question: http://stackoverflow.com/q/52418782
score: 0

http://stackoverflow.com/q/52403334
has comment: http://stackoverflow.com/comment/91750619
has title: Why python chose to access different members (static or instance members) based on when they are set
favorite count: 0
tagged with: static
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91750461
score: 2
has body: I am coming from classical OOP world - Java, C# etc. And I have been fiddling with some basic python stuff for a while. I wrote this basic code: class MyClass: def createInstanceMember(self): self.member = "instance member" def createClassMember(self): MyClass.member = "class member" def printMember(self): print(self.member) def printStaticMember(self): print(MyClass.member) Now when I do following: myObj = MyClass() myObj.createClassMember() myObj.printMember() myObj.createInstanceMember() myObj.printMember() myObj.createClassMember() myObj.printMember() myObj.printStaticMember() It prints this: class member instance member instance member class member But when I do this: myObj.createInstanceMember() myObj.printMember() myObj.createClassMember() myObj.printMember() myObj.printStaticMember() It prints: instance member instance member class member Here, when I call createInstanceMember() first, printMember() can never print class member. And it can print class member, as long as createInstanceMember() is not called. So, even though I understand why this behavior is happening, I feel its a bit weird and somewhat inconsistent in language design perspective. Why certain variable reference should access different memory locations based on order of execution sequence of other statements? Is there any specific reason / design choice, why python designers chose to make it that way? Or I am interpreting it plain wrong? PS: In classical OOP languages, say in Java, this is not at all the case. There, static members are operated very differently, albeit more consistently (or its just my head dictating Java's behavior is more consistent). In Java, we cannot have instance and static member with same name.
has comment: http://stackoverflow.com/comment/91750410
answer count: 0
upvote count: 3
tagged with: java
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91750485

mask
tags question: http://stackoverflow.com/q/52411321
type: Tag
tag name: mask
tags question: http://stackoverflow.com/q/52427905
tags question: http://stackoverflow.com/q/52289146

http://stackoverflow.com/q/52404998
type: AnsweredQuestion
upvote count: 3
duplicate of: http://stackoverflow.com/q/23887881
has body: This is probably quite simple, but I'm new to pandas. I need to repeat a dataframe n times. My current dataframe looks like: df = 0 0 1 60 2 300 3 320 For example, for n=3, my desired output is: new_df = 0 0 1 60 2 300 3 320 4 0 5 60 6 300 7 320 8 0 9 60 10 300 11 320
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/52405033
tagged with: pandas
score: 3
downvote count: 0
answer count: 1
favorite count: 0
tagged with: repeat
tagged with: python
linked to: http://stackoverflow.com/q/23887881
accepted answer: http://stackoverflow.com/a/52405033
has title: Pandas: repeat dataframe n times

http://stackoverflow.com/q/52306852
has title: python modify mutable iterator
tagged with: python
tagged with: generator
has comment: http://stackoverflow.com/comment/91560967
downvote count: 1
has answer: http://stackoverflow.com/a/52306914
type: AnsweredQuestion
has body: The code is like following: f=open('test.txt') file=iter(f) When I do next(file) It will print line by line of file. But when I modified the test.txt file and saved it, the next(file) still printed the original file content. Does iterator store the complete file in the memory? If not why the content of the file didn't get updated?
upvote count: 5
type: Question
answer count: 2
tagged with: iterator
has comment: http://stackoverflow.com/comment/91561846
accepted answer: http://stackoverflow.com/a/52306914
score: 4
has comment: http://stackoverflow.com/comment/91561268
favorite count: 0
possible better answer: http://stackoverflow.com/a/52307305
has answer: http://stackoverflow.com/a/52307305

http://stackoverflow.com/comment/91740613
type: Comment
comment on: http://stackoverflow.com/a/52398103
score: 0
has text: yea i fixed it im just not sure how to mark this as resolved
type: AnswerComment

http://stackoverflow.com/a/75159587
has body: Here's an option that retains everything in the input URL (just adds or updates the auth), using stdlib only: from urllib.parse import urlparse, urlunparse def inject_auth_to_url(url: str, user: str, password: str) -> str: parsed = urlparse(url) # works no matter if the original url had a user/pass or not domain = parsed.netloc.split("@")[-1] domain = f"{user}:{password}@{domain}" unparsed = (parsed[0], domain, parsed[2], parsed[3], parsed[4], parsed[5]) return urlunparse(unparsed)
answers question: http://stackoverflow.com/q/52359488
score: 0
type: Answer

http://stackoverflow.com/comment/91552615
comment on: http://stackoverflow.com/a/52302316
type: AnswerComment
score: 0
has text: colons should be use in C language. Python language uses indentation
type: Comment

http://stackoverflow.com/comment/91799097
comment on: http://stackoverflow.com/a/52418792
score: 0
type: AnswerComment
type: Comment
has text: Thank you Mark, so I'm wondering why my code doesn't seem to return me the correct (at least I think it is) 0x8A CRC code. Here's the code: import crc8 hash = crc8.crc8() hash.update("0x001123321CAC233F25473DB7E2C56DB5DFFB48D2B060D0F5A71096E00000000000000000C58A".encode('utf-8')) print( hash.hexdigest() ) Is there somenthing I'm doing wrong?

http://stackoverflow.com/comment/91568911
comment on: http://stackoverflow.com/q/52291458
type: Comment
type: QuestionComment
has text: @DanielR. Thanks for letting me know about the parser. I have edited my post and added some content of files.
score: 0

http://stackoverflow.com/comment/91553945
score: 0
type: Comment
type: QuestionComment
has text: `(a < 4.9)&(a>1.5)` yields `True` where it meets the conditions. `((a < 4.9)&(a>1.5)).any()` yields `True` if, as you asked, *anywhere in a list it does not meet the condition*.
comment on: http://stackoverflow.com/q/52303086

http://stackoverflow.com/q/52365257
downvote count: 2
upvote count: 1
tagged with: python
tagged with: regex
tagged with: whitespace
type: Question
score: -1
has answer: http://stackoverflow.com/a/52365474
has answer: http://stackoverflow.com/a/52365521
answer count: 2
has body: I have this line as string: '10 NGBSDN60AQ\n Adafazef ajlafea jhaze 20 SSB 30BA\nqdfqd 40 ON 300 30\n' My Regex is r'[0-9]{2,3}[\s]+[A-Z0-9\s]{6,12}\\n{1}' It identifies: 10 NGBSDN60AQ\n 20 SSB 30BA\n 40 ON 300 30\n but i dont want last one, 40 ON 300 30\n I'd like to know how to get the second part of my regular expression string between 6 and 12 characters (numbers or letters) that allows only one whitespace or not.
linked to: http://stackoverflow.com/q/21722081
has comment: http://stackoverflow.com/comment/91674936
favorite count: 0
has comment: http://stackoverflow.com/comment/91675029
has title: regular expression for string allowing one whitespace
has comment: http://stackoverflow.com/comment/91674856
type: UnansweredQuestion

http://stackoverflow.com/comment/91537207
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52294681
has text: @MaccenWright You can use the same approach to search for the time `td`

http://stackoverflow.com/comment/91689928
has text: `from django.shortcuts import render, redirect`
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52372636

http://stackoverflow.com/a/52388156
answers question: http://stackoverflow.com/q/52388005
downvote count: 0
has comment: http://stackoverflow.com/comment/91721552
type: Answer
has comment: http://stackoverflow.com/comment/91721402
score: 2
upvote count: 2
has body: You can using bdate_range, also I corrected your input , since the most of MonthEnd is early than the MonthBegin [len(pd.bdate_range(x,y))for x,y in zip(df['MonthBegin'],df['MonthEnd'])] Out[519]: [16, 21, 22, 23, 20]

http://stackoverflow.com/comment/91788169
score: 0
comment on: http://stackoverflow.com/q/52420164
has text: That is the dirty fix i want to implement. I know that the way i am making it right now is not the way it should be made but not my saying in this... Trying to wrap it in a try catch (example in question) i receive that error message and i don't know what to do because if i don't use the wrapper it works fine... and i cannot share code due to proxy :/
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91536857
score: 0
has text: Can you please show dummy examples of your two dictionaries? The formatting of your question makes it difficult to understand what you need.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52294603

http://stackoverflow.com/comment/91656561
comment on: http://stackoverflow.com/a/52355862
has text: print(row[0]) is right above the if condition, so it should get run regardless of the outcome of if row[0] == key
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91685708
comment on: http://stackoverflow.com/q/52370491
score: 0
has text: The double softmax: `logits_l = tf.layers.dense(dense, num_labels, activation=tf.nn.softmax)`, then you again perform `softmax_cross_entropy_with_logits`. This is different, and since it performs better, it is also interesting :)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52327787
has body: I am trying to pass a dynamically generated list of date variables into a multi-process pool. When I ask for specific dates from data_2_days() the multi-process works fine, but if I generate the string using data_start_and_end() I get: ValueError: need more than 1 value to unpack I believe the string returned is enclosed in quotes and this is what is causing the issue. Whats the best way to generate the list of date variables to pass into the multi-process pool ? Thanks def data_start_and_end(start_date,end_date): start_date = DateTime.strptime(start_date, '%Y-%m-%d') end_date = DateTime.strptime(end_date, '%Y-%m-%d') no_days = (end_date-start_date).days date_str = "(" # date_end_str = x = 0 while x &lt;= no_days : if x ==0: date = start_date if date.month &lt; 10: month_str = "0"+str(date.month) else: month_str = date.month if date.day &lt; 10: day_str = "0"+str(date.day) else: day_str = date.day date_str = date_str + "['"+ str(date.year) + "','" + str(month_str) + "','" + str(day_str) +"']," # print date_str date = date + TimeDelta(days=1) x=x+1 date_str = date_str[:-1] + ")" print date_str # dates = return(date_str) def data_2_days(): data = ( \ ['2018','01','01'], \ ['2018','01','02']) return(data) def figure_probs_mp(start_date,end_date): data = ZZ_MP_data_lists.data_start_and_end(start_date,end_date) pool = multiprocessing.Pool(36) pool.map(figure_probs, data) pool.close() pool.join() figure_probs_mp(start_date,end_date)
score: 0
answer count: 1
tagged with: multiprocess
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52329290
has title: Pass Dynamically Generated List to multiprocess
type: Question

http://stackoverflow.com/a/52282419
upvote count: 1
type: Answer
downvote count: 0
score: 1
has body: [i.update({w:int(k)}) for i in l for w,k in i.items()] it the second loop is only looping over one key set, so take the two loops with gram of salt :)
answers question: http://stackoverflow.com/q/52282066

http://stackoverflow.com/comment/91625084
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52338668
has text: This is close, however it's removing all words in the text field. I need to keep all of the text and keep all rows where values in my list exist.

http://stackoverflow.com/comment/91759482
has text: Thank you so much sir. I really appreciate this answer!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52395612

http://stackoverflow.com/comment/91583865
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52307057
has text: Thanks for your answer, but I'm trying to implement it without using libraries. It can be good to implement in other languages.
score: 0

http://stackoverflow.com/comment/91583570
score: 1
comment on: http://stackoverflow.com/q/52318117
has text: Instead of trying to detect an exit on failure, why not use a context manager that detects uncaught exceptions (which includes `SystemExit`)?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91690226
comment on: http://stackoverflow.com/q/52372690
has text: I apologize, since I have been learning python from past couple weeks, I am clueless which direction to go. If I know what to look into I will look into it. I deeply apologize, I asked a question without working on it much.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52367279
has answer: http://stackoverflow.com/a/69128397
accepted answer: http://stackoverflow.com/a/52367354
possible better answer: http://stackoverflow.com/a/52367702
tagged with: python
type: AnsweredQuestion
has body: I have a problem with this Python script. I'm attempting to pass the values from a list that has home strings in it. I've attached the script. In this command page = requests.get("https://www.google.dz/search?q=lista[url]") I have to put what I'm looking for on google after the search?q=. I want to search multiple keyword, so I made a list. I don't how to pass the values from the list in that command... import requests import re from bs4 import BeautifulSoup lista = [] lista.append("Samsung S9") lista.append("Samsung S8") lista.append("Samsung Note 9") list_scrape = [] for url in lista: page = requests.get("https://www.google.dz/search?q=lista[url]") soup = BeautifulSoup(page.content) links = soup.findAll("a") for link in soup.find_all("a",href=re.compile("(?&lt;=/url\?q=) (htt.*://.*)")): list_scrape.append(re.split(":(?=http)",link["href"].replace("/url?q=",""))) print(list_scrape) Thank you!
score: 1
upvote count: 1
has title: How to pass the value from a list in a url string
type: Question
linked to: http://stackoverflow.com/q/5607551
has answer: http://stackoverflow.com/a/52367354
answer count: 3
downvote count: 0
tagged with: url
has answer: http://stackoverflow.com/a/52367702
has comment: http://stackoverflow.com/comment/91678780
favorite count: 0
linked to: http://stackoverflow.com/q/2602043
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/91678796

http://stackoverflow.com/comment/91605548
score: 0
type: AnswerComment
has text: I want to add this a = min([k[1] for k in points if k[0] = start[0]]) and using it to compare with current[h], but this recursively functions so I can not add command above to the code because Points will be [ ].So how can I solve this problem?
type: Comment
comment on: http://stackoverflow.com/a/52311625

http://stackoverflow.com/a/62845579
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52378761
downvote count: 0
has body: I had a similar error but with "Fused conv implementation does not support..." instead of "Generic conv implementation does not support..." as the error message. It turned out to be a TensorFlow version issue for me too -- version 1.13.2 was what I needed. To fix it, I did this BEFORE doing "import tensorflow as tf": !pip install tensorflow==1.13.2 This solved it for me.
score: 1

http://stackoverflow.com/comment/91633791
type: QuestionComment
has text: Works for me too. By the way, why have you used `plt.show()` twice?
score: 0
comment on: http://stackoverflow.com/q/52342124
type: Comment

http://stackoverflow.com/a/52377897
has comment: http://stackoverflow.com/comment/91702444
has body: import numpy as np import cv2 # Load an color image in grayscale img = cv2.imread('captcha.jpg',0) #display image in window #cv2.imshow('image',img) #@param - windowname, image to be displayed horizontal_inv = cv2.bitwise_not(img) #perform bitwise_and to mask the lines with provided mask masked_img = cv2.bitwise_and(img, img, mask=horizontal_inv) #reverse the image back to normal masked_img_inv = cv2.bitwise_not(masked_img) kernel = np.ones((5,5),np.uint8) dilation = cv2.dilate(masked_img_inv,kernel,iterations = 3) # to remove blackline noise cv2.imwrite("result1.jpg", dilation) ret,thresh2 = cv2.threshold(dilation,254,255,cv2.THRESH_BINARY_INV) thresh2=cv2.bitwise_not(thresh2) # cv2.imshow("masked img", masked_img_inv) cv2.imwrite("result2.jpg", thresh2) cv2.waitKey(0) # time for window to show image in milliseconds - 0 is infinite wait cv2.destroyAllWindows() Let me know if you have future queries.
accepted answer of: http://stackoverflow.com/q/52374197
has comment: http://stackoverflow.com/comment/91702307
answers question: http://stackoverflow.com/q/52374197
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91702660
downvote count: 0
score: 8
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/91702555
has comment: http://stackoverflow.com/comment/91702766

http://stackoverflow.com/comment/91574093
has text: Seriously? Changing the question when you've already checked an answer?
score: 1
comment on: http://stackoverflow.com/q/52312950
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91541358
comment on: http://stackoverflow.com/q/52296723
has text: `InputType` is one of two types defined in `cStringIO`. Presumably you have a `OutputType` instance instead.
type: Comment
type: QuestionComment
score: 1

geopandas
tags question: http://stackoverflow.com/q/52318187
type: Tag
tags question: http://stackoverflow.com/q/52335450
tags question: http://stackoverflow.com/q/52428311
tags question: http://stackoverflow.com/q/52306635
tags question: http://stackoverflow.com/q/52335737
tags question: http://stackoverflow.com/q/52371968
tag name: geopandas

http://stackoverflow.com/comment/91723438
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52384271
has text: I want these numbers to be thousand-separated in the input

http://stackoverflow.com/comment/91608172
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52330621
has text: Thanks for the warm welcome, norok2! I hope the above helps?

http://stackoverflow.com/comment/91768624
comment on: http://stackoverflow.com/a/52412271
score: 0
type: Comment
has text: @justengel A GUI can be part of a script, and for any widget to show up it needs a QApplication, so what you point out is not correct. I agree with you that the solution is QDialog but its explanation stinks.
type: AnswerComment

http://stackoverflow.com/q/52341391
answer count: 2
upvote count: 0
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/52341441
type: AnsweredQuestion
has title: obtain parameters from another parameters
has body: How to convert parameters bigger than a certain number into 1 and smaller than a certain number into 0. For exmaple, I set parameters model.distance = Param(model.dc,model.location,domain=NonNegativeReals) param distance := DC1 Shelter1 0.61 DC1 Shelter2 3.32 DC1 Shelter3 9.5 DC1 Shelter4 6.52 DC2 Shelter1 6.04 DC2 Shelter2 0.51 DC2 Shelter3 1.34 DC2 Shelter4 6.06 ; How could I obtain a new parameters say model.a that is (threshold = 2): DC1 Shelter1 0 DC1 Shelter2 1 DC1 Shelter3 1 DC1 Shelter4 1 DC2 Shelter1 1 DC2 Shelter2 0 DC2 Shelter3 0 DC2 Shelter4 1 I know it's an easy question, but I'm new to pyomo &amp; python. Thanks
has answer: http://stackoverflow.com/a/52341441
downvote count: 1
has answer: http://stackoverflow.com/a/52341908
type: Question
accepted answer: http://stackoverflow.com/a/52341908
score: -1
tagged with: pyomo

http://stackoverflow.com/comment/91756050
type: QuestionComment
comment on: http://stackoverflow.com/q/52406104
score: 0
has text: i tried it too. but it shows me some error like writer object has no attribute DictWriter. can you please show me how can i do that. with the above code csv_column1=[head1, head2,head3] csv_column2=[head21, head22,head23] ..etc
type: Comment

http://stackoverflow.com/q/52391688
has body: I'm facing an exception similar to this one and I'm trying to handle it based on the error itself. The problem is that pyhive.exc.OperationalError is very generic and handles errors from timeouts to non-existent tables so I would need the exact value from the errorMessage part in order to handle each error type differently, like if it's a timeout, wait and retry; if it's something else, handle it differently and so on. If I catch the error as except OperationalError as e, how would I extract the errorMessage part? I could parse the string representation (e.__str__()) but that seems weird as I'm sure there's a proper way.
has comment: http://stackoverflow.com/comment/99695122
type: Question
has title: Python/PyHive - extract specific error message from exception
has answer: http://stackoverflow.com/a/69669067
score: 2
has answer: http://stackoverflow.com/a/56563753
downvote count: 0
answer count: 3
tagged with: pyhive
tagged with: python
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/56630231
type: UnansweredQuestion
tagged with: error-handling

http://stackoverflow.com/q/52396387
has answer: http://stackoverflow.com/a/52398920
favorite count: 0
has comment: http://stackoverflow.com/comment/91745203
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91745236
tagged with: python
tagged with: openpyxl
has comment: http://stackoverflow.com/comment/91738199
downvote count: 1
has title: Iterating through top row of excel sheet
tagged with: excel
type: Question
score: -1
has body: I have the following section of code which is using openpyxl to search through the top row of a spreadsheet and find the first element that does not contain a value. It returns the following error when I run it. Is there a better way to do this? Or how do I get rid of the error? val = "something" j = 1 titleIndex = None while val != None: val = lecture['%s1' % chr(ord('@') + j)].internal_value print val print j j += 1 else: titleIndex = '%s1' % chr(ord('@') + j - 1) File "C:\Users\ecustodio\Documents\Python Scripts\ExcelIterate.py", line 14, in set_title val = lecture['%s1' % chr(ord('A') + j)].internal_value File "C:\Users\ecustodio\AppData\Local\Continuum\anaconda2\lib\site-packages\openpyxl\worksheet\worksheet.py", line 345, in getitem min_col, min_row, max_col, max_row = range_boundaries(key) File "C:\Users\ecustodio\AppData\Local\Continuum\anaconda2\lib\site-packages\openpyxl\utils\cell.py", line 135, in range_boundaries raise ValueError("{0} is not a valid coordinate or range") ValueError: {0} is not a valid coordinate or range
linked to: http://stackoverflow.com/q/42974450
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/91534697
has text: Actually i m a beginner and i am trying to understand this code.h is h = success.stdout.decode('utf-8').lstrip('#')
comment on: http://stackoverflow.com/q/52293248
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52285755
has answer: http://stackoverflow.com/a/52285805
downvote count: 0
has body: I am trying to web scrape from this address: https://www.pro-football-reference.com/boxscores/ It is a page of game scores for American Football. I want to get the date, winner, and loser of each game. I have no problem accessing the date, however can not figure out how to isolate and grab the team names for the winners and losers. What I have so far... from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup #assigning url my_url = 'https://www.pro-football-reference.com/boxscores/' # opening up connection, grabbing the page uClient = uReq(my_url) page_html = uClient.read() uClient.close() # html parsing page_soup = soup(page_html,"html.parser") games = page_soup.findAll("div",{"class":"game_summary expanded nohover"}) for game in games: date_block = game.findAll("tr",{"class":"date"}) date_val = date_block[0].text winner_block = game.findAll("tr",{"class":"winner"}) #here I need a line that returns the game winner, e.g. "Philadelphia Eagles" loser = game.findAll("tr",{"class":"loser"}) And here is the relevant html... Sep 6, 2018 Atlanta Falcons 12 Final Philadelphia Eagles 18 PassYds Ryan-ATL 251 RushYds Ajayi-PHI 62 RecYds Jones-ATL 169 I get an error saying the ResultSet object has no attribute "td". Any help would be greatly appreciated
has answer: http://stackoverflow.com/a/52285951
favorite count: 0
has answer: http://stackoverflow.com/a/52285855
tagged with: http://stackoverflow.com/tag/html
tagged with: python
answer count: 4
type: AnsweredQuestion
tagged with: web-scraping
upvote count: 1
accepted answer: http://stackoverflow.com/a/52285951
type: Question
has title: web scraping with python. can't access td element
has answer: http://stackoverflow.com/a/52285962
score: 1
possible better answer: http://stackoverflow.com/a/52285805

http://stackoverflow.com/a/52333196
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52331326
has comment: http://stackoverflow.com/comment/91630436
has body: Basically, sum up per user, then average (mean) up per gender. In one line print(df.groupby(['Gender','Username']).sum()['Price'].reset_index()'Gender','Price'.groupby('Gender').mean()) Or in some lines df1 = df.groupby(['Gender','Username']).sum()['Price'].reset_index() df2 = df1'Gender','Price'.groupby('Gender').mean() print(df2) Some notes, I read your example from the clipboard import pandas as pd df = pd.read_clipboard() which required a separator or the item names to be without spaces. I put an extra space into space lord for the test. Normally, you should provide an example file good enough to do the test, so you'd need one with at least one female in.
upvote count: 1
type: Answer

http://stackoverflow.com/a/61768723
has body: The LSTM model requires a 3D input in the form of [samples, time steps, features] When defining the first layer of our LSTM model, we need to specify only the time steps and features. Even though this may seem 2D it is actually 3D as the samples size i.e. batch size is specified at the time of model fit. features = x_train_d.shape[1] Hence, we first need to reshape our input in the 3D format: x_train_d = np.reshape(x_train_d, (x_train_d.shape[0], 1, x_train_d.shape[1])) Here goes the LSTM first layer: model.add(LSTM(5,input_shape=(1, features),activation='relu')) And the model fit specifies the samples=50 as expected by LSTM model.fit(x_train_d,y_train_d.values,batch_size=50,epochs=100) For the question asked with variable length inputs, there is a discussion initiated at https://datascience.stackexchange.com/questions/26366/training-an-rnn-with-examples-of-different-lengths-in-keras
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52388831
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91776327
type: Comment
has text: Mmmm... However they can always modify the data of the other supervisors, and of the other users present in the auth_user
comment on: http://stackoverflow.com/a/52416447
score: 0
type: AnswerComment

http://stackoverflow.com/a/52547559
accepted answer of: http://stackoverflow.com/q/52388831
type: Answer
answers question: http://stackoverflow.com/q/52388831
has body: I believe the input shape for Keras should be: input_shape=(number_of_samples, nb_time_steps, max_nb_features). And most often nb_time_steps = 1 P.S.: I tried solving a very similar problem for an internship position (but my results turned out to be wrong). You may take a look here: https://github.com/AbbasHub/Deep_Learning_LSTM/blob/master/2018-09-22_Multivariate_LSTM.ipynb (see if you can spot my mistake!)
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52422266
linked to: http://stackoverflow.com/q/21405267
has comment: http://stackoverflow.com/comment/91792829
type: Question
tagged with: html-table
has answer: http://stackoverflow.com/a/52423033
tagged with: css-selectors
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91792545
tagged with: python
has comment: http://stackoverflow.com/comment/91792833
has comment: http://stackoverflow.com/comment/91790206
accepted answer: http://stackoverflow.com/a/52423033
score: 2
upvote count: 2
tagged with: selenium
has body: I have multiple cases of table rows from which I want to extract data: Case 1 Onsite Service After Remote Diagnosis April 19, 2014 April 19, 2017 Case 2 CAR October 15, 2016 October 15, 2017 Onsite Service After Remote Diagnosis October 15, 2016 October 15, 2019 Case 3 NBD ProSupport July 16, 2008 July 15, 2011 Onsite Service After Remote Diagnosis July 16, 2008 July 15, 2011 The information that I need to be extracted is on the rows that contain "Onsite Service After Remote Diagnosis" on the second td, which will be for every case the date on the right of the row Expected output: April 19, 2017 October 15, 2017 July 15, 2011 My code: from selenium import webdriver import time from openpyxl import load_workbook driver = webdriver.Chrome() def scrape(codes): dates = [] for i in range(len(codes)): driver.get("https://www.dell.com/support/home/us/en/19/product-support/" "servicetag/%s/warranty?ref=captchasuccess" % codes[i]) # Solve captcha manually if i == 0: print("You now have 120\" seconds to solve the captcha") time.sleep(120) print("120\" Passed") # Extract data expdate = driver.find_element_by_css_selector("#printdivid &gt; div &gt; div.not-annotated.hover &gt; table:nth-child(3) &gt; tbody &gt; tr &gt; td:nth-child(3)") print(expdate.get_attribute('innerText')) driver.close() codes = ['159DT3J', '15FDBG2', '10V8YZ1'] scrape(codes) My output: April 19, 2014 October 15, 2016 July 16, 2008 Taken from the first row that appears and the first td I've tried changing tbody &gt; tr &gt; td:nth-child(3)but identifying based on the text would be better and avoid errors.
type: AnsweredQuestion
has title: Identify table row and table data - CSS Selector Python

http://stackoverflow.com/comment/91752254
type: Comment
type: QuestionComment
has text: can you try https://stackoverflow.com/a/46967289/2425654 and pass only options
score: 0
comment on: http://stackoverflow.com/q/52391198

python-datetime
tag name: python-datetime
tags question: http://stackoverflow.com/q/52416332
tags question: http://stackoverflow.com/q/52296599
type: Tag

http://stackoverflow.com/a/52365029
score: 1
downvote count: 1
upvote count: 2
has body: Of course not this, but try globals (in def use locals): for i in range(1,5): vect = globals()['vect_%s'%i] print(vect) Although still the most pythonic way is using @Oscar's solution
answers question: http://stackoverflow.com/q/52364934
has comment: http://stackoverflow.com/comment/91674987
type: Answer

http://stackoverflow.com/q/52397450
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91850365
tagged with: python
score: 7
has comment: http://stackoverflow.com/comment/91973353
has comment: http://stackoverflow.com/comment/129952712
upvote count: 7
tagged with: tensorflow
tagged with: celery
type: Question
has answer: http://stackoverflow.com/a/74678560
has comment: http://stackoverflow.com/comment/91781762
has comment: http://stackoverflow.com/comment/91781872
has title: Celery worker running tensorflow unable to create CUDA event
linked to: http://stackoverflow.com/q/63645357
downvote count: 0
answer count: 1
has body: I am loading tensorflow model to the celery worker but when I try to run a task on the worker, it shows the following error: [2018-09-19 10:29:39,753: INFO/MainProcess] Received task: analyze_atom[f6bb76cc-aa16-4761-a7cf-0ed111886ff8] [2018-09-19 10:29:41,198: WARNING/ForkPoolWorker-2] paper checkpoint1 takes 1.433300495147705 senconds 2018-09-19 10:29:41.318467: E tensorflow/core/grappler/clusters/utils.cc:81] Failed to get device properties, error code: 3 2018-09-19 10:29:42.650529: E tensorflow/stream_executor/event.cc:40] could not create CUDA event: CUDA_ERROR_NOT_INITIALIZED [2018-09-19 10:29:42,673: ERROR/MainProcess] Process 'ForkPoolWorker-2' pid:3782 exited with 'signal 11 (SIGSEGV)' [2018-09-19 10:29:42,704: ERROR/MainProcess] Task handler raised error: WorkerLostError('Worker exited prematurely: signal 11 (SIGSEGV).',) Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/billiard/pool.py", line 1223, in mark_as_worker_lost human_status(exitcode)), billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 11 (SIGSEGV). This is a tensorflow model and when the celery is started the model is loaded successfully on GPU, here is the work started log: totalMemory: 15.90GiB freeMemory: 15.61GiB 2018-09-19 10:35:38.431559: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1435] Adding visible gpu devices: 0 2018-09-19 10:35:38.793007: I tensorflow/core/common_runtime/gpu/gpu_device.cc:923] Device interconnect StreamExecutor with strength 1 edge matrix: 2018-09-19 10:35:38.793054: I tensorflow/core/common_runtime/gpu/gpu_device.cc:929] 0 2018-09-19 10:35:38.793063: I tensorflow/core/common_runtime/gpu/gpu_device.cc:942] 0: N 2018-09-19 10:35:38.793487: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1053] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 15131 MB memory) -&gt; physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:08.0, compute capability: 6.0) 2018-09-19 10:3…
favorite count: 0

sentence-similarity
tags question: http://stackoverflow.com/q/52300725
tag name: sentence-similarity
type: Tag

http://stackoverflow.com/q/52398903
answer count: 2
has title: Scipy poisson distribution with an upper limit
downvote count: 0
tagged with: statistics
has answer: http://stackoverflow.com/a/52412376
possible better answer: http://stackoverflow.com/a/52412778
has answer: http://stackoverflow.com/a/52412778
accepted answer: http://stackoverflow.com/a/52412376
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: I am generating a random number using scipy stats. I used the Poisson distribution. Below is an example: import scipy.stats as sct A =2.5 Pos = sct.poisson.rvs(A,size = 20) When I print Pos, I got the following numbers: array([1, 3, 2, 3, 1, 2, 1, 2, 2, 3, 6, 0, 0, 4, 0, 1, 1, 3, 1, 5]) You can see from the array that some of the number,such as 6, is generated. What I want to do it to limit the biggest number(let's say 5), i.e. any random number generated using sct.poisson.rvs should be equal or less than 5, How can I tweak my code to achieve it. By the way, I am using this in Pandas Dataframe.
score: 7
has comment: http://stackoverflow.com/comment/91743836
tagged with: poisson
upvote count: 7
tagged with: scipy
type: Question

http://stackoverflow.com/q/52374493
has comment: http://stackoverflow.com/comment/91775808
has body: I am trying to train some 200 pairs of images using siamese CNNs using Keras and notice that the validation accuracy doesn't change through the epochs. Train on 144 samples, validate on 16 samples Epoch 1/20 144/144 [==============================] - 51s 352ms/step - loss: 0.3041 - accuracy: 0.4375 - val_loss: 0.4816 - val_accuracy: 0.5000 Epoch 2/20 144/144 [==============================] - 56s 387ms/step - loss: 0.2819 - accuracy: 0.5208 - val_loss: 0.4816 - val_accuracy: 0.5000 Epoch 3/20 144/144 [==============================] - 47s 325ms/step - loss: 0.2784 - accuracy: 0.4861 - val_loss: 0.4816 - val_accuracy: 0.5000 Epoch 00003: ReduceLROnPlateau reducing learning rate to 0.0001500000071246177. Epoch 4/20 144/144 [==============================] - 50s 349ms/step - loss: 0.2865 - accuracy: 0.4306 - val_loss: 0.4816 - val_accuracy: 0.5000 Epoch 5/20 144/144 [==============================] - 54s 377ms/step - loss: 0.2936 - accuracy: 0.4375 - val_loss: 0.4815 - val_accuracy: 0.5000 Epoch 00005: ReduceLROnPlateau reducing learning rate to 4.500000213738531e-05. Epoch 6/20 144/144 [==============================] - 50s 349ms/step - loss: 0.2980 - accuracy: 0.4097 - val_loss: 0.4815 - val_accuracy: 0.5000 Epoch 7/20 144/144 [==============================] - 47s 324ms/step - loss: 0.2824 - accuracy: 0.4931 - val_loss: 0.4815 - val_accuracy: 0.5000 Epoch 00007: ReduceLROnPlateau reducing learning rate to 1.3500000204658135e-05. Epoch 8/20 144/144 [==============================] - 48s 336ms/step - loss: 0.2888 - accuracy: 0.4722 - val_loss: 0.4815 - val_accuracy: 0.5000 Epoch 9/20 144/144 [==============================] - 45s 315ms/step - loss: 0.2572 - accuracy: 0.5417 - val_loss: 0.4815 - val_accuracy: 0.5000 Epoch 00009: ReduceLROnPlateau reducing learning rate to 4.050000006827758e-06. Epoch 10/20 144/144 [==============================] - 45s 313ms/step - loss: 0.2827 - accuracy: 0.5139 - val_loss: 0.4815 - val_accuracy: 0.5000 Epoch 11/20 144/144 [==========…
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91695523
tagged with: python
has title: Validation accuracy doesnt change though epochs, but training accuracy improves
tagged with: conv-neural-network
type: Question
tagged with: keras

http://stackoverflow.com/comment/91598595
comment on: http://stackoverflow.com/a/52325755
score: 0
type: Comment
type: AnswerComment
has text: JSON is meant for texts. You can encode images into texts with [`base64`](https://docs.python.org/3/library/base64.html) if you insist though.

http://stackoverflow.com/a/52403439
answers question: http://stackoverflow.com/q/52402837
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91751310
has body: You input has to be like below: lst = ({'data':['SymbolA','SymbolB', 'SymbolC', 'SymbolN']}) print pd.DataFrame(lst)

http://stackoverflow.com/comment/139695189
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79216115
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).
score: 1

http://stackoverflow.com/comment/91608012
comment on: http://stackoverflow.com/q/52330667
type: Comment
type: QuestionComment
has text: You should not be altering the list length while iterating over it. Instead you should build a new list with the items you want to keep
score: 3

http://stackoverflow.com/q/52367854
has title: Fastest way to read binary file with 2d array with fixed number of columns but unknown rows
answer count: 1
has body: I have a binary files that has saved values of a 2d array. All values are saved in double format (8bytes) The data is written to the file row by row. I want to read the file as fast as possible without knowing how many rows the file has. I am doing it this way, but I was wondering if there is a faster method than this: with open("myfile", "rb") as f: byte = f.read(8) while byte != "": # Do stuff with byte. byte = f.read(8)
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/52367893
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52367893
type: Question

http://stackoverflow.com/a/52418829
type: Answer
has body: Update: As stated in the comments this should work now: Up until very recently images in existing files were not preserved. You need >= 2.5.5 for this. The doc states for older versions: openpyxl does currently not read all possible items in an Excel file so images and charts will be lost from existing files if they are opened and saved with the same name. There are several bug issues about this (here, here, here) One comment in the issues is using win32com as a workaround to copy the sheet with the image to a different file.
score: 1
has comment: http://stackoverflow.com/comment/91781092
answers question: http://stackoverflow.com/q/52414544
has comment: http://stackoverflow.com/comment/91864237
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/91662543
type: Comment
has text: @Bazingaa but I do disagree with the beginner comment as to say that someone using a `for` loop , `enumerate` ,`pop` and `insert` can't use just a `for` loop
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52358882

http://stackoverflow.com/q/52342209
downvote count: 2
has answer: http://stackoverflow.com/a/52342366
linked to: http://stackoverflow.com/q/6473679
tagged with: python
upvote count: 6
type: AnsweredQuestion
has title: Matrix transpose without numpy, error: list index out of range
type: Question
has body: I wanted to do the transpose of a matrix. I don't want to use numpy. I am getting the following error, (below code). Any help is appreciated matrix = [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]] transposed = [] for i in range(7): new=[] for row in matrix: new.append(row[i]) transposed.append(lst) print(transposed) error: --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-106-856d3ec27942&gt; in &lt;module&gt;() 6 new=[] 7 for row in matrix: ----&gt; 8 new.append(row[i]) 9 transposed.append(lst) 10 print(transposed) IndexError: list index out of range
accepted answer: http://stackoverflow.com/a/52342366
score: 4
answer count: 3
possible better answer: http://stackoverflow.com/a/52342301
favorite count: 0
duplicate of: http://stackoverflow.com/q/6473679
has answer: http://stackoverflow.com/a/52342301
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52342323

http://stackoverflow.com/q/52324800
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/52326956
answer count: 2
has body: I'm trying to return both count (the number of neighbors) and ind (indices of said neighbors) but I can't unless I call query_radius twice, which although computationally intensive, is actually faster for me in Python than iterating through and counting the sizes of each row in ind! This seems terribly inefficient so I wonder is there a way to just return them both in one call? I tried to access the count and ind objects of tree after calling query_radius but it doesn't exist. There's no efficient way to do this in numpy, is there? &gt;&gt;&gt; array = np.array([[1,2,3], [2,3,4], [6,2,3]]) &gt;&gt;&gt; tree = KDTree(array) &gt;&gt;&gt; neighbors = tree.query_radius(array, 1) &gt;&gt;&gt; tree.ind Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'sklearn.neighbors.kd_tree.KDTree' object has no attribute 'ind' &gt;&gt;&gt; tree.count Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'sklearn.neighbors.kd_tree.KDTree' object has no attribute 'count'
downvote count: 0
tagged with: scikit-learn
tagged with: kdtree
favorite count: 0
has answer: http://stackoverflow.com/a/52326956
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/91906249
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52326463
score: 1
has title: Scikit-learn KDTree query_radius return both count and ind?
has answer: http://stackoverflow.com/a/52326463
upvote count: 1

http://stackoverflow.com/a/52327316
accepted answer of: http://stackoverflow.com/q/52327134
has comment: http://stackoverflow.com/comment/91601958
answers question: http://stackoverflow.com/q/52327134
has comment: http://stackoverflow.com/comment/91795494
has comment: http://stackoverflow.com/comment/91803993
upvote count: 2
type: AcceptedAnswer
has body: from timeit import default_timer as timer test = [x for x in range(1000)] count = 0 start = timer() len(test) end = timer() print(end - start) start = timer() for i in test: count += 1 end = timer() print(end - start) Returns: 2.643069343567298e-06 213.7110354941546e-06 If test = "This is a test string." Returns: 2.2654880087719696e-06 1.0572277374269745e-05
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/52358549
tagged with: file-io
answer count: 1
tagged with: text-files
accepted answer: http://stackoverflow.com/a/52358587
tagged with: python
has body: I have the below program wherein I am trying to convert text files to a character unigram (feature vector) and writing the output to a text file. I am printing the output on the console and writing it to a text file at the same time, however, printing to the console will print all the records while printing to the file prints only the last iteration of the filename in articles. Should I be using an array for rawcu? My Code: for fileName in allarticles: rawcu = [0.0]*95 out=open("CASIS-25fvs_rawcu.txt","w") fileOpen = open(fileName) charFrequency = {} for line in fileOpen: for letter in line: if((ord(letter) &gt; 31) and ord(letter) &lt; 127): rawcu[ord(letter)-32] += 1.0 print rawcu print &gt;&gt; out, rawcu
type: AnsweredQuestion
has title: Printing to a file in python
type: Question
has answer: http://stackoverflow.com/a/52358587
score: 0

http://stackoverflow.com/comment/91536524
has text: Please close `fp1` and `fp2` ;)
score: 1
comment on: http://stackoverflow.com/a/52291504
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91771271
has text: Thank you for your answer, Dave.
type: Comment
score: 2
comment on: http://stackoverflow.com/a/52410514
type: AnswerComment

http://stackoverflow.com/comment/91726473
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52390465
has text: Do you know what to do in this case? @Andersson

http://stackoverflow.com/q/52413023
type: AnsweredQuestion
score: 1
has title: Pandas Change Index Pro's & Con's
tagged with: dataframe
upvote count: 1
has comment: http://stackoverflow.com/comment/91769704
type: Question
has body: I have to make hundreds of dataframes, and index them all starting at 1 as opposed to 0. I have found three functional approaches, but I'm not certain if there is a optimal/preferable approach. Can anyone give me insight if there are any pros and cons of the following options?: df.index += 1 df.index = df.index + 1 df.index = range(1,len(df)+1)
downvote count: 0
has answer: http://stackoverflow.com/a/52413092
has comment: http://stackoverflow.com/comment/91769907
tagged with: pandas
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91769719
tagged with: python
accepted answer: http://stackoverflow.com/a/52413092

http://stackoverflow.com/comment/91947825
type: QuestionComment
has text: Sorry I wasn't clear: I can customize the font used in my terminal emulator, but the ones you mention do not change the width of the box drawing characters. Things do look different, but none display box drawing characters at single width. I wonder if pursuing this is worth the effort compared to simple cross-platform bitmap drawing :)
comment on: http://stackoverflow.com/q/52429607
score: 0
type: Comment

http://stackoverflow.com/q/52318603
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91584789
has body: I'm trying to find a way to avoid a double for loop in python by using numpy, but I'm not sure if it's even possible. I have two 3D matrices that I've flatten into two 2D matrices using numpy's flatten(), now I need to do a calculation with each row, to every row. Basically each row represents an image, and I'm doing a series of calculations to two vectors, and returning a scalar. A [a, b, c, d] A' [a, b, c, d] B [e, f, g, h] B' [e, f, g, h] C [i, j, k, l] C' [i, j, k, l] D [m, n, o, p] D' [m, n, o, p] result [AA' AB' AC' AD'] [BA' BB' BC' BD'] [CA' CB' CC' CD'] [DA' DB' DC' DD'] EDIT: Here's my double for loop aMatrix = np.array([[5, 3, 2, 1, 4, 2], [7, 0, 3, 5, 7, 9], [9, 8, 0, 2, 4, 8], [3, 5, 2, 0, 1, 9], [7, 7, 4, 1, 7, 6], [5, 9, 8, 9, 6, 1]]) find_distance_of_two_sets(aMatrix, aMatrix) def find_distance_of_two_sets(aMatrix, bMatrix): distance = np.zeros((6, 6)) i = 0 for a in aMatrix: j = 0 for b in bMatrix: distance[i][j] = euclidean_distance(a, b) j += 1 i += 1 outputFile = open('distanceMatrix', 'wb') np.save(outputFile, distance) def euclidean_distance(a, b): return np.sqrt(np.sum(np.square(np.subtract(a, b)))) and if you were to print the result it would be [[ 0. 9.38083152 9.05538514 8.18535277 7. 11.87434209] [ 9.38083152 0. 9.79795897 10.14889157 8.66025404 13.82027496] [ 9.05538514 9.79795897 0. 7.93725393 5.91607978 13.52774926] [ 8.18535277 10.14889157 7.93725393 0. 8.36660027 15.03329638] [ 7. 8.66025404 5.91607978 8.36660027 0. 10.67707825] [11.87434209 13.82027496 13.52774926 15.03329638 10.67707825 0. ]]
favorite count: 0
has title: Python avoiding double for loop
has comment: http://stackoverflow.com/comment/91584834
accepted answer: http://stackoverflow.com/a/52318674
linked to: http://stackoverflow.com/q/15831766
has comment: http://stackoverflow.com/comment/91584760
upvote count: 2
duplicate of: http://stackoverflow.com/q/15831766
tagged with: python
duplicate of: http://stackoverflow.com/q/18014889
has comment: http://stackoverflow.com/comment/91584840
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52318674
type: Question
tagged with: numpy
duplicate of: http://stackoverflow.com/q/52030458
has comment: http://stackoverflow.com/comment/91585494

http://stackoverflow.com/q/52321938
type: AnsweredQuestion
type: Question
tagged with: pyqt
has title: Call def and change Qt and variable based on passed value
has body: In the example below I would need to do this function about 7 times. The only change would be instead of strength it would be perception for example. Anywhere you see the word strength, it would need to be changed, including in the Qt functions such as self.strengthSpin.setValue(). Is there a way to do this without copying/pasting the code several times? if stat == "strength": newValue = self.strengthSpin.value() varChange = newValue - strength if varChange &gt; 0: if statPoints - varChange &gt;= 0: statPoints -= varChange self.statPointsLCD.setProperty("intValue", statPoints) strength += varChange self.strengthSpin.setValue(strength) else: print("not enough stat points") self.strengthSpin.setValue(strength) else: if newValue &gt; 0: print("should be adding") statPoints -= varChange self.statPointsLCD.setProperty("intValue", statPoints) strength += varChange self.strengthSpin.setValue(strength) else: print("must be at least 0") self.strengthSpin.setValue(strength)
has answer: http://stackoverflow.com/a/52352500
accepted answer: http://stackoverflow.com/a/52352500
score: 0
answer count: 1
tagged with: python
tagged with: pyqt5

http://stackoverflow.com/comment/91771081
has text: @yodish yes, it splits on whitespace and gives a list
comment on: http://stackoverflow.com/a/52413650
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/q/52296723
upvote count: 1
has title: StringIO() argument 1 must be string or buffer, not cStringIO.StringIO
downvote count: 1
has comment: http://stackoverflow.com/comment/91541551
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52296905
has body: I have a function that's reading a content object into a pandas dataframe. import pandas as pd from cStringIO import StringIO, InputType def create_df(content): assert content, "No content was provided, can't create dataframe" if not isinstance(content, InputType): content = StringIO(content) content.seek(0) return pd.read_csv(content) However I keep getting the error TypeError: StringIO() argument 1 must be string or buffer, not cStringIO.StringIO I checked the incoming type of the content prior to the StringIO() conversion inside the function and it's of type str. Without the conversion I get an error that the str object does not have a seek function. Any idea whats wrong here?
tagged with: cstringio
type: Question
has comment: http://stackoverflow.com/comment/91541358
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52296905
tagged with: python-2.7
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/91541647
tagged with: python
tagged with: stringio

http://stackoverflow.com/q/52364612
downvote count: 0
has comment: http://stackoverflow.com/comment/91676747
has answer: http://stackoverflow.com/a/52364795
has answer: http://stackoverflow.com/a/52386301
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/52364795
has comment: http://stackoverflow.com/comment/91676393
upvote count: 2
tagged with: for-loop
tagged with: pandas
tagged with: try-except
has comment: http://stackoverflow.com/comment/91674571
has comment: http://stackoverflow.com/comment/91676707
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52364736
accepted answer: http://stackoverflow.com/a/52386301
has title: How to continue a loop after catching exception in try ... except
tagged with: python
has body: I am reading a big file in chunks and I am doing some operations on each of the chunks. While reading one of get them I had the following message error: pandas.errors.ParserError: Error tokenizing data. C error: Expected 26 fields in line 15929977, saw 118 which means that one of my file lines doesn't follow the same format as the others. What I thought I could do was to just omit this chunk but I couldn't get a way to do it. I tried to do a try/except block as follows: data = pd.read_table('ny_data_file.txt', sep=',', header=0, encoding = 'latin1', chunksize = 5000) try: for chunk in data: # operations except pandas.errors.ParseError: # Here is my problem What I have written here is my problem is that if the chunk is not well parsed, my code will automatically go to the exception not even entering the for loop, but what I would like is to skip this chunk and move forward to the next one, on which I would like to perform the operations inside the loop. I have checked on stackoverflow but I couldn't find anything similar where the try was performed on the for loop. Any help would be appreciated. UPDATE: I have tried to do as suggested in the comments: try: for chunk in data: #operations except pandas.errors.ParserError: # continue/pass/handle error But still is not cathching the exception because as said the exception is created when getting the chyunk out of my data not when doing operations with it.
has comment: http://stackoverflow.com/comment/91678325
has comment: http://stackoverflow.com/comment/91676092
answer count: 4
has answer: http://stackoverflow.com/a/52364910
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/91535533
comment on: http://stackoverflow.com/q/52293909
type: QuestionComment
has text: .. and call it with `q[1]()` - you have to figure out how to provide parameters to your function as well if needed
type: Comment
score: 1

http://stackoverflow.com/q/52299505
tagged with: tensorflow-datasets
favorite count: 0
type: Question
upvote count: 2
tagged with: python
answer count: 1
has body: I have a dataset created from one tfrecord file. This dataset contains 5 different classes. Now I want to create batches with a fixed number of elements (8 for example) from each batch. So it should create batches of 40 elements containing 8 elements of each class. Is this possible with tf.data?
has answer: http://stackoverflow.com/a/52300835
tagged with: tensorflow
score: 2
has title: Split tensorflow dataset in dataset per class
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91547123
type: QuestionComment
has text: I am not expert in python requests, but shorturl you got looks like a wrong url to me. you probably need to do something like r = requests.get(url_link, params=payload)
comment on: http://stackoverflow.com/q/52299690
score: 0
type: Comment

http://stackoverflow.com/q/52324666
score: 0
tagged with: multithreading
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/52339046
tagged with: pandas
answer count: 1
has body: I have a large dataframe and a column "image" in it, the data in "image" is the file name(with extension equals "jpg" or "jpeg") of a large amount of files. Some files exist with right extension, but others not. So, I have to check whether "image" data is right, but it takes 30 seconds with single-threading, I then decide to do this with multi-threading. I have written a code with Python(3.6.5) to check this, it runs well when I execute it on Command Line, but error occurs when I execute it on Spyder(3.2.8), how could I do to avoid this? Here is my code: # -*- coding: utf-8 -*- import multiprocessing import numpy as np import os import pandas as pd from multiprocessing import Pool #some large scale DataFrame, the size is about (600, 15) waferDf = pd.DataFrame({"image": ["aaa.jpg", "bbb.jpeg", "ccc.jpg", "ddd.jpeg", "eee.jpg", "fff.jpg", "ggg.jpeg", "hhh.jpg"]}) waferDf["imagePath"] = np.nan #to parallelize whole process def parallelize(func, df, uploadedDirPath): partitionCount = multiprocessing.cpu_count() partitions = np.array_split(df, partitionCount) paras = [(part, uploadedDirPath) for part in partitions] pool = Pool(partitionCount) df = pd.concat(pool.starmap(func, paras)) pool.close() pool.join() return df #check whether files exist def checkImagePath(partialDf, uploadedDirPath): for index in partialDf.index.values: print(index) if os.path.exists(os.path.join(uploadedDirPath, partialDf.loc[index, ["image"]][0].replace(".jpeg\n", ".jpeg"))): partialDf.loc[index, ["imagePath"]][0] = os.path.join(uploadedDirPath, partialDf.loc[index, ["image"]][0].replace(".jpeg\n", ".jpeg")) elif os.path.exists(os.path.join(uploadedDirPath, partialDf.loc[index, ["image"]][0].replace(".jpeg\n", ".jpg"))): partialDf.loc[index, ["imagePath"]][0] = os.path.join(uploadedDirPath, partialDf.loc[index, ["image"]][0].replace(".jpeg\n", ".jpg")) print(partialDf) return partialDf if __name__ == '__main__': waferDf = parallelize(checkImagePath, waferDf, "/eap/uploadedFiles/") print(waferDf…
linked to: http://stackoverflow.com/q/48078722
type: UnansweredQuestion
tagged with: python
has title: Python: Error occurs on Spyder when modifing pandas DataFrame with multi-threading
linked to: http://stackoverflow.com/q/419163

http://stackoverflow.com/q/52394543
tagged with: python-3.x
score: 51
downvote count: 3
has body: I am unable to locate package python-pip: Reading package lists... Done Building dependency tree Reading state information... Done E: Unable to locate package python3-pip How can I resolve this problem?
tagged with: apt
tagged with: python
has answer: http://stackoverflow.com/a/60832178
has answer: http://stackoverflow.com/a/54982567
has answer: http://stackoverflow.com/a/57134641
has title: "E: Unable to locate package python3-pip"
has comment: http://stackoverflow.com/comment/134623017
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91734425
has answer: http://stackoverflow.com/a/58072486
type: Question
has answer: http://stackoverflow.com/a/52394612
has answer: http://stackoverflow.com/a/60694330
upvote count: 54
has comment: http://stackoverflow.com/comment/134622881
has comment: http://stackoverflow.com/comment/99651874
has comment: http://stackoverflow.com/comment/134622934
answer count: 7
has answer: http://stackoverflow.com/a/54285599
favorite count: 0

scrapy
tags question: http://stackoverflow.com/q/52368631
tags question: http://stackoverflow.com/q/52357029
tags question: http://stackoverflow.com/q/52379948
tags question: http://stackoverflow.com/q/52303882
tags question: http://stackoverflow.com/q/52294394
tags question: http://stackoverflow.com/q/52289675
tags question: http://stackoverflow.com/q/52297395
tags question: http://stackoverflow.com/q/52399825
tags question: http://stackoverflow.com/q/52276179
tags question: http://stackoverflow.com/q/52380423
tags question: http://stackoverflow.com/q/52361531
tags question: http://stackoverflow.com/q/52298479
tags question: http://stackoverflow.com/q/52418478
tags question: http://stackoverflow.com/q/52291998
tags question: http://stackoverflow.com/q/52428670
tags question: http://stackoverflow.com/q/52372698
tags question: http://stackoverflow.com/q/52272406
tags question: http://stackoverflow.com/q/52330140
tags question: http://stackoverflow.com/q/52291557
tags question: http://stackoverflow.com/q/52420801
tags question: http://stackoverflow.com/q/52305689
tags question: http://stackoverflow.com/q/52394954
tags question: http://stackoverflow.com/q/52395837
tags question: http://stackoverflow.com/q/52365494
tags question: http://stackoverflow.com/q/52399981
tags question: http://stackoverflow.com/q/52425741
tags question: http://stackoverflow.com/q/52410068
tags question: http://stackoverflow.com/q/52273393
tags question: http://stackoverflow.com/q/52382517
tags question: http://stackoverflow.com/q/52338156
tags question: http://stackoverflow.com/q/52283158
tags question: http://stackoverflow.com/q/52382206
tags question: http://stackoverflow.com/q/52383001
tag name: scrapy
tags question: http://stackoverflow.com/q/52377159
tags question: http://stackoverflow.com/q/52285525
tags question: http://stackoverflow.com/q/52310852
tags question: http://stackoverflow.com/q/52395894
tags question: http://stackoverflow.com/q/52406933
tags question: http://stackoverflow.com/q/52349807
tags question: http://stackoverflow.com/q/52359645
tags question: http://stackoverflow.com/q/52407467
tags question: http://stackoverflow.com/q/52333133
type: Tag
tags question: http://stackoverflow.com/q/52362938
tags question: http://stackoverflow.com/q/52343374
tags question: http://stackoverflow.com/q/52325790

http://stackoverflow.com/q/52360506
linked to: http://stackoverflow.com/q/1207406
has comment: http://stackoverflow.com/comment/91665416
tagged with: loops
has comment: http://stackoverflow.com/comment/91665429
type: Question
has body: If i have large list which runs in millions of items, i want to iterate through each of them. Once i use the item it will never be used again, so how do i delete the item from the list once used? What is the best approach? I know numpy is fast and efficient but want to know how it can be done using normal list. mylst = [item1, item2,............millions of items] for each_item in mylist: #use the item #delete the item to free that memory
has title: How to remove an item in list once used from a large list in python to save the memory?
answer count: 3
has answer: http://stackoverflow.com/a/52360544
has answer: http://stackoverflow.com/a/52364226
tagged with: python-3.x
tagged with: memory-management
has answer: http://stackoverflow.com/a/52360652
type: UnansweredQuestion
score: 0
tagged with: python

http://stackoverflow.com/comment/92236830
type: Comment
has text: if I want to show the output of model and show the decoder and w_predictor on test data, how can I do it?
type: AnswerComment
comment on: http://stackoverflow.com/a/52489422
score: 0

http://stackoverflow.com/comment/91505517
comment on: http://stackoverflow.com/q/52277797
has text: What is the reason to use `"text.usetex": False,` here? Should that not be `True`? If you use `\usepackage{tgheros}` in a latex document, does it affect math font? (i.e. would something like `This is text and $a= \sin{b}$` be printed in the same sans-serif font in a pure latex document?)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52401930
type: Answer
score: 0
has body: Maybe you could do data1 = data.fillna('0') to force the substitution value (0) to be a string.
answers question: http://stackoverflow.com/q/52401762

http://stackoverflow.com/comment/91740941
has text: without child means contours that does not have any child under it (or inner most contour)
score: 0
comment on: http://stackoverflow.com/q/52397592
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91668499
has text: [https://stackoverflow.com/questions/16015548/tool-for-sending-multipart-form-data-request](https://stackoverflow.com/questions/16015548/tool-for-sending-multipart-form-data-request) this can help to test your api with postman
comment on: http://stackoverflow.com/q/52361130
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52316409
type: Question
has answer: http://stackoverflow.com/a/52316650
has answer: http://stackoverflow.com/a/52316813
has comment: http://stackoverflow.com/comment/91580472
upvote count: 5
has title: How to skip indexes?
answer count: 8
has answer: http://stackoverflow.com/a/52316518
has answer: http://stackoverflow.com/a/52316747
score: 4
favorite count: 0
has answer: http://stackoverflow.com/a/52316658
has answer: http://stackoverflow.com/a/52316540
has answer: http://stackoverflow.com/a/52316612
tagged with: python
tagged with: list
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52316515
downvote count: 1
tagged with: skip
has body: I am having an issue with last part of a code I'm creating. I am trying to, for example, make the list iterate to item 3 normally, but then check if the item is 3 and other condition (which doesn't matter right now), then change the index to iterate from example 10. I made a lot of attempts but it doesn't seem to work. li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] for i in range(0,len(li)): print(i) if i == 3: #along with other condition def g(li): global i i = li[9] g() print(i)

http://stackoverflow.com/q/52355260
has answer: http://stackoverflow.com/a/52355369
has comment: http://stackoverflow.com/comment/91655178
answer count: 1
tagged with: regex
has comment: http://stackoverflow.com/comment/91655151
has comment: http://stackoverflow.com/comment/91655193
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91655277
upvote count: 1
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/91655143
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/91655131
type: Question
has title: grouping a list into sublists, breaked by alphabet elements in python
accepted answer: http://stackoverflow.com/a/52355369
has comment: http://stackoverflow.com/comment/91655231
tagged with: string
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/91655208
has comment: http://stackoverflow.com/comment/91655138
has comment: http://stackoverflow.com/comment/91655159
has body: I have a list in python that is mixed: some elements are numeric and some are alphabet. For example: l = ['999','123','hello','222','333','444','bye'] I want to split this list to a lists that are seperated by the elements that are all alphabet: ['999','123','hello'], ['222','333','444','bye'] For ['hello', '123', 'test', 'test', '456', 'test', '789'] The output will be: ['hello'],['123','test'],['test'],['456','test'],['789'] Every element is all alphabet or all numeric. What is the most pythonic way to do so?

http://stackoverflow.com/comment/91821543
has text: Then please post an answer that explains how you solved it.
score: 3
comment on: http://stackoverflow.com/q/52404923
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52386680
type: AnsweredQuestion
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/52386744
answer count: 1
has comment: http://stackoverflow.com/comment/91717760
downvote count: 0
has body: I'm trying to add an object/dictionary to my already existing dictionary based on key, but the already existing object is being overwritten. What I am trying to achieve: 'CXR100': {'MeSH': {u'major': [u'normal'], u'minor': []}, {u'major': [u'normal'], u'minor': []}} What I am getting: 'CXR100': {'MeSH': {u'major': [u'normal'], u'minor': []}} My code: data = dict() for record in records['list']: if data.get(record['uid']): data[record['uid']]['MeSH'].update(record['MeSH']) # have tried: data[record['uid']]['MeSH'] += {'MeSH': record['MeSH']} else: data[record['uid']] = {'MeSH': record['MeSH']} print(data) I have been programming PHP/Laravel for the past two years and have totally lost my feeling for Python. I hope someone can give me directions on what I am doing wrong.
has comment: http://stackoverflow.com/comment/91717728
has comment: http://stackoverflow.com/comment/91717750
favorite count: 0
has title: Add object to dictionary based on key in Python 2
has answer: http://stackoverflow.com/a/52386744
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91717701

http://stackoverflow.com/q/52302442
has body: I want to add several arrays together but they have different sizes. I think the code should look like this commission = [0.55,0.03,0.025,0.025] interest = [0.05,0.045] premium = 10 fund = [] for i = 1 to 120 fund[i] = premium * (1 - commission[i]) + interest[i] * fund[i-1] But the issue is that this will go out of bounds. I just want the commission[4] to extend to all 120 periods. Same with the interest array. Usually in the past I have used the "upperbound" command within the for loop to do this calculation. How is it done in python? Thanks
has answer: http://stackoverflow.com/a/52302622
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91553646
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52302547
accepted answer: http://stackoverflow.com/a/52302622
has title: Python adding arrays of different sizes - upper bound?
score: 0
possible better answer: http://stackoverflow.com/a/52302547

http://stackoverflow.com/comment/91670585
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52361731
has text: In the [release notes of Django 2.0](https://docs.djangoproject.com/en/2.1/releases/2.0/#features-removed-in-2-0) they're mentioning about this ***`on_delete`*** argument
score: 0

http://stackoverflow.com/comment/91700398
type: AnswerComment
comment on: http://stackoverflow.com/a/52377796
type: Comment
score: 1
has text: Also `and` rather than `or`.

http://stackoverflow.com/a/52500213
accepted answer of: http://stackoverflow.com/q/52371384
answers question: http://stackoverflow.com/q/52371384
type: Answer
upvote count: 2
score: 2
type: AcceptedAnswer
has body: Ok, I found out what the problem was. When Django's default username field is instantiated, it adds a MaxLengthValidator to its list of validators and uses the max_length argument to set its limit_value. When I monkey patched the User class, I overwrote the max_length and help_text of the username field, but I didn't take care of the validator. Adding this line under my custom User class fixed the issue: User._meta.get_field('username').validators[1].limit_value = 255 The amount of time I spent debugging this is probably a good illustration of how monkey patching is usually a bad idea.
downvote count: 0

http://stackoverflow.com/comment/91739850
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52387141
has text: @BillyJhon i just edited the code for your requirement of excluding ids listed in cite_id
type: AnswerComment

http://stackoverflow.com/comment/91655143
score: 0
type: Comment
type: QuestionComment
has text: @JonClements - Yes
comment on: http://stackoverflow.com/q/52355260

http://stackoverflow.com/a/52403472
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52403400
upvote count: 2
type: AcceptedAnswer
has body: Use Index.isin with MultiIndex: df = df1[df1.index.isin(df2.set_index(['i1','i2']).index)] Alternative: df = df1[df1.index.isin(pd.MultiIndex.from_arrays([df2['i1'], df2['i2']]))] Or use merge, join - but necessary reset and set index: df = df1.reset_index().merge(df2).set_index(['i1', 'i2']) df = df2.join(df1, on=['i1', 'i2'], how='inner').set_index(['i1', 'i2']) print (df) c i1 i2 a1 b1 1 a3 b3 3
type: Answer
answers question: http://stackoverflow.com/q/52403400
score: 2

http://stackoverflow.com/q/52429323
tagged with: pandas
has body: I'm trying to figure out how to bold the column and row labels for a matplotlib table I'm making. I've gone through the different table properties, and I can figure out how to style the individual cells, but not the actual columns or row labels. Further, I'm not able to find out how to bold anything.. just font size, actual font, and color. Any help? import numpy as np import matplotlib.pyplot as plt import pandas as pd fig, axs =plt.subplots(figsize = (10,6)) clust_data = np.random.random((10,3)) collabel=("col 1", "col 2", "col 3") axs.axis('tight') axs.axis('off') df = pd.DataFrame(np.random.randn(10, 4), columns=['a','b','c','d'], index = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']) table = axs.table(cellText=df.values, colLabels = df.columns, rowLabels = df.index, loc='center') plt.show() EDIT: Figured it out, though it's kind of clunky. You can find the columns/row labels in the "celld" property. You can then set it to bold using .set_text_props(fontproperties = FontProperties(weight = 'bold'). i.e. import numpy as np import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties import pandas as pd fig, axs =plt.subplots(figsize = (10,6)) clust_data = np.random.random((10,3)) collabel=("col 1", "col 2", "col 3") axs.axis('tight') axs.axis('off') df = pd.DataFrame(np.random.randn(10, 4), columns=['a','b','c','d'], index = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']) table = axs.table(cellText=df.values, colLabels = df.columns, rowLabels = df.index, loc='center') P = [] for key, cell in table.get_celld().items(): row, col = key P.append(cell) for x in P[40:]: x.set_text_props(fontproperties=FontProperties(weight='bold')) plt.show()
answer count: 1
has answer: http://stackoverflow.com/a/52433450
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 6
tagged with: matplotlib
has title: Python: making column/row labels of matplotlib table bold
type: Question
downvote count: 0
score: 6

wagtail
tag name: wagtail
tags question: http://stackoverflow.com/q/52415442
tags question: http://stackoverflow.com/q/52324240
tags question: http://stackoverflow.com/q/52405554
type: Tag

gridlines
tags question: http://stackoverflow.com/q/52331662
tag name: gridlines
type: Tag

http://stackoverflow.com/q/52332554
has title: VSCode: The term 'python' is not recognized...but py works
tagged with: vscode-code-runner
has answer: http://stackoverflow.com/a/75774439
has answer: http://stackoverflow.com/a/62424686
has answer: http://stackoverflow.com/a/76043045
tagged with: visual-studio-code
tagged with: automation
has body: I just installed python on VS Code and I can't run any python code using python command. python command: Running the code seems to run python command by default and it does not recognize it. When I right click and choose Run Code it complains: 'python' is not recognized as an internal or external command, operable program or batch file Same goes for manually running python main.py. When I open an elevated PowerShell and run python, it complains: python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + python + ~~~~~~ + CategoryInfo : ObjectNotFound: (python:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException py command: It doesn't try to use py command but it recognizes it. And when I manually call py main.py, it works. When I manually do >py main.py it writes my Goodbye, World! Question: How can I make it compile/run in VS Code simply by using the CodeRunner's right-click feature (Run Code)? I already have both Python folder and its Scripts folder in PATH. I'm using VS Code 1.27.2 and I have installed python 3.7.0 on my machine and have checked its installer checkbox for adding the environment variables automatically. (PATH is ok) I also installed : ms-python.python and tht13.python and formulahendry.code-runner extensions on the VS Code. This is my main.py code: print("Goodbye, World!")
has comment: http://stackoverflow.com/comment/91760476
has answer: http://stackoverflow.com/a/69425524
accepted answer: http://stackoverflow.com/a/52408379
score: 32
possible better answer: http://stackoverflow.com/a/55945820
has answer: http://stackoverflow.com/a/55945820
has answer: http://stackoverflow.com/a/78735757
has comment: http://stackoverflow.com/comment/106611378
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/61078797
has answer: http://stackoverflow.com/a/75670267
downvote count: 0
has answer: http://stackoverflow.com/a/79081197
favorite count: 0
has answer: http://stackoverflow.com/a/52395181
has answer: http://stackoverflow.com/a/72575567
has comment: http://stackoverflow.com/comment/91620423
type: Question
has comment: http://stackoverflow.com/comment/91612584
tagged with: python
linked to: http://stackoverflow.com/q/5583024
upvote count: 32
has comment: http://stackoverflow.com/comment/91612672
has answer: http://stackoverflow.com/a/52408379
tagged with: build
answer count: 13
has answer: http://stackoverflow.com/a/61876898

http://stackoverflow.com/q/52302853
has comment: http://stackoverflow.com/comment/91553464
tagged with: valueerror
has comment: http://stackoverflow.com/comment/91553512
answer count: 0
has comment: http://stackoverflow.com/comment/91553530
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91553622
has comment: http://stackoverflow.com/comment/91553767
type: Question
has comment: http://stackoverflow.com/comment/91572377
has title: How to resolve "valueError: can not merge DataFrame with instance of type <class 'str'>"?
score: 0
has body: Getting this error valueError: can not merge DataFrame with instance of type with this code: import numpy as np import matplotlib.pyplot as plt import pandas as pd contract = pd.read_csv('4.CONTRACT_0806.csv') contractaff = pd.read_csv('5.CONTRACTAFFILIATE_0806.csv') df1 = pd.DataFrame(contract) df2 = pd.DataFrame(contractaff) mergedf = pd.merge('df1','df2',how = 'outer',left_on=['CONTRACT_CONTRACT_ID']) Why is that?
tagged with: python

http://stackoverflow.com/comment/91659849
comment on: http://stackoverflow.com/q/52357560
has text: @DeepSpace Ah... I was using 3.5.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52410714
tagged with: python-3.x
has body: here's sample code order = 10100 status = 'Shipped' columnname= 'OrderNumber' sql = """SELECT * from orders where %s = %s and status = %s order by %s""" df1 = pd.read_sql_query(sql, cnx, params=[columnname,order, status,columnname]) """SELECT * from orders where 'OrderNumber' = 10100 and status = 'Shipped' order by OrderNumber""" I want to pass variable name and other parameters dynamically. here other parameters passing correctly but columnname parameter i am getting error. as it's passing with quoted string. How to pass parameter without quoted string like below example """SELECT * from orders where OrderNumber = 10100 and status = 'Shipped' order by OrderNumber""" Thanks
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91765348
tagged with: python
has comment: http://stackoverflow.com/comment/91765654
has comment: http://stackoverflow.com/comment/91766489
has comment: http://stackoverflow.com/comment/134824196
has comment: http://stackoverflow.com/comment/91765443
has comment: http://stackoverflow.com/comment/91765332
has comment: http://stackoverflow.com/comment/91765581
answer count: 0
has title: passing variables without quotes in sql query
has comment: http://stackoverflow.com/comment/91765219
type: Question
has comment: http://stackoverflow.com/comment/91765732
has comment: http://stackoverflow.com/comment/91765499
has comment: http://stackoverflow.com/comment/91765333
has comment: http://stackoverflow.com/comment/91765286
tagged with: pandas
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91765240
favorite count: 0

http://stackoverflow.com/a/52325202
answers question: http://stackoverflow.com/q/52323575
type: Answer
downvote count: 0
has body: Here is another one by using sklearn.preprocessing The lines are quite long and not much difference. I don:t know why but produced a similar results. import numpy as np from sklearn.preprocessing import OneHotEncoder sent = ["a", "b", "c", "d", "e", "f", "g"] aaa = len(sent) aa = {x:i for i,x in enumerate(sent)} sentences = ["b", "c", "e"] a = {} for xx in sentences: a[xx] = aa[xx] a = {"a":0, "b":1, "c":2, "d":3, "e":4, "f":5, "g":6} aa =len(a) index = [] for x,y in a.items(): index.append([y]) index = np.asarray(index) enc = OneHotEncoder() enc.fit(index) print(enc.transform([[1], [2], [4]]).toarray()) Output [[0. 1. 0. 0. 0. 0. 0.] [0. 0. 1. 0. 0. 0. 0.] [0. 0. 0. 0. 1. 0. 0.]]
score: 1
upvote count: 1

http://stackoverflow.com/q/52350369
has answer: http://stackoverflow.com/a/52350441
has answer: http://stackoverflow.com/a/52354792
score: 0
has body: print ('please enter a roman numeral') romannum = input() lenrm = len(romannum) total = 0 for i in range (lenrm): numone = 0 numtwo = 0 if (romannum[i]).lower() == 'i': numone = numone + 1 if (romannum[i]).lower() == 'v': numone = numone + 5 if (romannum[i]).lower() == 'x': numone = numone + 10 if (romannum[i + 1]).lower() == 'i': numtwo = numtwo + 1 if (romannum[i + 1]).lower() == 'v': numtwo = numtwo + 5 if (romannum[i + 1]).lower() == 'x': numtwo = numtwo + 10 if numone &lt; numtwo: total = total + (numtwo - numone) else: total = total + numone i += 1 print (total) With an input of xiv, I am getting an error message Traceback (most recent call last): File "C:\Users\poona\Python\roman_numeral_reader.py", line 18, in &lt;module&gt; if (romannum[i + 1]).lower() == 'i': IndexError: string index out of range
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has title: Interpret roman numeral and returns a numerical value
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/52351209
has answer: http://stackoverflow.com/a/52350408
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/q/52411261
answer count: 0
has body: I recently started working with keras and have looked at every available solution but its did not work. I have a simple neural network to compute a tensor value from 5 input constants, and 10 input tensors.This is my neural network, the main input layer inputs 5 constants and tensor input layer inputs 10 tensors: import numpy as np from keras.utils import plot_model from keras.models import Model from keras.layers import Input,Lambda from keras.layers import Dense from keras import backend as K def function(x): #This function is used for the last layer to compute Anisotropic R-S tensor = x[0] constants = x[1] a = K.zeros(shape=(3,3,)) for i in range(10): a = a + constants[:,i]*tensor[:,:,:,i] return a main_input = Input(shape = (5,),name = 'main_input') #The invariant inputs hidden1 = Dense(10,activation = 'relu')(main_input) hidden2 = Dense(10,activation= 'relu')(hidden1) #10 constants tensor_input = Input(shape= (3,3,10,),name = 'tensor_input') output_layer = Lambda(function)([tensor_input,hidden2]) model = Model(inputs = [main_input,tensor_input], outputs = output_layer) print(model.summary()) model.compile(optimizer = 'adam', loss='mean_squared_error', metrics=['accuracy']) plot_model(model, to_file='multilayer_perceptron_graph.png') #Just test inputs and outputs to correct shape I_test = np.ones((120,5)) T_test = np.ones((120,3,3,10)) a_test = np.ones((120,3,3)) model.fit({'main_input': I_test, 'tensor_input': T_test},a_test,epochs=50,batch_size=2) I have used a lambda layer as the output layer. It computes the tensor a as: a = g1*T1 + g2*T2 + ....g10*T10 where g's are constants which are computed from Dense 24 layer. There is no activation here, its simple linear combination. The output a is (3,3) matrix. The input tensors are 10 3*3 tensors, thus shape of I is (129,3,3,10). I am getting the following error whenever batchsize>1: InvalidArgumentError: Incompatible shapes: [2] vs. [2,3,3] [[Node: training_7/Adam/gradients/lambda_12/mul_9_grad/BroadcastGradientAr…
type: UnansweredQuestion
score: 2
downvote count: 0
tagged with: tensorflow
type: Question
upvote count: 2
tagged with: keras
has title: Getting Incompatible shapes error with batch_size>1 with keras
favorite count: 0
tagged with: keras-layer
tagged with: python
tagged with: python-3.x

oauth-2.0
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/52340535
type: Tag

http://stackoverflow.com/q/52352319
has answer: http://stackoverflow.com/a/52352346
score: 0
has body: Can someone please help me? I'm trying to read data from an excel file, save everything into a database file, then query the database and print all the name attributes. I'm using Python with sqlite3. There are special caracters in the strings in my excel, so I'm trying to escape them. I don't need the special characters. I looked for the solution on google, but couldn't find out how to do it. I'm still a beginner at python and databases. I got this error message: When I saved all the data without the "re.escape", I got this error message: OperationalError: near "6": syntax error This is all the content of hamburgers.xlsx: import re import openpyxl import sqlite3 from sqlite3 import Error wb_ins = openpyxl.load_workbook("hamburgers.xlsx") sheet_ins = wb_ins['Hamburger'] try: connection = sqlite3.connect("hamburger.db") print("hamburger.db created") except Error as e: print(e) cursor = connection.cursor() cursor.execute("DROP TABLE IF EXISTS hamburger") sql = """CREATE TABLE hamburger ( last_found Date, name char(10), stored number(4), hamb_id char(30) PRIMARY KEY);""" cursor.execute(sql) for row in sheet_ins.iter_rows(min_row=2, max_row=4): last_found = row[0].value name = re.escape(row[1].value) stored = row[2].value hamb_id= re.escape(row[3].value) cursor.execute("INSERT INTO hamburger VALUES('{lf}', '{n}', '{s}', '{hid}');".format(lf=last_found, n=name, s=stored, hid=hamb_id)) cursor.execute("SELECT name FROM hamburger") name = cursor.fetchall() print(name)
has title: Python code trying to save excel data into database - error escaping special characters
type: Question
tagged with: escaping
accepted answer: http://stackoverflow.com/a/52352346
tagged with: sqlite
answer count: 1
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/52346431
answers question: http://stackoverflow.com/q/52346223
type: Answer
downvote count: 0
has body: You need to add an extra check in your code to exit. if j == len(numList): maxcount = len(resList) value = resList[1] location = i break In your code it'll look like this: import sys import stdio # Ask the user input for the list of integers numList = list(sys.argv[1]) maxcount = 0 value = None location = None i = 1 while i &lt; len(numList) - 1: resList = [] count = 0 # If i &gt; i-1, then we start taking i into the resList if numList[i] &gt; numList[i - 1]: # start counting resList += [numList[i]] # Iterating through the rest of the numbers j = i + 1 while j &lt; len(numList): # If the j element equals the i, then append it to resList if numList[i] == numList[j]: resList += [numList[j]] j += 1 elif numList[i] &lt; numList[j]: # if j element is greater than i, break out the loop i = j break else: # if j element is smaller than i, count equals length of resList count = len(resList) if count &gt; maxcount: maxcount = count value = resList[1] location = i i = j #EXTRA CHECK HERE if j == len(numList): maxcount = len(resList) value = resList[1] location = i break else: # if not greater than the previous one, increment by 1 i += 1 stdio.writeln("The longest continuous plateau is at location: " + str(location)) stdio.writeln("Length is: " + str(maxcount)) stdio.writeln("Number is: " + str(value))
score: 1
has comment: http://stackoverflow.com/comment/91651209
upvote count: 1

http://stackoverflow.com/q/52379697
upvote count: 28
has answer: http://stackoverflow.com/a/52380239
tagged with: python
tagged with: amazon-sns
tagged with: amazon-cloudwatch
type: Question
accepted answer: http://stackoverflow.com/a/52380239
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/62186000
has answer: http://stackoverflow.com/a/52380377
answer count: 3
possible better answer: http://stackoverflow.com/a/62186000
downvote count: 0
has body: I'm trying to parse data with Lambda when an alarm is triggered in Cloudwatch. I am currently using SNS to trigger the lambda; however, I want to know what data is being sent to that Lambda so that I can parse it correctly. How can I read the JSON alarm data that's passed into Lambda by SNS?
tagged with: amazon-web-services
favorite count: 0
score: 28
tagged with: aws-lambda
has title: What is in the JSON payload Cloudwatch sends to SNS? How can I read that data?

http://stackoverflow.com/q/52419851
has comment: http://stackoverflow.com/comment/91783126
tagged with: python
has title: how to make list of files in directory and process them one by one? - Python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91784149
type: Question
tagged with: text
has body: i want to make a list of all text files in a directory. then i want to create separate list of the contents in each file. e.g document1=[] and then document2=[] so on. and then by using document 1 and document 2 keywords i want to calculate term frequency and other processes. code is running but list cant be assigned different names as document1 and so on. import glob import math import re a=0 flist=glob.glob(r'D:/Final Year Project/Development process/Text_data_extraction/MyFolder/*.txt') #get all the files from the d`#open each file &gt;&gt; tokenize the content &gt;&gt; and store it in a set for fname in flist: tfile=open(fname,"r") line=tfile.read() a+=1 line = line.lower() # lowercase line = re.sub("&amp;lt;/?.*?&amp;gt;"," &amp;lt;&amp;gt; ",line) #remove tags line = re.sub("(\\d|\\W)+"," ",line) # remove special characters and digits l_ist = line.split("\n") print 'document' print(l_ist) tfile.close() # close the file print"Number of documents:" print(a)
has answer: http://stackoverflow.com/a/52419996
answer count: 2
has answer: http://stackoverflow.com/a/52419954
score: 0
has comment: http://stackoverflow.com/comment/91782852

http://stackoverflow.com/comment/91614980
type: QuestionComment
comment on: http://stackoverflow.com/q/52333864
score: 1
has text: You can't `print()` an assertion, can you please fix that?
type: Comment

http://stackoverflow.com/a/52396304
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/138520434
answers question: http://stackoverflow.com/q/52396257
type: Answer
accepted answer of: http://stackoverflow.com/q/52396257
has comment: http://stackoverflow.com/comment/91737556
has comment: http://stackoverflow.com/comment/91737485
has comment: http://stackoverflow.com/comment/91737580
score: 0
has body: If you haven't realized by now, ltmemory stands for long term memory, and stmemory stands for short term memory. I haven't yet had a long look at the github code, but I do have a basic understanding of how AlphaZero and reinforcement learning come together (being a chess enthusiast myself). Basically, what makes AlphaZero so strong is that it uses both a long and a short term memory, much like we humans do. By being able to make decisions off of time-local data (i.e. events that have recently happened) and more global data (i.e. the entire game and its outcome), AlphaZero is able to make decisions that will not only benefit it in the short term, but will also benefit it in the long term. Does this make sense or at all answer your question? I sort of typed this quickly and gave a fairly high level description of what was going on. Leave a question comment if there is one part that you want me to go into more detail on.
upvote count: 1

http://stackoverflow.com/a/52346225
downvote count: 0
has body: Link: https://github.com/numpy/numpy/issues/1608 According to the link, this bug was reported and fixed in the 1.13.0 release of Numpy. A quick workaround you can use is: any(elem is None for elem in abc)
accepted answer of: http://stackoverflow.com/q/52345998
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/52345998
score: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/91695878
comment on: http://stackoverflow.com/a/52373253
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/180229/discussion-between-gc5-and-pirsquared).
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91921618
score: 0
comment on: http://stackoverflow.com/q/52423024
type: Comment
has text: Possible duplicate of [Python video is not playing Downloaded by using requests module](https://stackoverflow.com/questions/52417686/python-video-is-not-playing-downloaded-by-using-requests-module)
type: QuestionComment

http://stackoverflow.com/q/52361293
has body: I've seen some snippets of python code in which a loop was written as follows: someList = g.db.execute('SELECT title, body FROM posts') posts = [dict(title=x[0],body=[1]) for x in someList.fetchAll()] What is this kind of loop refered to as? I realize it could be just refered to as a for loop, but the syntax it quite different from a c-based language (shorter and more productive), so I just wondered if have some other name written like this.
possible better answer: http://stackoverflow.com/a/52361337
upvote count: 2
has title: What is a for-loop with the for-loop at the end of it called in python?
score: 0
answer count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/52361337
favorite count: 0
has comment: http://stackoverflow.com/comment/91666874
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/34835951
has answer: http://stackoverflow.com/a/52361317
accepted answer: http://stackoverflow.com/a/52361317
duplicate of: http://stackoverflow.com/q/34835951
type: Question
has comment: http://stackoverflow.com/comment/91666925
has comment: http://stackoverflow.com/comment/91666884

http://stackoverflow.com/comment/91691856
score: 0
type: AnswerComment
has text: Yes, but then I will need to install & configure terminator in every machine that the code is going to be run on. It is many machines that I don't even have access to, so it's not an option
type: Comment
comment on: http://stackoverflow.com/a/52373399

http://stackoverflow.com/comment/91592339
score: 0
type: AnswerComment
type: Comment
has text: Also, even if you had included the function definition of your code, `a = [[]]` before the assignment statement `small = a[0][0]` will still result in `IndexError` exception as `a` is a list that contains an empty list and `a[0][0]` refers to an element that does not exist
comment on: http://stackoverflow.com/a/52322260

http://stackoverflow.com/a/52409340
answers question: http://stackoverflow.com/q/52408993
has body: What you are doing is transposing an array. Use transpose directly. See numpy transpose New_Intensity = np.transpose(Intensity) Here is a demo of what I am suggesting import numpy as np a = np.array([[1,2,3],[4,5,6]]) print(a) [[1 2 3] [4 5 6]] b = np.transpose(a) print(b) [[1 4] [2 5] [3 6]] If you want to do this manually then you can do it this way. # get the size of the matrix size = a.shape() # create the output of the correct size c = np.zeros((size[1],size[0])) # iterate over the range of row values for m in range(size[0]): # iterate over the range of column values for n in range(size[1]): c[n,m]=a[m,n] print(c) [[ 1. 4.] [ 2. 5.] [ 3. 6.]] The result is the same as just using numpy.transpose but with much more typing.
score: 0
type: Answer

http://stackoverflow.com/q/52351936
tagged with: pandas
has body: sht.head() How Can I create a column K containing all non-zero-values from A:J? Expected result would be: K = ["A001", "B001", "C001", "D001", "E001", "A002", ...]
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/52352234
score: -1
type: AnsweredQuestion
has title: How to filter some columns values and generate a new column with these values in Pandas?
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/52351958
type: Question
possible better answer: http://stackoverflow.com/a/52351958
accepted answer: http://stackoverflow.com/a/52352234
answer count: 2

http://stackoverflow.com/q/52379078
type: UnansweredQuestion
tagged with: microsoft-distributed-file-system
tagged with: python
has title: How to keep track of node depth in DFS without recursion(using a stack)?
score: 1
upvote count: 1
type: Question
has body: This is my code snippet for DFS with out recursion in python: def DFS(graph,start,end): explored=[] queue=start if start == end: return "done" while queue: path=queue.pop() node=path[-1] if node not in explored: neighbours=graph[node] for neighbour in neighbours: new_path=list(path) new_path.append(neighbour.name) queue.append(new_path) if neighbour.name== end: return new_path explored.append(node) return "no path" This is how my node looks like: class edge: #def init(): def __init__(self,name,value,depth=0): self.name=name self.value=value self.depth=depth How do I keep track of levels of each node as I've to implement depth limited search without recursion?
has answer: http://stackoverflow.com/a/52379277
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/91558097
type: Comment
type: QuestionComment
has text: Can you provide a sample input data?
score: 1
comment on: http://stackoverflow.com/q/52305296

scrapy-splash
tag name: scrapy-splash
tags question: http://stackoverflow.com/q/52310852
type: Tag

http://stackoverflow.com/a/68028722
upvote count: 1
has body: You would have already found the sol. for getting pod name I am posting here one more. Below you can get pod from a namespace with particular regex (regex = if you want to search specific pod with some pattern). Also you can check if a specific pod Exists or not with below fn. from kubernetes import config , client from kubernetes.client import Configuration from kubernetes.client.api import core_v1_api from kubernetes.client.rest import ApiException from kubernetes.stream import stream import re pod_namespace = "dev_staging" pod_regex = "log_depl" try: config.load_kube_config() c = Configuration().get_default_copy() except AttributeError: c = Configuration() c.assert_hostname = False Configuration.set_default(c) core_v1 = core_v1_api.CoreV1Api() def get_pod_name(core_v1,pod_namespace,pod_regex): ret = core_v1.list_namespaced_pod(pod_namespace) for i in ret.items: #print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name)) pod_name=i.metadata.name if re.match(pod_regex, pod_name): return pod_name def check_pod_existance(api_instance,pod_namespace,pod_name): resp = None try: resp = api_instance.read_namespaced_pod(name=pod_name,namespace=pod_namespace) except ApiException as e: if e.status != 404: print("Unknown error: %s" % e) exit(1) if not resp: print("Pod %s does not exist. Create it..." % pod_name) You can call your Functions as: pod_name=get_pod_name(core_v1,pod_namespace,pod_regex) check_pod_existance(core_v1,pod_namespace,pod_name)
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52329005
score: 1

http://stackoverflow.com/a/52323654
type: Answer
has comment: http://stackoverflow.com/comment/91599562
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52323297
downvote count: 0
has body: The solution was to use integer division in this line: (IMAGE_SIZE//4, IMAGE_SIZE//4, (n if vanilla_architecture else 3*n)), The type error was not due to the tensor but instead that IMAGE_SIZE/4 returned a float

http://stackoverflow.com/comment/91528101
score: 0
type: Comment
type: QuestionComment
has text: There are some odd things here. You're using a ModelViewSet; why are you using a plain Serializer rather than a ModelSerializer?
comment on: http://stackoverflow.com/q/52289385

http://stackoverflow.com/a/52282123
answers question: http://stackoverflow.com/q/52282066
has body: The following works in one line: r = [{'integer':int(x['integer'])} for x in l] print(r) # [{'integer': 1}, {'integer': 2}, {'integer': 3}, {'integer': 4}] This utilizes a dict comprehension inside a list comprehension.
has comment: http://stackoverflow.com/comment/91512687
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/91512450
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91512514

http://stackoverflow.com/q/52353743
tagged with: tree
type: AnsweredQuestion
tagged with: format
has answer: http://stackoverflow.com/a/52353889
tagged with: http://stackoverflow.com/tag/json
has body: I have this tree: Active Mode |___ Local (EU) | |___ &lt;Random String&gt; |___ International (WW) | |___ &lt;Random String&gt; (I want this random string!!!) Passive Mode |___ Local (EU) | |___ &lt;Random String&gt; |___ International (WW) |___ &lt;Random String&gt; But due to circumstances, my python will see it as a flat string: Active Mode Local (EU) &lt;Random String&gt; International (WW) &lt;Random String&gt; (I want this random string!!!) Passive Mode Local (EU) &lt;Random String&gt; International (WW) &lt;Random String&gt; Note: is basically a random string that I don't know what it is. Now it's pretty easy to get the line I want, I just do string.split(\n)[4]. The tricky part is: the parents (Active Mode and Passive Mode) can be shuffled so the Active Mode would be after Passive Mode the children (Local (EU) and International (WW)) can also be shuffled A Parent might be missing or a child might be missing (so there is a chance that there is no Active Mode which means I should get something like None One possible solution I thought of was to somehow convert the flat string into a multi-layer dictionary, list or json but I don't know how am I suppose to do it.
type: Question
accepted answer: http://stackoverflow.com/a/52353889
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91652274
tagged with: string
has comment: http://stackoverflow.com/comment/91652417
has comment: http://stackoverflow.com/comment/91652424
has title: String Manipulation: convert flat string to a tree-like format
tagged with: python

http://stackoverflow.com/comment/91533003
has text: @Ashish that doesn't let you set up TLS_PSK only set the certs
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52281398
score: 0

http://stackoverflow.com/comment/91522578
type: Comment
score: 0
has text: yeah iv tried removing the [str] and just doing [int] but that didnt work either
type: AnswerComment
comment on: http://stackoverflow.com/a/52287356

http://stackoverflow.com/q/52329504
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52338734
has title: How to fill a cell range with a single value with Openpyxl?
accepted answer: http://stackoverflow.com/a/52338734
type: Question
answer count: 1
tagged with: excel-2016
has body: from openpyxl import load_workbook wb = load_workbook('PathToFile') sht = wb['SheetName'] rge = sht['k1:k999'] I would like to fill every cell in "rge" (i.e. k1, k2, ..., k999) with the string "...". I found an easy way with xlwings, but I would prefer to use openpyxl, since openpyxl can be used on both Windows and GNU/Linux: sht.range('k1:k999').value='...'
tagged with: python
favorite count: 0
tagged with: python-3.x
score: 0
tagged with: openpyxl
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/91505350
type: Comment
has text: When using `figsize=(10,10)` does it still report the same `460100x333779` pixels? What does `print(fig.dpi)` result in? Do you get the same error when not using an animation?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52277854

http://stackoverflow.com/comment/91628422
has text: @g_m is correct, that would be the preferred way. note that the reason you're getting the permission denied error is because you're not allowed to open a directory for reading, like you can a file (in python, this is allowed by some OSs and programming languages). a quick google shows python doesn't even expose the underlying unix opendir function like some other scripting languages do.
comment on: http://stackoverflow.com/q/52340654
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52355411
upvote count: 1
has body: The documentation says: The first n_samples % n_splits folds have size n_samples // n_splits + 1, other folds have size n_samples // n_splits, where n_samples is the number of samples. In this case, the dataset is split into 14 folds, with 12 folds having 3 examples each, and 2 folds having 2 examples each. You can see that with your code if you just remove the pointer variable. from sklearn.model_selection import KFold import numpy as np kf_test = KFold(n_splits=14) test_x = np.random.rand(40) for item_t, item_v in kf_test.split(test_x): print(item_t.shape) print(item_v.shape) print(len(item_v) / 40) # test_x
answers question: http://stackoverflow.com/q/52354229
accepted answer of: http://stackoverflow.com/q/52354229
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/91498188
comment on: http://stackoverflow.com/q/52274857
has text: @MVS What is your pandas version.? What is the numpy version.?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52320842
type: Question
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52320950
tagged with: python-2.7
has title: pythonic way to convert lists to class fields
has body: Is there a more pythonic way to distribute the content of multiple lists into fields in multiple structures? Example below using pandas.dataframe import pandas # INPUT files = ['file1.csv','file2.csv','file3.csv','file4.csv', 'file5.csv'] names = ['Cold', 'Hot','Hotter','Hottest','Hottestest'] lines = ['-','-',':','-',':'] colors = ['b','r','r','y','y'] marker = ['','','','o',''] cases = [] for idx,case in enumerate(files): cases.append(pandas.read_csv(fname)) cases[idx].name = names[idx] cases[idx].color = colors[idx] cases[idx].marker = marker[idx] cases[idx].lines = lines[idx]
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52320897
accepted answer: http://stackoverflow.com/a/52320897
possible better answer: http://stackoverflow.com/a/52320950
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/52320969
upvote count: 8
type: Question
has comment: http://stackoverflow.com/comment/91619556
has comment: http://stackoverflow.com/comment/91591750
has title: Matplotlib reports font family 'serif' not found
answer count: 1
score: 8
favorite count: 0
has comment: http://stackoverflow.com/comment/91589635
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52900297
tagged with: python
has comment: http://stackoverflow.com/comment/91590854
downvote count: 0
tagged with: fonts
tagged with: matplotlib
has body: When I try and run, for example: mpl.rcParams['font.family'] = 'serif' plt.rcParams['figure.figsize'] = [15,7] plt.plot(data['flow-time'], data['staticpressurerecovery']) plt.xlabel('Time [s]') plt.ylabel('Static Pressure Recovery [-]') plt.title('McD13_4S3 Plenum: Performance Coefficient ') plt.ylim((0.33, 0.4)) plt.grid() plt.show() in a Jupyter notebook, I get the following error message: C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\font_manager.py:1331: UserWarning: findfont: Font family ['serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) Things I've Tried: Deleting the fontList.cache, fontList.json, and fontList.py3.cache Uncommenting the font family related sections of the matplotlibrc file Uninstalled and reinstalled matplotlib using pip uninstall matplotlib and pip install matplotlib Nothing has solved the issue. The only possible way for me to get different fonts now is to use LaTeX as the backend, but that's slow and unnecessary. Any ideas what I can try next? Edit: I'm using Windows 10, so not using apt-get for me. That seems to be a common fix for these problems, but I can't do it. It appears those solutions just add Microsoft fonts to the Linux font manager, so it's probably not even relevant since I'm already on a Microsoft machine. Minimum working Example: import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np mpl.rcParams['font.family'] = 'serif' mpl.rcParams['font.serif'] = 'Computer Modern' t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2*np.pi*t) plt.plot(t, s) plt.show() In fontList.json, Computer Modern is listed as an available font.

http://stackoverflow.com/q/52303258
has comment: http://stackoverflow.com/comment/91554292
score: 0
answer count: 1
has title: Fast implementation for neighbourhoods in numpy tensor
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91556732
tagged with: python
has body: I have a 3-tensor A in numpy and an index (i,j,k). I need to put in a single (possibly numpy) array arr the linear index of the 'neighborhoods' of (i,j,k), (i.e., the elements (i+i1, j+j1, k+k1), where i1, j1, k2 = -1, 0, 1). I need to do this for every index (i,j,k) of A, so my question is, there is a short and fast way to do this? A toy example: n = 10 dim = (10, 10, 10) i, j, k = (2, 3, 4) res = [] pm = [-1, 0, 1] for i1 in range(3): for j1 in range(3): for k1 in range(3): # ravel_multi_index transforms a multi-index (i,j,k) to the corresponding linear index of a tensor of shape "dim" res.append(np.ravel_multi_index((i + pm[i1], j + pm[j1], k + pm[k1]), dim)) #print... [123, 124, 125, 133, 134, 135, 143, 144, 145, 223, 224, 225, 233, 234, 235, 243, 244, 245, 323, 324, 325, 333, 334, 335, 343, 344, 345] There are 27 neighborhoods. The boundary index has fewer neighborhoods: for example, the coordinate (0, 0, 0) has 8 neighborhoods. As solution, I was thinking in some "traslation" of the neighborhoods to one fixed, but this rapidly become cumbersome.
has comment: http://stackoverflow.com/comment/91555193
has comment: http://stackoverflow.com/comment/91557714
has answer: http://stackoverflow.com/a/52305203
type: Question
tagged with: numpy
tagged with: arrays

http://stackoverflow.com/a/52303974
has body: On inspection of your code, I notice a number of problems: First, you initialize items to a tuple, when it should be a list: items = []. You should change your name property to reflect the name you want on your crawler so you can use it like so: scrapy crawl my_crawler where name = "my_crawler". start_urls is supposed to contain strings, not Request objects. You should change the entry from page to the exact search string you want to use. If you have a number of search strings and want to iterate over them, I would suggest using a middleware. When you try to extract the data from CSS you're forgetting to call extract_all() which would actually transform your selector into string data which you could use. Also, you shouldn't be redirecting to the standard output stream because a lot of logging goes there and it'll make your output file really messy. Instead, you should extract the responses into items using loaders. Finally, you're probably missing the appropriate settings from your settings.py file. You can find the relevant documentation here. FEED_FORMAT = "csv" FEED_EXPORT_FIELDS = ["Field 1", "Field 2", "Field 3"]
answers question: http://stackoverflow.com/q/52303882
type: Answer
score: 0

http://stackoverflow.com/comment/127510670
type: AnswerComment
has text: Glad you figured it out
score: 0
comment on: http://stackoverflow.com/a/52315435
type: Comment

http://stackoverflow.com/q/52421041
has comment: http://stackoverflow.com/comment/91798670
has comment: http://stackoverflow.com/comment/91791176
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52422082
has comment: http://stackoverflow.com/comment/91791195
has body: I want to generate a random sample size of 90 (10+30+50), create a list that holds these 90 randomly generated samples and find the sample median. this is what I'm given: sub_pop = [300, 500, 1000] samplesize = [10, 30, 50] std_list = [40, 50, 60] mean_list = [50, 60, 70] in other words, I want to randomly generate a sub sample size of 10 from sub_pop 300, a sub sample size of 30 from sub_pop 500 and a sub sample size of 50 from sub_pop 1000 and then append the results into a single list. each sub_pop are normally distributed as follows: sub_pop 300 is normally distributed wif std dev 40 and mean 50, sub_pop 500 is normally distributed wif std dev 50 and mean 60 and so on. this is what I've done so far: import numpy as np n_pop = 1800 obs_size = 90 sub_pop = [300, 500, 1000] samplesize = [10, 30, 50] std_list = [40, 50, 60] mean_list = [50, 60, 70] list = [] for i in range(300): list += np.random.normal(loc = 50, scale = 40, size = 10).tolist() for i in range(500): list += np.random.normal(loc = 60, scale = 50, size = 30).tolist() for i in range(1000): list += np.random.normal(loc = 70, scale = 60, size = 50).tolist() list1 = [abs(x) for x in list] print(list1) print(np.median(list1)) is my approach right?
has comment: http://stackoverflow.com/comment/91791427
type: Question
has answer: http://stackoverflow.com/a/52421956
answer count: 2
has comment: http://stackoverflow.com/comment/91796643
has comment: http://stackoverflow.com/comment/91786815
has comment: http://stackoverflow.com/comment/91799366
tagged with: statistics
has comment: http://stackoverflow.com/comment/91798698
score: 0
has title: difference between numpy repeat and this method
has comment: http://stackoverflow.com/comment/91798526

http://stackoverflow.com/q/52397513
has title: What is type <U12?
upvote count: 10
type: Question
score: 9
tagged with: numpy
tagged with: pandas
has answer: http://stackoverflow.com/a/52397572
has body: I was using pandas and numpy to process some data until I got two similar output of arrays: array(['french', 'mexican', 'cajun_creole', ..., 'southern_us', 'italian', 'thai'], dtype='&lt;U12') array(['french', 'mexican', 'cajun_creole', ..., 'jamaican', 'italian', 'thai'], dtype=object) I don't see the difference, what is &lt;U12?
has answer: http://stackoverflow.com/a/77610221
tagged with: types
tagged with: arrays
favorite count: 0
accepted answer: http://stackoverflow.com/a/52397572
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/52397820
has comment: http://stackoverflow.com/comment/106033718
downvote count: 1
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52397820

http://stackoverflow.com/comment/91762536
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52407451
type: Comment
has text: Okay, understood. Thank you very much!